Created
August 15, 2013 12:08
-
-
Save doublec/6240315 to your computer and use it in GitHub Desktop.
An attempt at a List that has the length encoded as a type parameter in Rust using phantom types. I wasn't able to get list_zip to compile unfortunately.
This file contains hidden or 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
| use std::cast::transmute; | |
| struct Zero; | |
| struct Succ<T>; | |
| struct Prev<T>; | |
| enum List<T,N> { | |
| Nil, | |
| Cons (T, ~List<T,N>) | |
| } | |
| fn nil<T> () -> ~List<T, Zero> { ~Nil } | |
| fn cons<T,N> (hd: T, tl: ~List<T,N>) -> ~List<T,Succ<N>> { | |
| unsafe { transmute(~Cons (hd, tl)) } | |
| } | |
| fn singleton<T>(t: T) -> ~List<T,Succ<Zero>> { | |
| cons (t, nil ()) | |
| } | |
| /* | |
| fn list_zip<A,B,N> (xs: ~List<A,N>, ys: ~List<B,N>) -> ~List<(A,B),N> { | |
| match (xs, ys) { | |
| (~Nil, ~Nil) => { nil () } | |
| (~Cons (x, xs), ~Cons (y,ys)) => { cons((x,y), list_zip(xs, ys)) } | |
| } | |
| } | |
| i*/ | |
| fn print_list<T,N>(xs: ~List<T,N>) { | |
| match *xs { | |
| Nil => { () } | |
| Cons (x, xs) => { | |
| println(fmt!("%?", x)); | |
| print_list(xs); | |
| } | |
| } | |
| } | |
| fn main() { | |
| let a = singleton(5); | |
| let b = cons (1, cons (2, a)); | |
| print_list(b); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment