list.rs 1.4 KB
Newer Older
1

2 3 4 5 6 7 8 9
import util.option;
import util.some;
import util.none;

// 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.

10 11 12 13 14
tag list[T] {
    cons(T, @list[T]);
    nil;
}

15 16 17 18 19 20 21 22 23 24 25 26 27 28
fn foldl[T,U](&list[T] ls, U u, fn(&T t, U u) -> U f) -> U {
  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;
    }
  }
}

29 30
fn find[T,U](&list[T] ls,
             (fn(&T) -> option[U]) f) -> option[U] {
31 32 33
  alt(ls) {
    case (cons[T](?hd, ?tl)) {
        alt (f(hd)) {
34
            case (none[U]) {
35 36
                // FIXME: should use 'be' here, not 'ret'. But parametric tail
                // calls currently don't work.
37
                ret find[T,U](*tl, f);
38
            }
39 40
            case (some[U](?res)) {
                ret some[U](res);
41 42 43 44
            }
        }
    }
    case (nil[T]) {
45
        ret none[U];
46 47 48 49 50 51 52 53 54 55
    }
  }
}

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](_, _));
}
56 57 58 59 60 61 62 63 64

// 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: