]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/unboxed-closures-infer-recursive-fn.rs
rustdoc: Replace no-pretty-expanded with pretty-expanded
[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 // pretty-expanded FIXME #23616
12
13 #![feature(core,unboxed_closures)]
14
15 use std::marker::PhantomData;
16
17 // Test that we are able to infer a suitable kind for a "recursive"
18 // closure.  As far as I can tell, coding up a recursive closure
19 // requires the good ol' [Y Combinator].
20 //
21 // [Y Combinator]: http://en.wikipedia.org/wiki/Fixed-point_combinator#Y_combinator
22
23 struct YCombinator<F,A,R> {
24     func: F,
25     marker: PhantomData<(A,R)>,
26 }
27
28 impl<F,A,R> YCombinator<F,A,R> {
29     fn new(f: F) -> YCombinator<F,A,R> {
30         YCombinator { func: f, marker: PhantomData }
31     }
32 }
33
34 impl<A,R,F : Fn(&Fn(A) -> R, A) -> R> Fn<(A,)> for YCombinator<F,A,R> {
35     type Output = R;
36
37     extern "rust-call" fn call(&self, (arg,): (A,)) -> R {
38         (self.func)(self, arg)
39     }
40 }
41
42 fn main() {
43     let factorial = |recur: &Fn(u32) -> u32, arg: u32| -> u32 {
44         if arg == 0 {1} else {arg * recur(arg-1)}
45     };
46     let factorial: YCombinator<_,u32,u32> = YCombinator::new(factorial);
47     let r = factorial(10);
48     assert_eq!(3628800, r);
49 }