Skip to content

Instantly share code, notes, and snippets.

@bblum
Created October 13, 2012 15:34
Show Gist options
  • Save bblum/3885017 to your computer and use it in GitHub Desktop.
Save bblum/3885017 to your computer and use it in GitHub Desktop.
Lists with lengths in their types.
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));
}
}
@dwrensha
Copy link

Do I need to get Rust 0.4 to run this? When's that going to be released?
Also, github seems to think that this is a cpp file.

@dwrensha
Copy link

Got 0.4, and got this to work. Nice.

@bblum
Copy link
Author

bblum commented Oct 19, 2012

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