Skip to content

Instantly share code, notes, and snippets.

@kanaka
Last active August 29, 2015 13:57
Show Gist options
  • Select an option

  • Save kanaka/9514232 to your computer and use it in GitHub Desktop.

Select an option

Save kanaka/9514232 to your computer and use it in GitHub Desktop.
Attempt at List type using Rust std::rc::Rc
// Functional-style integer lists
// Compile with "rustc -o intlistRc intlistRc.rs"
use std::rc::Rc;
enum IntList {
Empty,
Cons(int, Rc<IntList>),
List(~Vector<Rc<IntList>>)
}
fn length(l: &IntList) -> uint {
match *l {
Empty => 0,
//Cons(_, ref rest) => 1 + length(&*rest), // expected `&IntList` but found `&std::rc::Rc<IntList>`
//Cons(_, rest) => 1 + length(&*rest), // cannot move out of dereference of `&`-pointer
Cons(_, ref rest) => 1 + length(&(*rest.borrow())),
_ => 0,
}
}
fn sum_list(l: &IntList) -> int {
match *l {
Empty => 0,
Cons(i, ref rest) => i + sum_list(&(*rest.borrow())),
_ => 0,
}
}
fn main()
{
let l1 = Rc::new(Cons(5, Rc::new(Cons(3, Rc::new(Cons(7, Rc::new(Empty)))))));
println!("length of l1 is {}", length(l1.borrow()));
println!("sum of l1 is {}", sum_list(l1.borrow()));
let l2 = Rc::new(Cons(17, l1));
println!("length of l2 is {}", length(l2.borrow()));
println!("sum of l2 is {}", sum_list(l2.borrow()));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment