RosettaCodeData/Task/Anonymous-recursion/Objective-C/anonymous-recursion-2.m

27 lines
627 B
Mathematica
Raw Permalink Normal View History

2013-04-10 22:43:41 -07:00
#import <Foundation/Foundation.h>
int fib(int n) {
if (n < 0)
@throw [NSException exceptionWithName:NSInvalidArgumentException
reason:@"fib: no negative numbers"
userInfo:nil];
2014-04-02 16:56:35 +00:00
int (^f)(int);
__block __weak int (^weak_f)(int); // block cannot capture strong reference to itself
weak_f = f = ^(int n) {
2013-04-10 22:43:41 -07:00
if (n < 2)
return 1;
else
2014-04-02 16:56:35 +00:00
return weak_f(n-1) + weak_f(n-2);
2013-04-10 22:43:41 -07:00
};
return f(n);
}
int main (int argc, const char *argv[]) {
2014-04-02 16:56:35 +00:00
@autoreleasepool {
2013-04-10 22:43:41 -07:00
2014-04-02 16:56:35 +00:00
NSLog(@"%d", fib(8));
2013-04-10 22:43:41 -07:00
2014-04-02 16:56:35 +00:00
}
2013-04-10 22:43:41 -07:00
return 0;
}