Last active
December 26, 2015 14:19
-
-
Save tautologico/7165194 to your computer and use it in GitHub Desktop.
Example of using lists.
This file contains hidden or 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
// Polymorphic lists | |
// Compile with "rustc -o list list.rs" | |
// more recent versions of the compiler need this for @ pointers | |
#[feature(managed_boxes)]; | |
// enable macros | |
#[feature(macro_rules)]; | |
enum List<A> { | |
Empty, | |
Cons(A, @List<A>) | |
} | |
fn length<A>(l: @List<A>) -> uint { | |
match *l { | |
Empty => 0, | |
Cons(_, rest) => 1 + length(rest) | |
} | |
} | |
fn length_acc<A>(l: @List<A>, acc: uint) -> uint { | |
match *l { | |
Empty => acc, | |
Cons(_, rest) => length_acc(rest, acc + 1) | |
} | |
} | |
macro_rules! list( | |
( $e:expr, $($rest:expr),+ ) => ( @Cons($e, list!( $( $rest ),+ )) ); | |
( $e:expr ) => ( @Cons($e, @Empty) ); | |
() => ( @Empty ) | |
) | |
fn sum_int_list(l: @List<int>) -> int { | |
match *l { | |
Empty => 0, | |
Cons(x, rest) => x + sum_int_list(rest) | |
} | |
} | |
fn main() { | |
let l = @Cons("3", @Cons("little", @Cons("strings", @Empty))); | |
println!("Length of l is {}", length(l)); | |
println!("Length of l is {}", length_acc(l, 0)); | |
let l2 = list!(5, 4, 4, 3); | |
println!("Length of l2 is {}", length(l2)); | |
println!("Sum of l2 is {}", sum_int_list(l2)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment