Created
October 10, 2012 12:03
-
-
Save akuraru/3865187 to your computer and use it in GitHub Desktop.
Objective-Cで関数型プログラミングしたいなーと思ってやってみた。とりあえずFizzBuzz
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
#import <Foundation/Foundation.h> | |
#import "NSArray-Fanctional.h" | |
int main(int argc, const char * argv[]) | |
{ | |
@autoreleasepool { | |
[[[NSArray from:1 to:100] map:^(NSNumber *num){ | |
NSInteger i = [num longValue]; | |
return | |
(i % 15 == 0)? @"FizzBuzz": | |
(i % 3 == 0)? @"Fizz": | |
(i % 5 == 0)? @"Buzz": | |
[NSString stringWithFormat:@"%li",i]; | |
}]foreach:^(NSString *str){ | |
NSLog(@"%@",str); | |
}]; | |
} | |
return 0; | |
} |
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
#import <Foundation/Foundation.h> | |
typedef id (^fanc_t)(id); | |
typedef void (^noReturn_t)(id); | |
@interface NSArray (Fanctional) | |
+ (NSArray *)from:(NSInteger)from to:(NSInteger)to; | |
- (NSArray *)map:(fanc_t)fanc; | |
- (void)foreach:(noReturn_t)fanc; | |
@end |
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
#import "NSArray-Fanctional.h" | |
@implementation NSArray (Fanctional) | |
+ (NSArray *)from:(NSInteger)from to:(NSInteger)to | |
{ | |
NSMutableArray *array = [NSMutableArray array]; | |
for (NSInteger i = 0, _len = to - from + 1; i < _len; i++) { | |
array[i] = [NSNumber numberWithLong:(from + i)]; | |
} | |
return array; | |
} | |
- (NSArray *)map:(fanc_t)fanc | |
{ | |
NSMutableArray *array = [NSMutableArray array]; | |
for (NSInteger i = 0, _len = [self count]; i < _len; i++) { | |
array[i] = fanc(self[i]); | |
} | |
return array; | |
} | |
- (void)foreach:(noReturn_t)fanc | |
{ | |
for (NSInteger i = 0, _len = [self count]; i < _len; i++) { | |
fanc(self[i]); | |
} | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment