2011-08-25 19:43:26 -05:00
|
|
|
// Uses foldl to exhibit the unchecked block syntax.
|
2011-12-29 14:24:03 -06:00
|
|
|
// TODO: since list's head/tail require the predicate "is_not_empty" now and
|
|
|
|
// we have unit tests for list, this test might me not necessary anymore?
|
2011-08-25 19:43:26 -05:00
|
|
|
use std;
|
|
|
|
|
|
|
|
import std::list::*;
|
|
|
|
|
|
|
|
// Can't easily be written as a "pure fn" because there's
|
|
|
|
// no syntax for specifying that f is pure.
|
2012-01-23 16:59:00 -06:00
|
|
|
fn pure_foldl<T: copy, U: copy>(ls: list<T>, u: U, f: fn(T, U) -> U) -> U {
|
2011-12-29 14:24:03 -06:00
|
|
|
alt ls {
|
2012-01-19 00:37:22 -06:00
|
|
|
nil { u }
|
2011-12-29 14:24:03 -06:00
|
|
|
cons(hd, tl) { f(hd, pure_foldl(*tl, f(hd, u), f)) }
|
|
|
|
}
|
2011-08-25 19:43:26 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// Shows how to use an "unchecked" block to call a general
|
|
|
|
// fn from a pure fn
|
2012-01-05 08:35:37 -06:00
|
|
|
pure fn pure_length<T: copy>(ls: list<T>) -> uint {
|
2011-10-06 05:50:24 -05:00
|
|
|
fn count<T>(_t: T, &&u: uint) -> uint { u + 1u }
|
2012-02-07 08:37:08 -06:00
|
|
|
unchecked{ pure_foldl(ls, 0u, count(_, _)) }
|
2011-08-25 19:43:26 -05:00
|
|
|
}
|
|
|
|
|
2012-01-05 08:35:37 -06:00
|
|
|
pure fn nonempty_list<T: copy>(ls: list<T>) -> bool { pure_length(ls) > 0u }
|
2011-08-25 19:43:26 -05:00
|
|
|
|
2011-09-02 17:34:58 -05:00
|
|
|
// Of course, the compiler can't take advantage of the
|
|
|
|
// knowledge that ls is a cons node. Future work.
|
|
|
|
// Also, this is pretty contrived since nonempty_list
|
2012-01-19 18:10:31 -06:00
|
|
|
// could be a "enum refinement", if we implement those.
|
2012-01-05 08:35:37 -06:00
|
|
|
fn safe_head<T: copy>(ls: list<T>) : nonempty_list(ls) -> T {
|
2011-12-29 14:24:03 -06:00
|
|
|
check is_not_empty(ls);
|
|
|
|
ret head(ls)
|
|
|
|
}
|
2011-08-25 19:43:26 -05:00
|
|
|
|
|
|
|
fn main() {
|
|
|
|
let mylist = cons(@1u, @nil);
|
|
|
|
// Again, a way to eliminate such "obvious" checks seems
|
|
|
|
// desirable. (Tags could have postconditions.)
|
2011-09-02 17:34:58 -05:00
|
|
|
check (nonempty_list(mylist));
|
|
|
|
assert (*safe_head(mylist) == 1u);
|
|
|
|
}
|