Created
May 31, 2013 19:23
-
-
Save MarkJr94/5687331 to your computer and use it in GitHub Desktop.
Simple Chain outline
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use core::from_str::*; | |
fn stringify<T: ToStr>(x: T) -> ~str { | |
x.to_str() | |
} | |
fn unstringify<T: FromStr> (s: ~str) -> Option<T> { | |
FromStr::from_str(s) | |
} | |
fn add_one(n: int) -> int { | |
n + 1 | |
} | |
fn times_two(n: int) -> int { | |
n * 2 | |
} | |
fn chain<A,B,C>(f1: ~fn(a: A) -> B,f2: ~fn(b: B) -> C) -> ~fn(A) -> C { | |
|x: A| { | |
f2(f1(x)) | |
} | |
} | |
fn main() { | |
let plus_one_times_two = chain(add_one,times_two); | |
let times_two_plus_one = chain(times_two,add_one); | |
let to_str_and_back: ~fn(x: int) -> Option<int> = chain(stringify,unstringify); | |
let fifty = match to_str_and_back(50) { | |
Some(n) => {n} | |
None => {0} | |
}; | |
let res1 = plus_one_times_two(50); | |
let res2 = times_two_plus_one(50); | |
println(fmt!("to_str_and_back(50) = %d", fifty)); | |
println(fmt!("plus_one_times_two(50) = %d",res1)); | |
println(fmt!("times_two_plus_one(50) = %d",res2)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment