2010-10-16 00:09:09 -05:00
|
|
|
|
2010-11-03 19:10:37 -05:00
|
|
|
import std.option;
|
|
|
|
import option.some;
|
|
|
|
import option.none;
|
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.
|
|
|
|
|
2010-10-16 00:09:09 -05:00
|
|
|
tag list[T] {
|
|
|
|
cons(T, @list[T]);
|
|
|
|
nil;
|
|
|
|
}
|
|
|
|
|
2010-10-28 17:02:00 -05:00
|
|
|
fn foldl[T,U](&list[T] ls, &U u, fn(&T t, U u) -> U f) -> U {
|
2010-10-18 16:35:44 -05:00
|
|
|
alt(ls) {
|
|
|
|
case (cons[T](?hd, ?tl)) {
|
|
|
|
auto u_ = f(hd, u);
|
|
|
|
// FIXME: should use 'be' here, not 'ret'. But parametric
|
|
|
|
// tail calls currently don't work.
|
|
|
|
ret foldl[T,U](*tl, u_, f);
|
|
|
|
}
|
|
|
|
case (nil[T]) {
|
|
|
|
ret u;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2010-10-18 18:02:59 -05:00
|
|
|
fn find[T,U](&list[T] ls,
|
2010-11-03 19:10:37 -05:00
|
|
|
(fn(&T) -> option.t[U]) f) -> option.t[U] {
|
2010-10-18 16:35:44 -05:00
|
|
|
alt(ls) {
|
|
|
|
case (cons[T](?hd, ?tl)) {
|
|
|
|
alt (f(hd)) {
|
2010-10-18 18:02:59 -05:00
|
|
|
case (none[U]) {
|
2010-10-18 16:35:44 -05:00
|
|
|
// FIXME: should use 'be' here, not 'ret'. But parametric tail
|
|
|
|
// calls currently don't work.
|
2010-10-18 18:02:59 -05:00
|
|
|
ret find[T,U](*tl, f);
|
2010-10-18 16:35:44 -05:00
|
|
|
}
|
2010-10-18 18:02:59 -05:00
|
|
|
case (some[U](?res)) {
|
|
|
|
ret some[U](res);
|
2010-10-18 16:35:44 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
case (nil[T]) {
|
2010-10-18 18:02:59 -05:00
|
|
|
ret none[U];
|
2010-10-18 16:35:44 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn length[T](&list[T] ls) -> uint {
|
|
|
|
fn count[T](&T t, uint u) -> uint {
|
|
|
|
ret u + 1u;
|
|
|
|
}
|
|
|
|
ret foldl[T,uint](ls, 0u, bind count[T](_, _));
|
|
|
|
}
|
2010-10-16 00:09:09 -05:00
|
|
|
|
|
|
|
// 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 .. 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
|
|
|
|
// End:
|