Skip to content

Commit

Permalink
Also add sample_iter to Rng
Browse files Browse the repository at this point in the history
  • Loading branch information
pitdicker committed Apr 1, 2018
1 parent b9a2c59 commit 0ae7841
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,39 @@ pub trait Rng: RngCore {
fn sample<T, D: Distribution<T>>(&mut self, distr: D) -> T {
distr.sample(self)
}

/// Create an iterator that generates values using the given distribution.
///
/// # Example
///
/// ```rust
/// use rand::{thread_rng, Rng};
/// use rand::distributions::{Alphanumeric, Range, Uniform};
///
/// let mut rng = thread_rng();
///
/// // Vec of 16 x f32:
/// let v: Vec<f32> = thread_rng().sample_iter(&Uniform).take(16).collect();
///
/// // String:
/// let s: String = rng.sample_iter(&Alphanumeric).take(7).collect();
///
/// // Combined values
/// println!("{:?}", thread_rng().sample_iter(&Uniform).take(5)
/// .collect::<Vec<(f64, bool)>>());
///
/// // Dice-rolling:
/// let die_range = Range::new_inclusive(1, 6);
/// let mut roll_die = rng.sample_iter(&die_range);
/// while roll_die.next().unwrap() != 6 {
/// println!("Not a 6; rolling again!");
/// }
/// ```
fn sample_iter<'a, T, D: Distribution<T>>(&'a mut self, distr: &'a D)
-> distributions::DistIter<'a, D, Self, T> where Self: Sized
{
distr.sample_iter(self)
}

/// Return a random value supporting the [`Uniform`] distribution.
///
Expand Down

0 comments on commit 0ae7841

Please sign in to comment.