// listmap.rs struct Node { head : int, tail : Option<@mut Node> } type List = Option<@mut Node> ; trait Map { fn mapr(&self, &fn(int) -> int); } trait Filter { fn filtr(&self, &fn(int) -> bool); } impl Map for List { fn mapr(&self, f: &fn(int) -> int) { // Thanks to dbaupp for figuring out why this breaks when called "map"! let mut current = *self; loop { match(current) { None => break, Some(node) => { node.head = f(node.head); current = node.tail }, } } } } impl ToStr for List { fn to_str(&self) -> ~str { fn elements_to_str(n: @mut Node) -> ~str { match (n.tail) { None => fmt!("%?", n.head), Some(tail) => fmt!("%?, %s", n.head, elements_to_str(tail)) } } match(*self) { None => ~"Null", Some(n) => fmt!("[%s]", elements_to_str(n)) } } } fn main() { let lst : List = Some(@mut Node{head: 1, tail: Some(@mut Node{head : 2, tail: Some(@mut Node{head: 3, tail: None})})}); println(lst.to_str()); lst.mapr(|x: int| { x + 1 }); println(lst.to_str()); lst.mapr(|x: int| { x * x }); println(lst.to_str()); lst.mapr(|x: int| { if x % 2 == 0 { x } else { -x }}); println(lst.to_str()); }