Created
April 8, 2011 14:49
-
-
Save ssoper/909988 to your computer and use it in GitHub Desktop.
Ruby's inject method in Objective-C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Enumerable.h | |
#import <Foundation/Foundation.h> | |
typedef id (^InjectBlock)(id, id); | |
@interface NSArray (Enumerable) | |
- (id) inject:(id) initial block:(InjectBlock) block; | |
@end | |
// Enumerable.m | |
#import "Enumerable.h" | |
@implementation NSArray (Enumerable) | |
- (id) inject:(id) initial block:(InjectBlock) block { | |
id memo = initial; | |
if (!memo) | |
memo = [self objectAtIndex: 0]; | |
for (id obj in self) { | |
memo = block(memo, obj); | |
} | |
return memo; | |
} | |
@end | |
// main.m | |
#import "Enumerable.h" | |
int main(int argc, char *argv[]) { | |
NSArray *ary = [NSArray arrayWithObjects: @"cat", @"sheep", @"bear", nil]; | |
InjectBlock block = ^ id (id memo, id word) { | |
return ((NSString *)memo).length > ((NSString *)word).length ? memo : word; | |
}; | |
id longestWord = [ary inject: nil block: block]; | |
NSLog(@"Longest word %@", longestWord); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment