9 August 2015 2min read

The concepts behind iterating

I’ve been reading and talking with people that when explaining functions like map, filter or reduce they start with “it loops over the collection and…”. When I ear that my mind starts thinking in why people doesn’t care about the concepts behind things.

Yes, that explanation is true from an imperative point of view. But I would like to invite you to forget that and not think that functions like map looooop over the collection.

Think of them as functions that apply to the collection.

Map applies a mapping function A -> B. Filter applies a filter function A -> Bool. Etc.

As I said, from an imperative point of view is the same. You can implement all of them simply by iterating the collection an performing some actions.

That’s fine.

But I like to think in terms of concepts.

concept:Philosophy: An idea or mental image which corresponds to some distinct entity or class of entities, or to its essential features, or determines the application of a term (especially a predicate), and thus plays a part in the use of reason or language.

map, and the rest, are not just simple functions, but concepts, and the idea behind them is different than iterating or looping.

All of this functions are called higher-order functions, but I don’t want to talk about Functional Programming. I just want to express the difference between the concepts, even if at the end they do the same.

Not knowing, or caring, about the concepts behind things leads us to do things that we shouldn’t do. In programming and in any other topic.

Don’t do this

let affectedThings = allThings.filter { $0.passessSomeTest() }
affectedThings.map { $0.doSomething() }

In the new Swift version, released with Xcode 7b5, the language has received a new function for all SequenceType: forEach. Presumably the creators of Swift have decided to add this to precisely avoid people merging the concepts of looping with map. We all have seen the usage of map to produce side effects, and even if it’s somewhat okey, the concept is wrong.

This new .forEach method arises mixed feelings because usually I would prefer to just use the for .. in control structure to perform iterations. The good part is that in the Release Notes this is also mentioned as a recommendation:

the forEach member is only recommended when applied to a chained series of functional algorithms (e.g. foo.map {…}.filter {… }.forEach { …}) and when the body is small. In other cases, we recommend using the for..in statement.

In conclusion. There are a bunch of ways to loop over a collection of items, but when deciding what way to use think about what you want to do, and not how. The old good FP sentence, I know. For me it’s not just about making code shorter, it’s about the concepts that are behind this tools and applying the correct one whenever I can. And remember, for .. in loops are still there.

If you enjoyed this post

Continue reading