Skip to content

Instantly share code, notes, and snippets.

@akuraru
Forked from anonymous/gist:6631580
Created September 20, 2013 08:00
Show Gist options
  • Save akuraru/6634552 to your computer and use it in GitHub Desktop.
Save akuraru/6634552 to your computer and use it in GitHub Desktop.
@interface Tuple : NSObject
@property (readonly, nonatomic) id _1;
@property (readonly, nonatomic) id _2;
+ (id)tupleWithFirst:(id)_1 second:(id)_2;
- (id)initWithFirst:(id)_1 second:(id)_2;
@end
@implementation Tuple
+ (id)tupleWithFirst:(id)_1 second:(id)_2 {
return [[self alloc] initWithFirst:_1 second:_2];
}
- (id)initWithFirst:(id)_1 second:(id)_2 {
self = [super init];
if (self) {
__1 = _1;
__2 = _2;
}
return self;
}
@end
#define tuple(x, y) [Tuple tupleWithFirst:(x) second:(y)];
@implementation NSObject (typeMatch)
@end
#define lambda(x, code) (^(id x){return ({ code ;});})
#define lambda2(x, y, code) (^(id x, id y){return ({ code ;});})
#define Case(code1, code2) [Tuple tupleWithFirst:(lambda(it, @(code1))) second:(lambda(it, code2))]
#define typeCase(type, code) Case([it isKindOfClass:[type class]], code)
#define eqCase(eq, code) Case([it isEqual:eq], code)
#define ifCase(if, code) Case(if, code)
#define other(code) [Tuple tupleWithFirst:lambda(it, @(YES)) second:lambda(it, code)]
#define pMatch (id)^(id __a, id __t) { id(^__m)(id) = [__t _1]; id(^__n)(id) = [__t _2]; return ([__m(__a) boolValue]) ? __n(__a) : nil; }
#define pMatch2 (id)^(id __a, id __t, id __t2) { return (pMatch(__a, __t)) ?: pMatch(__a, __t2); }
#define pMatch3 (id)^(id __a, id __t, id __t2, id __t3) { return (pMatch(__a, __t)) ?: pMatch2(__a, __t2, __t3); }
#define pMatch4 (id)^(id __a, id __t, id __t2, id __t3, id __t4) { return (pMatch(__a, __t)) ?: pMatch3(__a, __t2, __t3, __t4); }
//- (void)testMatch {
// NSString *str1 = @"hoge";
//
// id re = pMatch4(str1,
// typeCase(NSNumber, @([it integerValue] * 2)),
// eqCase(@"fuga", [it stringByAppendingString:it]),
// ifCase([@"hoge" compare:it] == NSOrderedAscending, @([it length])),
// other(it)
// );
//
// STAssertEqualObjects(@"hoge", re, @"same");
//}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment