Skip to content

Instantly share code, notes, and snippets.

@vi
Last active December 16, 2015 08:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vi/5408426 to your computer and use it in GitHub Desktop.
Save vi/5408426 to your computer and use it in GitHub Desktop.
Y combinator in Rust
/* Y combinator for Rust.
Implemented by Vitaly "_Vi" Shukela.
$ rustc --version
rustc 0.6 (5f13e9c 2013-04-02 13:36:51 -0700)
host: i686-unknown-linux-gnu
*/
type Yfunc<T> = @fn(x:T) -> T;
type Yfunc2<T> = @fn(f: Yfunc<T>, x:T) -> T;
fn fix<T>(f:Yfunc2<T>) -> Yfunc<T> {
let closure1 : @mut Yfunc<T> = @mut |_| { fail!() };
let closure2 : @fn(ff : Yfunc2<T> , xx : T)->T = |ff : Yfunc2<T> , xx : T| {
ff(*closure1, xx)
};
*closure1 = |x| {
let result = closure2(f, x);
*closure1 = |_| { fail!() }; // Fix memory leak
result
};
*closure1
}
fn main() {
let fac : Yfunc2<int> = |f:Yfunc<int>, x:int| {
if (x==0) { 1 } else { f(x-1) * x }
};
io::println( fmt!("%d", fix(fac) (5) ));
let fib : Yfunc2<int> = |f:Yfunc<int>, x:int| {
if (x<2) { 1 } else { f(x-1) + f(x-2) }
};
io::println( fmt!("%d", fix(fib) (10) ));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment