1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![feature(core,unboxed_closures)]
13 use std::marker::CovariantType;
15 // Test that we are able to infer a suitable kind for a "recursive"
16 // closure. As far as I can tell, coding up a recursive closure
17 // requires the good ol' [Y Combinator].
19 // [Y Combinator]: http://en.wikipedia.org/wiki/Fixed-point_combinator#Y_combinator
21 struct YCombinator<F,A,R> {
23 marker: CovariantType<(A,R)>,
26 impl<F,A,R> YCombinator<F,A,R> {
27 fn new(f: F) -> YCombinator<F,A,R> {
28 YCombinator { func: f, marker: CovariantType }
32 impl<A,R,F : Fn(&Fn(A) -> R, A) -> R> Fn<(A,)> for YCombinator<F,A,R> {
35 extern "rust-call" fn call(&self, (arg,): (A,)) -> R {
36 (self.func)(self, arg)
41 let factorial = |recur: &Fn(u32) -> u32, arg: u32| -> u32 {
42 if arg == 0 {1} else {arg * recur(arg-1)}
44 let factorial: YCombinator<_,u32,u32> = YCombinator::new(factorial);
45 let r = factorial(10);
46 assert_eq!(3628800, r);