Created
October 13, 2012 15:34
-
-
Save bblum/3885017 to your computer and use it in GitHub Desktop.
Lists with lengths in their types.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trait Nat { } | |
enum Zero = (); | |
enum Suc<N: Nat> = N; | |
impl | |
// ---------- | |
Zero : Nat { } | |
impl <N: Nat> | |
// ------------ | |
Suc<N> : Nat { } | |
trait List<T, N: Nat> { | |
fn each(fn(x: &T) -> bool); | |
} | |
enum Nil = (); | |
enum Cons<T, N: Nat, V: List<T,N>> = (T,V); | |
impl <T> | |
// ------------------- | |
Nil : List<T, Zero> { | |
fn each(_blk: fn(x: &T) -> bool) { } | |
} | |
impl <T, N: Nat, V: List<T,N>> | |
// ------------------------------- | |
Cons<T, N, V> : List<T, Suc<N>> { | |
fn each(blk: fn(x: &T) -> bool) { | |
match self { | |
Cons((ref data, ref rest)) => { | |
if blk(data) { | |
rest.each(blk); | |
} | |
} | |
} | |
} | |
} | |
fn nil<T>() -> List<T, Zero> { | |
Nil(()) as List::<T, Zero> | |
} | |
fn cons<T, N: Nat>(data: T, vec: List<T, N>) -> List<T, Suc<N>> { | |
Cons((data, vec)) as List::<T, Suc<N>> | |
} | |
fn main() { | |
// Annotating v as having any other type will error. Try it! | |
let v: List<int, Suc<Suc<Suc<Zero>>>> = cons(1, cons(2, cons(3, nil()))); | |
for v.each |x| { | |
io::println(fmt!("%?", *x)); | |
} | |
} |
yeah, I was running it with the 0.4 release candidate.
i chose cpp because that at least gives minimal syntax highlighting. there is a rust mode that doesn't do anything. c.c
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Got 0.4, and got this to work. Nice.