Skip to content

Instantly share code, notes, and snippets.

@DeedleFake
Last active August 29, 2015 14:25
Show Gist options
  • Save DeedleFake/fdc6ce77aa598d2a5ed0 to your computer and use it in GitHub Desktop.
Save DeedleFake/fdc6ce77aa598d2a5ed0 to your computer and use it in GitHub Desktop.
A (mostly) straight port of the Go examples at https://golang.org/doc/play to Rust.
fn fib() -> Box<FnMut() -> i32> {
let (mut a, mut b) = (0, 1);
Box::new(move || {
let c = a + b;
a = b;
b = c;
a
})
}
fn main() {
let mut f = fib();
for _i in 0..5 {
println!("{}", f());
}
}
// This produces a rather bad approximation of Pi on play.rust-lang.org.
// Did I mess up?
use std::thread;
use std::sync::mpsc::{channel, Sender};
fn pi(n: i32) -> f64 {
let (tx, rx) = channel();
for k in 0..n {
let tx = tx.clone();
thread::spawn(move || {
term(tx, k as f64);
});
}
let mut f = 0f64;
for _k in 0..n {
f += rx.recv().unwrap();
}
f
}
fn term(tx: Sender<f64>, k: f64) {
tx.send(4f64 * (-1f64).powf(k) / (2f64 * k + 1f64)).unwrap();
}
fn main() {
println!("{}", pi(500));
}
use std::thread;
use std::sync::mpsc::{channel, Sender, Receiver};
fn gen(ch: Sender<i32>) {
let mut i = 2;
loop {
ch.send(i).unwrap();
i += 1;
}
}
fn filter(left: Receiver<i32>, right: Sender<i32>, prime: i32) {
loop {
let i = left.recv().unwrap();
if i % prime != 0 {
right.send(i).unwrap();
}
}
}
fn main() {
let (tx, mut rx) = channel();
thread::spawn(move || {
gen(tx);
});
for _i in 0..10 {
let prime = rx.recv().unwrap();
println!("{}", prime);
let (tx2, rx2) = channel();
thread::spawn(move || {
filter(rx, tx2, prime);
});
rx = rx2;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment