Thursday, January 15, 2009

NSArray+Functional

Nicolas Seriot has written a category on NSArray to add map, filter, and reduce functionality. You pass a selector and a variable number of arguments, and it performs the selector on each object in the array. Blocks are much nicer, of course, but they’re not available yet in Objective-C. Higher order messaging provides type-checking at compile time and supports more types of arguments, however the va_arg approach is simpler than HOM and works better with selectors that return BOOL.

4 Comments RSS · Twitter

While a category on NSArray is fine, I probably would have written it either as a global function taking an "id" object or a category on NSObject.

Why? Because there are other collection objects besides NSArrays, such as NSSets. The call could test whether the collection object supports the -objectEnumerator call and, if so, call the supplied selector on all of the objects regardless of collection type.

Whether it should be a global function or category is a good question. I don't see a huge practical advantage of one over the other.

EricS: Yes, I think a global function would make sense, and it would be a bit more concise.

Y'know, I'd really appreciate it if the universe of gearheads could hurry up and produce a version of Obj-C that is an order of magnitude more abstracted than the current version.

I'd really like to write some apps.

Chucky -- They already have, it's called Smalltalk.

Leave a Comment