auto merge of #11150 : huonw/rust/moar-docs, r=alexcrichton

(I removed the `fn main` from the `std::rand` examples to make it consistent with the rest of the codebase.)
This commit is contained in:
bors 2013-12-28 16:06:59 -08:00
commit c0d4abf8c5
7 changed files with 183 additions and 168 deletions

View File

@ -12,6 +12,45 @@
//!
//! The tables use a keyed hash with new random keys generated for each container, so the ordering
//! of a set of keys in a hash table is randomized.
//!
//! # Example
//!
//! ```rust
//! use std::hashmap::HashMap;
//!
//! // type inference lets us omit an explicit type signature (which
//! // would be `HashMap<&str, &str>` in this example).
//! let mut book_reviews = HashMap::new();
//!
//! // review some books.
//! book_reviews.insert("Adventures of Hucklebury Fin", "My favorite book.");
//! book_reviews.insert("Grimms' Fairy Tales", "Masterpiece.");
//! book_reviews.insert("Pride and Prejudice", "Very enjoyable.");
//! book_reviews.insert("The Adventures of Sherlock Holmes", "Eye lyked it alot.");
//!
//! // check for a specific one.
//! if !book_reviews.contains_key(& &"Les Misérables") {
//! println!("We've got {} reviews, but Les Misérables ain't one.",
//! book_reviews.len());
//! }
//!
//! // oops, this review has a lot of spelling mistakes, let's delete it.
//! book_reviews.remove(& &"The Adventures of Sherlock Holmes");
//!
//! // look up the values associated with some keys.
//! let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
//! for book in to_find.iter() {
//! match book_reviews.find(book) {
//! Some(review) => println!("{}: {}", *book, *review),
//! None => println!("{} is unreviewed.", *book)
//! }
//! }
//!
//! // iterate over everything.
//! for (book, review) in book_reviews.iter() {
//! println!("{}: \"{}\"", *book, *review);
//! }
//! ```
use container::{Container, Mutable, Map, MutableMap, Set, MutableSet};
use clone::Clone;
@ -354,6 +393,43 @@ impl<K: Hash + Eq, V> HashMap<K, V> {
/// Modify and return the value corresponding to the key in the map, or
/// insert and return a new value if it doesn't exist.
///
/// This method allows for all insertion behaviours of a hashmap,
/// see methods like `insert`, `find_or_insert` and
/// `insert_or_update_with` for less general and more friendly
/// variations of this.
///
/// # Example
///
/// ```rust
/// use std::hashmap::HashMap;
///
/// // map some strings to vectors of strings
/// let mut map = HashMap::<~str, ~[~str]>::new();
/// map.insert(~"a key", ~[~"value"]);
/// map.insert(~"z key", ~[~"value"]);
///
/// let new = ~[~"a key", ~"b key", ~"z key"];
/// for k in new.move_iter() {
/// map.mangle(k, ~"new value",
/// // if the key doesn't exist in the map yet, add it in
/// // the obvious way.
/// |_k, v| ~[v],
/// // if the key does exist either prepend or append this
/// // new value based on the first letter of the key.
/// |key, already, new| {
/// if key.starts_with("z") {
/// already.unshift(new);
/// } else {
/// already.push(new);
/// }
/// });
/// }
///
/// for (k, v) in map.iter() {
/// println!("{} -> {:?}", *k, *v);
/// }
/// ```
pub fn mangle<'a,
A>(
&'a mut self,

View File

@ -60,11 +60,9 @@ impl Rand for Exp1 {
/// use std::rand;
/// use std::rand::distributions::{Exp, IndependentSample};
///
/// fn main() {
/// let exp = Exp::new(2.0);
/// let v = exp.ind_sample(&mut rand::task_rng());
/// println!("{} is from a Exp(2) distribution", v);
/// }
/// let exp = Exp::new(2.0);
/// let v = exp.ind_sample(&mut rand::task_rng());
/// println!("{} is from a Exp(2) distribution", v);
/// ```
pub struct Exp {
/// `lambda` stored as `1/lambda`, since this is what we scale by.

View File

@ -37,11 +37,9 @@ use num;
/// use std::rand;
/// use std::rand::distributions::{IndependentSample, Gamma};
///
/// fn main() {
/// let gamma = Gamma::new(2.0, 5.0);
/// let v = gamma.ind_sample(&mut rand::task_rng());
/// println!("{} is from a Gamma(2, 5) distribution", v);
/// }
/// let gamma = Gamma::new(2.0, 5.0);
/// let v = gamma.ind_sample(&mut rand::task_rng());
/// println!("{} is from a Gamma(2, 5) distribution", v);
/// ```
///
/// [1]: George Marsaglia and Wai Wan Tsang. 2000. "A Simple Method
@ -183,11 +181,9 @@ impl IndependentSample<f64> for GammaLargeShape {
/// use std::rand;
/// use std::rand::distributions::{ChiSquared, IndependentSample};
///
/// fn main() {
/// let chi = ChiSquared::new(11.0);
/// let v = chi.ind_sample(&mut rand::task_rng());
/// println!("{} is from a χ²(11) distribution", v)
/// }
/// let chi = ChiSquared::new(11.0);
/// let v = chi.ind_sample(&mut rand::task_rng());
/// println!("{} is from a χ²(11) distribution", v)
/// ```
pub enum ChiSquared {
// k == 1, Gamma(alpha, ..) is particularly slow for alpha < 1,
@ -237,11 +233,9 @@ impl IndependentSample<f64> for ChiSquared {
/// use std::rand;
/// use std::rand::distributions::{FisherF, IndependentSample};
///
/// fn main() {
/// let f = FisherF::new(2.0, 32.0);
/// let v = f.ind_sample(&mut rand::task_rng());
/// println!("{} is from an F(2, 32) distribution", v)
/// }
/// let f = FisherF::new(2.0, 32.0);
/// let v = f.ind_sample(&mut rand::task_rng());
/// println!("{} is from an F(2, 32) distribution", v)
/// ```
pub struct FisherF {
priv numer: ChiSquared,
@ -283,11 +277,9 @@ impl IndependentSample<f64> for FisherF {
/// use std::rand;
/// use std::rand::distributions::{StudentT, IndependentSample};
///
/// fn main() {
/// let t = StudentT::new(11.0);
/// let v = t.ind_sample(&mut rand::task_rng());
/// println!("{} is from a t(11) distribution", v)
/// }
/// let t = StudentT::new(11.0);
/// let v = t.ind_sample(&mut rand::task_rng());
/// println!("{} is from a t(11) distribution", v)
/// ```
pub struct StudentT {
priv chi: ChiSquared,

View File

@ -94,15 +94,13 @@ pub struct Weighted<T> {
/// use std::rand;
/// use std::rand::distributions::{Weighted, WeightedChoice, IndependentSample};
///
/// fn main() {
/// let wc = WeightedChoice::new(~[Weighted { weight: 2, item: 'a' },
/// Weighted { weight: 4, item: 'b' },
/// Weighted { weight: 1, item: 'c' }]);
/// let mut rng = rand::task_rng();
/// for _ in range(0, 16) {
/// // on average prints 'a' 4 times, 'b' 8 and 'c' twice.
/// println!("{}", wc.ind_sample(&mut rng));
/// }
/// let wc = WeightedChoice::new(~[Weighted { weight: 2, item: 'a' },
/// Weighted { weight: 4, item: 'b' },
/// Weighted { weight: 1, item: 'c' }]);
/// let mut rng = rand::task_rng();
/// for _ in range(0, 16) {
/// // on average prints 'a' 4 times, 'b' 8 and 'c' twice.
/// println!("{}", wc.ind_sample(&mut rng));
/// }
/// ```
pub struct WeightedChoice<T> {

View File

@ -76,12 +76,10 @@ impl Rand for StandardNormal {
/// use std::rand;
/// use std::rand::distributions::{Normal, IndependentSample};
///
/// fn main() {
/// // mean 2, standard deviation 3
/// let normal = Normal::new(2.0, 3.0);
/// let v = normal.ind_sample(&mut rand::task_rng());
/// println!("{} is from a N(2, 9) distribution", v)
/// }
/// // mean 2, standard deviation 3
/// let normal = Normal::new(2.0, 3.0);
/// let v = normal.ind_sample(&mut rand::task_rng());
/// println!("{} is from a N(2, 9) distribution", v)
/// ```
pub struct Normal {
priv mean: f64,
@ -120,12 +118,10 @@ impl IndependentSample<f64> for Normal {
/// use std::rand;
/// use std::rand::distributions::{LogNormal, IndependentSample};
///
/// fn main() {
/// // mean 2, standard deviation 3
/// let log_normal = LogNormal::new(2.0, 3.0);
/// let v = log_normal.ind_sample(&mut rand::task_rng());
/// println!("{} is from an ln N(2, 9) distribution", v)
/// }
/// // mean 2, standard deviation 3
/// let log_normal = LogNormal::new(2.0, 3.0);
/// let v = log_normal.ind_sample(&mut rand::task_rng());
/// println!("{} is from an ln N(2, 9) distribution", v)
/// ```
pub struct LogNormal {
priv norm: Normal

View File

@ -51,21 +51,17 @@ randomness.
use std::rand;
use std::rand::Rng;
fn main() {
let mut rng = rand::rng();
if rng.gen() { // bool
println!("int: {}, uint: {}", rng.gen::<int>(), rng.gen::<uint>())
}
let mut rng = rand::rng();
if rng.gen() { // bool
println!("int: {}, uint: {}", rng.gen::<int>(), rng.gen::<uint>())
}
```
```rust
use std::rand;
fn main () {
let tuple_ptr = rand::random::<~(f64, char)>();
println!("{:?}", tuple_ptr)
}
let tuple_ptr = rand::random::<~(f64, char)>();
println!("{:?}", tuple_ptr)
```
*/
@ -91,27 +87,28 @@ pub mod reader;
pub mod reseeding;
mod rand_impls;
/// A type that can be randomly generated using an Rng
/// A type that can be randomly generated using an `Rng`.
pub trait Rand {
/// Generates a random instance of this type using the specified source of
/// randomness
/// randomness.
fn rand<R: Rng>(rng: &mut R) -> Self;
}
/// A random number generator
/// A random number generator.
pub trait Rng {
/// Return the next random u32. This rarely needs to be called
/// directly, prefer `r.gen()` to `r.next_u32()`.
/// Return the next random u32.
///
/// This rarely needs to be called directly, prefer `r.gen()` to
/// `r.next_u32()`.
// FIXME #7771: Should be implemented in terms of next_u64
fn next_u32(&mut self) -> u32;
/// Return the next random u64. This rarely needs to be called
/// directly, prefer `r.gen()` to `r.next_u64()`.
/// Return the next random u64.
///
/// By default this is implemented in terms of `next_u32`. An
/// implementation of this trait must provide at least one of
/// these two methods.
/// these two methods. Similarly to `next_u32`, this rarely needs
/// to be called directly, prefer `r.gen()` to `r.next_u64()`.
fn next_u64(&mut self) -> u64 {
(self.next_u32() as u64 << 32) | (self.next_u32() as u64)
}
@ -139,11 +136,9 @@ pub trait Rng {
/// ```rust
/// use std::rand::{task_rng, Rng};
///
/// fn main() {
/// let mut v = [0u8, .. 13579];
/// task_rng().fill_bytes(v);
/// println!("{:?}", v);
/// }
/// let mut v = [0u8, .. 13579];
/// task_rng().fill_bytes(v);
/// println!("{:?}", v);
/// ```
fn fill_bytes(&mut self, dest: &mut [u8]) {
// this could, in theory, be done by transmuting dest to a
@ -169,20 +164,17 @@ pub trait Rng {
}
}
/// Return a random value of a Rand type.
/// Return a random value of a `Rand` type.
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
/// use std::rand::{task_rng, Rng};
///
/// fn main() {
/// let mut rng = rand::task_rng();
/// let x: uint = rng.gen();
/// println!("{}", x);
/// println!("{:?}", rng.gen::<(f64, bool)>());
/// }
/// let mut rng = task_rng();
/// let x: uint = rng.gen();
/// println!("{}", x);
/// println!("{:?}", rng.gen::<(f64, bool)>());
/// ```
#[inline(always)]
fn gen<T: Rand>(&mut self) -> T {
@ -194,15 +186,12 @@ pub trait Rng {
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
/// use std::rand::{task_rng, Rng};
///
/// fn main() {
/// let mut rng = rand::task_rng();
/// let x: ~[uint] = rng.gen_vec(10);
/// println!("{:?}", x);
/// println!("{:?}", rng.gen_vec::<(f64, bool)>(5));
/// }
/// let mut rng = task_rng();
/// let x: ~[uint] = rng.gen_vec(10);
/// println!("{:?}", x);
/// println!("{:?}", rng.gen_vec::<(f64, bool)>(5));
/// ```
fn gen_vec<T: Rand>(&mut self, len: uint) -> ~[T] {
vec::from_fn(len, |_| self.gen())
@ -220,16 +209,13 @@ pub trait Rng {
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
/// use std::rand::{task_rng, Rng};
///
/// fn main() {
/// let mut rng = rand::task_rng();
/// let n: uint = rng.gen_range(0u, 10);
/// println!("{}", n);
/// let m: f64 = rng.gen_range(-40.0, 1.3e5);
/// println!("{}", m);
/// }
/// let mut rng = task_rng();
/// let n: uint = rng.gen_range(0u, 10);
/// println!("{}", n);
/// let m: f64 = rng.gen_range(-40.0, 1.3e5);
/// println!("{}", m);
/// ```
fn gen_range<T: Ord + SampleRange>(&mut self, low: T, high: T) -> T {
assert!(low < high, "Rng.gen_range called with low >= high");
@ -241,13 +227,10 @@ pub trait Rng {
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
/// use std::rand::{task_rng, Rng};
///
/// fn main() {
/// let mut rng = rand::rng();
/// println!("{:b}", rng.gen_weighted_bool(3));
/// }
/// let mut rng = task_rng();
/// println!("{:b}", rng.gen_weighted_bool(3));
/// ```
fn gen_weighted_bool(&mut self, n: uint) -> bool {
n == 0 || self.gen_range(0, n) == 0
@ -259,12 +242,9 @@ pub trait Rng {
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
/// use std::rand::{task_rng, Rng};
///
/// fn main() {
/// println(rand::task_rng().gen_ascii_str(10));
/// }
/// println(task_rng().gen_ascii_str(10));
/// ```
fn gen_ascii_str(&mut self, len: uint) -> ~str {
static GEN_ASCII_STR_CHARSET: &'static [u8] = bytes!("ABCDEFGHIJKLMNOPQRSTUVWXYZ\
@ -288,15 +268,12 @@ pub trait Rng {
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
/// use std::rand::{task_rng, Rng};
///
/// fn main() {
/// let choices = [1, 2, 4, 8, 16, 32];
/// let mut rng = rand::task_rng();
/// println!("{:?}", rng.choose_option(choices));
/// println!("{:?}", rng.choose_option(choices.slice_to(0)));
/// }
/// let choices = [1, 2, 4, 8, 16, 32];
/// let mut rng = task_rng();
/// println!("{:?}", rng.choose_option(choices));
/// println!("{:?}", rng.choose_option(choices.slice_to(0)));
/// ```
fn choose_option<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> {
if values.is_empty() {
@ -311,12 +288,9 @@ pub trait Rng {
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
/// use std::rand::{task_rng, Rng};
///
/// fn main() {
/// println!("{:?}", rand::task_rng().shuffle(~[1,2,3]));
/// }
/// println!("{:?}", task_rng().shuffle(~[1,2,3]));
/// ```
fn shuffle<T>(&mut self, values: ~[T]) -> ~[T] {
let mut v = values;
@ -329,17 +303,14 @@ pub trait Rng {
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
/// use std::rand::{task_rng, Rng};
///
/// fn main() {
/// let mut rng = rand::task_rng();
/// let mut y = [1,2,3];
/// rng.shuffle_mut(y);
/// println!("{:?}", y);
/// rng.shuffle_mut(y);
/// println!("{:?}", y);
/// }
/// let mut rng = task_rng();
/// let mut y = [1,2,3];
/// rng.shuffle_mut(y);
/// println!("{:?}", y);
/// rng.shuffle_mut(y);
/// println!("{:?}", y);
/// ```
fn shuffle_mut<T>(&mut self, values: &mut [T]) {
let mut i = values.len();
@ -356,14 +327,11 @@ pub trait Rng {
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
/// use std::rand::{task_rng, Rng};
///
/// fn main() {
/// let mut rng = rand::task_rng();
/// let sample = rng.sample(range(1, 100), 5);
/// println!("{:?}", sample);
/// }
/// let mut rng = task_rng();
/// let sample = rng.sample(range(1, 100), 5);
/// println!("{:?}", sample);
/// ```
fn sample<A, T: Iterator<A>>(&mut self, iter: T, n: uint) -> ~[A] {
let mut reservoir : ~[A] = vec::with_capacity(n);
@ -392,12 +360,10 @@ pub trait SeedableRng<Seed>: Rng {
/// ```rust
/// use std::rand::{Rng, SeedableRng, StdRng};
///
/// fn main() {
/// let mut rng: StdRng = SeedableRng::from_seed(&[1, 2, 3, 4]);
/// println!("{}", rng.gen::<f64>());
/// rng.reseed([5, 6, 7, 8]);
/// println!("{}", rng.gen::<f64>());
/// }
/// let mut rng: StdRng = SeedableRng::from_seed(&[1, 2, 3, 4]);
/// println!("{}", rng.gen::<f64>());
/// rng.reseed([5, 6, 7, 8]);
/// println!("{}", rng.gen::<f64>());
/// ```
fn reseed(&mut self, Seed);
@ -406,13 +372,10 @@ pub trait SeedableRng<Seed>: Rng {
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
/// use std::rand::{Rng, SeedableRng, StdRng};
///
/// fn main() {
/// let mut rng: rand::StdRng = rand::SeedableRng::from_seed(&[1, 2, 3, 4]);
/// println!("{}", rng.gen::<f64>());
/// }
/// let mut rng: StdRng = SeedableRng::from_seed(&[1, 2, 3, 4]);
/// println!("{}", rng.gen::<f64>());
/// ```
fn from_seed(seed: Seed) -> Self;
}
@ -647,13 +610,11 @@ impl Rng for TaskRng {
/// ```rust
/// use std::rand::random;
///
/// fn main() {
/// if random() {
/// let x = random();
/// println!("{}", 2u * x);
/// } else {
/// println!("{}", random::<f64>());
/// }
/// if random() {
/// let x = random();
/// println!("{}", 2u * x);
/// } else {
/// println!("{}", random::<f64>());
/// }
/// ```
#[inline]
@ -672,12 +633,10 @@ pub fn random<T: Rand>() -> T {
/// ```rust
/// use std::rand::{random, Open01};
///
/// fn main() {
/// println!("f32 from (0,1): {}", *random::<Open01<f32>>());
/// println!("f32 from (0,1): {}", *random::<Open01<f32>>());
///
/// let x: Open01<f64> = random();
/// println!("f64 from (0,1): {}", *x);
/// }
/// let x: Open01<f64> = random();
/// println!("f64 from (0,1): {}", *x);
/// ```
pub struct Open01<F>(F);
@ -692,12 +651,10 @@ pub struct Open01<F>(F);
/// ```rust
/// use std::rand::{random, Closed01};
///
/// fn main() {
/// println!("f32 from [0,1]: {}", *random::<Closed01<f32>>());
/// println!("f32 from [0,1]: {}", *random::<Closed01<f32>>());
///
/// let x: Closed01<f64> = random();
/// println!("f64 from [0,1]: {}", *x);
/// }
/// let x: Closed01<f64> = random();
/// println!("f64 from [0,1]: {}", *x);
/// ```
pub struct Closed01<F>(F);

View File

@ -26,10 +26,8 @@ use rand::Rng;
/// use std::rand::{reader, Rng};
/// use std::io::mem;
///
/// fn main() {
/// let mut rng = reader::ReaderRng::new(mem::MemReader::new(~[1,2,3,4,5,6,7,8]));
/// println!("{:x}", rng.gen::<uint>());
/// }
/// let mut rng = reader::ReaderRng::new(mem::MemReader::new(~[1,2,3,4,5,6,7,8]));
/// println!("{:x}", rng.gen::<uint>());
/// ```
pub struct ReaderRng<R> {
priv reader: R