2 #![feature(fn_traits, unboxed_closures)]
4 use std::marker::PhantomData;
6 // Test that we are able to infer a suitable kind for a "recursive"
7 // closure. As far as I can tell, coding up a recursive closure
8 // requires the good ol' [Y Combinator].
10 // [Y Combinator]: https://en.wikipedia.org/wiki/Fixed-point_combinator#Y_combinator
12 struct YCombinator<F,A,R> {
14 marker: PhantomData<(A,R)>,
17 impl<F,A,R> YCombinator<F,A,R> {
18 fn new(f: F) -> YCombinator<F,A,R> {
19 YCombinator { func: f, marker: PhantomData }
23 impl<A,R,F : Fn(&dyn Fn(A) -> R, A) -> R> Fn<(A,)> for YCombinator<F,A,R> {
24 extern "rust-call" fn call(&self, (arg,): (A,)) -> R {
25 (self.func)(self, arg)
29 impl<A,R,F : Fn(&dyn Fn(A) -> R, A) -> R> FnMut<(A,)> for YCombinator<F,A,R> {
30 extern "rust-call" fn call_mut(&mut self, args: (A,)) -> R { self.call(args) }
33 impl<A,R,F : Fn(&dyn Fn(A) -> R, A) -> R> FnOnce<(A,)> for YCombinator<F,A,R> {
35 extern "rust-call" fn call_once(self, args: (A,)) -> R { self.call(args) }
39 let factorial = |recur: &dyn Fn(u32) -> u32, arg: u32| -> u32 {
40 if arg == 0 {1} else {arg * recur(arg-1)}
42 let factorial: YCombinator<_,u32,u32> = YCombinator::new(factorial);
43 let r = factorial(10);
44 assert_eq!(3628800, r);