Skip to content

Instantly share code, notes, and snippets.

@jonsterling
Created September 18, 2010 05:43
Show Gist options
  • Select an option

  • Save jonsterling/585393 to your computer and use it in GitHub Desktop.

Select an option

Save jonsterling/585393 to your computer and use it in GitHub Desktop.
template <typename T> NSArray *fk::arr (T obj1, ...) NS_REQUIRES_NIL_TERMINATION;
template <typename T> NSArray *fk::lift_arr (T obj);
// we started with the following, which would be better represented as a C-array of ints:
[NSArray arrayWithObjects:
[NSNumber numberWithInt:2],
[NSNumber numberWithInt:5],
[NSNumber numberWithInt:1],
[NSNumber numberWithInt:45],
nil];
// but it could be better, if we are intent on using an NSArray:
[NSArray arrayWithObjects:box<int>(2),box<int>(5),box<int>(1),box<int>(45),nil];
// still better:
[NSArray arrayWithObjects:box(2),box(5),box(1),box(45),nil];
// but check this out:
fk::arr<int>(2,5,1,45,nil);
// using C++'s type inference, we can make this even simpler!:
fk::arr(2,5,1,45,nil);
// FunctionKit also provides a way to lift a single value into an array without having to terminate with nil:
fk::lift_arr<int>(3); // => [NSArray arrayWithObject:[NSNumber numberWithInt:3]];
// of course, this is even better:
fk::lift_arr(3);
template <typename K,typename V> NSDictionary *fk::dict (K k1,...) NS_REQUIRES_NIL_TERMINATION;
template <typename K,typename V> NSDictionary *fk::pair (K key, V value);
// let's start with a simple key-value pair, where the value is a boolean, and the key is a string:
[NSDictionary dictionaryWithObject:[NSNumber numberWithBOOL:YES] forKey:@"foo"];
[NSDictionary dictionaryWithObject:box<BOOL>(YES) forKey:@"foo"];
[NSDictionary dictionaryWithObject:$(YES) forKey:@"foo"];
fk::pair<BOOL,NSString *>(YES,@"foo");
// The same concept goes for dictionaries with many pairs
[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBOOL:YES],@"foo",
[NSNumber numberWithBOOL:NO],@"bar",
nil];
[NSDictionary dictionaryWithObjectsAndKeys:
box<BOOL>(YES),@"foo",
box<BOOL>(NO),@"bar",
nil];
fk::dict<BOOL,NSString *>(YES,@"foo",NO,@"bar",nil);
+ (id <Functor>)functorWithObjects:(NSArray *)anArray {
return fold_monoid_append(anArray);
}
fk::f f = fk::f(^(NSString *s) {
return [s stringByAppendingString:@"!"];
});
fk::f F = map(f);
NSArray *arr = [NSArray arrayWithObjects:@"dog",@"cat",nil];
f(@"dog"); // => @"dog!"
F(arr); // => {@"dog!",@"cat!"}
map(f)(arr); // => {@"dog!",@"cat!"}
f[arr]; // => {@"dog!",@"cat!"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment