Skip to content

Instantly share code, notes, and snippets.

@akuraru
Created October 10, 2012 12:03
Show Gist options
  • Save akuraru/3865187 to your computer and use it in GitHub Desktop.
Save akuraru/3865187 to your computer and use it in GitHub Desktop.
Objective-Cで関数型プログラミングしたいなーと思ってやってみた。とりあえずFizzBuzz
#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;
}
#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
#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