]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/unboxed-closures-infer-recursive-fn.rs
Auto merge of #22517 - brson:relnotes, r=Gankro
[rust.git] / src / test / run-pass / unboxed-closures-infer-recursive-fn.rs
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.
4 //
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.
10
11 #![feature(core,unboxed_closures)]
12
13 use std::marker::CovariantType;
14
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].
18 //
19 // [Y Combinator]: http://en.wikipedia.org/wiki/Fixed-point_combinator#Y_combinator
20
21 struct YCombinator<F,A,R> {
22     func: F,
23     marker: CovariantType<(A,R)>,
24 }
25
26 impl<F,A,R> YCombinator<F,A,R> {
27     fn new(f: F) -> YCombinator<F,A,R> {
28         YCombinator { func: f, marker: CovariantType }
29     }
30 }
31
32 impl<A,R,F : Fn(&Fn(A) -> R, A) -> R> Fn<(A,)> for YCombinator<F,A,R> {
33     type Output = R;
34
35     extern "rust-call" fn call(&self, (arg,): (A,)) -> R {
36         (self.func)(self, arg)
37     }
38 }
39
40 fn main() {
41     let factorial = |recur: &Fn(u32) -> u32, arg: u32| -> u32 {
42         if arg == 0 {1} else {arg * recur(arg-1)}
43     };
44     let factorial: YCombinator<_,u32,u32> = YCombinator::new(factorial);
45     let r = factorial(10);
46     assert_eq!(3628800, r);
47 }