]> git.lizzy.rs Git - rust.git/blob - tests/ui/unboxed-closures/unboxed-closures-infer-recursive-fn.rs
Rollup merge of #106856 - vadorovsky:fix-atomic-annotations, r=joshtriplett
[rust.git] / tests / ui / unboxed-closures / unboxed-closures-infer-recursive-fn.rs
1 // run-pass
2 #![feature(fn_traits, unboxed_closures)]
3
4 use std::marker::PhantomData;
5
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].
9 //
10 // [Y Combinator]: https://en.wikipedia.org/wiki/Fixed-point_combinator#Y_combinator
11
12 struct YCombinator<F,A,R> {
13     func: F,
14     marker: PhantomData<(A,R)>,
15 }
16
17 impl<F,A,R> YCombinator<F,A,R> {
18     fn new(f: F) -> YCombinator<F,A,R> {
19         YCombinator { func: f, marker: PhantomData }
20     }
21 }
22
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)
26     }
27 }
28
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) }
31 }
32
33 impl<A,R,F : Fn(&dyn Fn(A) -> R, A) -> R> FnOnce<(A,)> for YCombinator<F,A,R> {
34     type Output = R;
35     extern "rust-call" fn call_once(self, args: (A,)) -> R { self.call(args) }
36 }
37
38 fn main() {
39     let factorial = |recur: &dyn Fn(u32) -> u32, arg: u32| -> u32 {
40         if arg == 0 {1} else {arg * recur(arg-1)}
41     };
42     let factorial: YCombinator<_,u32,u32> = YCombinator::new(factorial);
43     let r = factorial(10);
44     assert_eq!(3628800, r);
45 }