Skip to content

Instantly share code, notes, and snippets.

@smvv
Forked from jasom/gist:5988857
Last active December 19, 2015 17:09
Show Gist options
  • Select an option

  • Save smvv/5988955 to your computer and use it in GitHub Desktop.

Select an option

Save smvv/5988955 to your computer and use it in GitHub Desktop.
use std::io;
use std::util;
enum List {
Cons(uint,~List),
Nil()
}
fn cons(x : uint, l : ~List) -> ~List{
return ~Cons(x,l);
}
fn printl(mut l : &~List) {
io::print("(");
loop {
match l {
&~Cons(x, ref next) => {
l = next;
io::print(fmt!("%u ",x))
}
&~Nil() => break
}
}
io::print(")");
}
fn truncate<'r> (l: &'r mut ~List, N: uint) -> &'r mut ~List {
if N == 0 {
util::replace(l, ~Nil);
} else {
match **l {
Cons(_, ref mut l) => {
truncate(l, N - 1);
}
Nil => {}
}
}
l
}
fn main() {
let mut l = cons(1,cons(2,cons(3,~Nil)));
printl(&l);
io::print("\n");
printl(truncate(&mut l, 2));
io::print("\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment