int fibonacci(int x) {
return x <= 2 ? 1 :
fibonacci(x - 1) + fibonacci(x - 2);
}
//the cache is captured by the block
typedef int (^IntFunc)(int);
IntFunc memoize(IntFunc fun) {
NSMutableDictionary *memo =
[NSMutableDictionary dictionary];
return ^int(int x) {
NSNumber *cached = memo[@(x)];
if (cached != nil) {
return cached.intValue;
}
int r = fun(x);
memo[@(x)] = @(r);
return r;
};
}
IntFunc memFibonacci = memoize(^int(int x) {
return fibonacci(x);
});
for (int i = 1; i <= 2; i++) {
NSDate *start = [NSDate date];
int f37 = memFibonacci(37);
NSTimeInterval seconds =
-start.timeIntervalSinceNow;
NSLog(@"%d: f37 is %d", i, f37);
NSLog(@"%d: seconds is %f", i, seconds);
}
//the second call is instant:
//the value comes from the cache
| Данный способ мемоизации хорошо работает с нерекурсивными функциями. Поскольку запоминает только результат первого вызова функции. |