diff options
| author | Huon Wilson <dbau.pp+github@gmail.com> | 2013-10-10 14:30:34 +1100 |
|---|---|---|
| committer | Huon Wilson <dbau.pp+github@gmail.com> | 2013-10-23 10:40:06 +1100 |
| commit | 5aaef138ff4d717ab723ac024c94c92539b4daa7 (patch) | |
| tree | bbf1d4b61374d5d5b0b0e39eebc7d84774669835 /src/libstd | |
| parent | 2cd772bdba10ac5b8449595cc218419c33b9bcf4 (diff) | |
| download | rust-5aaef138ff4d717ab723ac024c94c92539b4daa7.tar.gz rust-5aaef138ff4d717ab723ac024c94c92539b4daa7.zip | |
std::rand: Add RandSample for Sample-ing Rand types directly.
Diffstat (limited to 'src/libstd')
| -rw-r--r-- | src/libstd/rand/distributions.rs | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/src/libstd/rand/distributions.rs b/src/libstd/rand/distributions.rs index 845d8bbc952..0ee073a926b 100644 --- a/src/libstd/rand/distributions.rs +++ b/src/libstd/rand/distributions.rs @@ -41,6 +41,20 @@ pub trait IndependentSample<Support>: Sample<Support> { fn ind_sample<R: Rng>(&self, &mut R) -> Support; } +/// A wrapper for generating types that implement `Rand` via the +/// `Sample` & `IndependentSample` traits. +pub struct RandSample<Sup>; + +impl<Sup: Rand> Sample<Sup> for RandSample<Sup> { + fn sample<R: Rng>(&mut self, rng: &mut R) -> Sup { self.ind_sample(rng) } +} + +impl<Sup: Rand> IndependentSample<Sup> for RandSample<Sup> { + fn ind_sample<R: Rng>(&self, rng: &mut R) -> Sup { + rng.gen() + } +} + mod ziggurat_tables; // inlining should mean there is no performance penalty for this @@ -166,3 +180,24 @@ impl Rand for Exp1 { pdf, zero_case)) } } + +#[cfg(test)] +mod tests { + use rand::*; + use super::*; + + struct ConstRand(uint); + impl Rand for ConstRand { + fn rand<R: Rng>(_: &mut R) -> ConstRand { + ConstRand(0) + } + } + + #[test] + fn test_rand_sample() { + let mut rand_sample = RandSample::<ConstRand>; + + assert_eq!(*rand_sample.sample(task_rng()), 0); + assert_eq!(*rand_sample.ind_sample(task_rng()), 0); + } +} |
