Wednesday, September 3, 2014

The Humble Map

Rob Napier:

And again we replace our cut-and-paste for-loop with a reusable function that captures the goal. We save some code, but it’s more than that. We can compose filters and maps to create more interesting things in highly readable ways.

[…]

The goal of using map and filter this way is to make your code easier to read, understand, and debug. It gets the boilerplate out of the way and leaves you with the key parts of what you’re trying to do.

This is so much nicer in Swift than Objective-C because of the concise syntax.

4 Comments RSS · Twitter

What i really miss from Smalltalk is the possibility to replace blocks with selectors, which increases readability even more.

Instead of (1 to: 20) select:[:each | each even] you can simply write (1 to: 20) select: #even.

In Objective-C that'd be like anArray filter:@selector(something) but unfortunately selectors are not objects, so there's currently no way of doing that.
In Swift however it should be possible.

I have been using MACollectionUtilities in Objective-C for years: https://github.com/mikeash/MACollectionUtilities

Offers MAP, MATCH, SELECT, REDUCE and REJECT. Also the syntax is quite nice because it hides the block syntax from you through some clever macros.

@Ilja I recommend the macro approach in Objective-C as well. In most cases I just need an expression, so it’s nice to be able to omit the block syntax. The downside is that if you have nested operations the order looks backwards.

Leave a Comment