From 0ae7841ef2a230faa9c94b2f602ab7a914b8cdf7 Mon Sep 17 00:00:00 2001 From: Paul Dicker Date: Sun, 1 Apr 2018 13:43:05 +0200 Subject: [PATCH] Also add sample_iter to Rng --- src/lib.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 1c2eecebcf3..4364d5d80c8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -380,6 +380,39 @@ pub trait Rng: RngCore { fn sample>(&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 = 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::>()); + /// + /// // 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>(&'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. ///