rust/src/lib/list.rs

84 lines
2.1 KiB
Rust
Raw Normal View History

import option::some;
import option::none;
2010-10-18 16:35:44 -05:00
2010-10-18 16:35:44 -05:00
// FIXME: It would probably be more appealing to define this as
// type list[T] = rec(T hd, option[@list[T]] tl), but at the moment
// our recursion rules do not permit that.
tag list[T] { cons(T, @list[T]); nil; }
2011-07-27 07:19:39 -05:00
fn from_vec[T](v: vec[T]) -> list[T] {
let l = nil[T];
2011-05-21 23:11:28 -05:00
// FIXME: This would be faster and more space efficient if it looped over
// a reverse vector iterator. Unfortunately generic iterators seem not to
// work yet.
2011-07-27 07:19:39 -05:00
for item: T in vec::reversed(v) { l = cons[T](item, @l); }
2011-05-21 23:11:28 -05:00
ret l;
}
2011-07-27 07:19:39 -05:00
fn foldl[T, U](ls_: &list[T], u: &U, f: fn(&T, &U) -> U ) -> U {
let accum: U = u;
let ls = ls_;
while true {
alt ls {
cons(hd, tl) { accum = f(hd, accum); ls = *tl; }
nil. { break; }
2011-05-21 21:11:42 -05:00
}
2010-10-18 16:35:44 -05:00
}
ret accum;
2010-10-18 16:35:44 -05:00
}
2011-07-27 07:19:39 -05:00
fn find[T, U](ls_: &list[T], f: fn(&T) -> option::t[U] ) -> option::t[U] {
let ls = ls_;
while true {
alt ls {
cons(hd, tl) {
alt f(hd) { none. { ls = *tl; } some(rs) { ret some(rs); } }
}
nil. { break; }
2010-10-18 16:35:44 -05:00
}
}
ret none;
2010-10-18 16:35:44 -05:00
}
2011-07-27 07:19:39 -05:00
fn has[T](ls_: &list[T], elt: &T) -> bool {
let ls = ls_;
while true {
alt ls {
cons(hd, tl) { if elt == hd { ret true; } else { ls = *tl; } }
nil. { ret false; }
2011-05-25 11:54:43 -05:00
}
}
ret false; // Typestate checker doesn't understand infinite loops
2011-06-16 18:55:46 -05:00
2011-05-25 11:54:43 -05:00
}
2011-07-27 07:19:39 -05:00
fn length[T](ls: &list[T]) -> uint {
fn count[T](t: &T, u: &uint) -> uint { ret u + 1u; }
ret foldl[T, uint](ls, 0u, bind count[T](_, _));
2010-10-18 16:35:44 -05:00
}
2011-07-27 07:19:39 -05:00
fn cdr[T](ls: &list[T]) -> list[T] { alt ls { cons(_, tl) { ret *tl; } } }
2011-07-27 07:19:39 -05:00
fn car[T](ls: &list[T]) -> T { alt ls { cons(hd, _) { ret hd; } } }
2011-07-27 07:19:39 -05:00
fn append[T](l: &list[T], m: &list[T]) -> list[T] {
alt l {
nil. { ret m; }
cons(x, xs) {
let rest: list[T] = append[T](*xs, m);
ret cons[T](x, @rest);
}
}
}
// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End: