RosettaCodeData/Task/Y-combinator/Objective-C/y-combinator-1.m

42 lines
864 B
Mathematica
Raw Permalink Normal View History

2013-04-11 01:07:29 -07:00
#import <Foundation/Foundation.h>
typedef int (^Func)(int);
typedef Func (^FuncFunc)(Func);
typedef Func (^RecursiveFunc)(id); // hide recursive typing behind dynamic typing
2015-02-20 00:35:01 -05:00
Func Y(FuncFunc f) {
2013-04-11 01:07:29 -07:00
RecursiveFunc r =
2015-02-20 00:35:01 -05:00
^(id y) {
RecursiveFunc w = y; // cast value back into desired type
return f(^(int x) {
return w(w)(x);
});
};
2013-04-11 01:07:29 -07:00
return r(r);
}
int main (int argc, const char *argv[]) {
2014-04-02 16:56:35 +00:00
@autoreleasepool {
2013-04-11 01:07:29 -07:00
2015-02-20 00:35:01 -05:00
Func fib = Y(^Func(Func f) {
2014-04-02 16:56:35 +00:00
return ^(int n) {
if (n <= 2) return 1;
return f(n - 1) + f(n - 2);
};
2015-02-20 00:35:01 -05:00
});
Func fac = Y(^Func(Func f) {
return ^(int n) {
if (n <= 1) return 1;
return n * f(n - 1);
};
});
2013-04-11 01:07:29 -07:00
2014-04-02 16:56:35 +00:00
Func fib = fix(almost_fib);
Func fac = fix(almost_fac);
NSLog(@"fib(10) = %d", fib(10));
NSLog(@"fac(10) = %d", fac(10));
2013-04-11 01:07:29 -07:00
2014-04-02 16:56:35 +00:00
}
2013-04-11 01:07:29 -07:00
return 0;
}