/* Module: list A standard linked list */ import option::{some, none}; /* Section: Types */ /* Tag: list */ tag list { /* Variant: cons */ cons(T, @list); /* Variant: nil */ nil; } /*Section: Operations */ /* Function: from_vec Create a list from a vector */ fn from_vec(v: [mutable? T]) -> list { let l = nil::; // 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. for item: T in vec::reversed(v) { l = cons::(item, @l); } ret l; } /* Function: foldl Left fold Applies `f` to the first argument in the list and `u`, then applies `f` to the second argument and the result of the previous call, and so on, returning the accumulated result. Parameters: ls_ - The list to fold u - The initial value f - The function to apply */ fn foldl(ls_: list, u: U, f: block(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; } } } ret accum; } /* Function: find Search for an element that matches a given predicate Apply function `f` to each element of `v`, starting from the first. When function `f` returns true then an option containing the element is returned. If `f` matches no elements then none is returned. */ fn find(ls_: list, f: block(T) -> option::t) -> option::t { let ls = ls_; while true { alt ls { cons(hd, tl) { alt f(hd) { none. { ls = *tl; } some(rs) { ret some(rs); } } } nil. { break; } } } ret none; } /* Function: has Returns true if a list contains an element with the given value */ fn has(ls_: list, elt: T) -> bool { let ls = ls_; while true { alt ls { cons(hd, tl) { if elt == hd { ret true; } else { ls = *tl; } } nil. { break; } } } ret false; } /* Function: length Returns the length of a list */ fn length(ls: list) -> uint { fn count(_t: T, &&u: uint) -> uint { ret u + 1u; } ret foldl(ls, 0u, bind count(_, _)); } /* Function: cdr Returns all but the first element of a list */ fn cdr(ls: list) -> list { alt ls { cons(_, tl) { ret *tl; } nil. { fail "list empty" } } } /* Function: car Returns the first element of a list */ fn car(ls: list) -> T { alt ls { cons(hd, _) { ret hd; } nil. { fail "list empty" } } } /* Function: append Appends one list to another */ fn append(l: list, m: list) -> list { alt l { nil. { ret m; } cons(x, xs) { let rest = append(*xs, m); ret cons(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: