Freelance iOS Developer, Rapidly Aging Punk

Functional Programming for Jerks: Map

Jul 26, 2015 at 01:29PM

Most of what I've read about functional programming is big on philosophy and short on pragmatism. This series of posts is my attempt to learn some of the basics of functional programming and to write about them in a way that jerks like me can understand.

Map

Wikipedia says:

map is the name of a higher-order function that applies a given function to each element of a list, returning a list of results.

What I Think That Means

I think I can follow this one. A "higher-order" function is a function that takes a function as a variable. Most modern-day developers are familiar with that kind of thing – Objective-C calls it "blocks" and Swift calls it "closures." List is just another word for array. So map is going to take an array, run a function on each element, and return an array of the results. Sounds a lot like a for-in loop!

The Old Way

var nums = [1, 2, 3, 4, 5, 6]

var newNums = [Int]()
for num in nums {
    newNums.append(num * 2)
}

nums = newNums

The Functional Way

var nums = [1, 2, 3, 4, 5, 6]

nums = map(nums, { (num) -> Int in
    num * 2
})

//nums is now [2, 4, 6, 8, 10, 12]

Conclusion

This is okay. It saves some lines over a for-in at the expense of some clarity. A beginner could probably work out the for-in with a little thought but I don't think I'd ever just figure out map without looking at the documentation. My understanding is that map is just the first step into more complex operations – so maybe the tradeoff will make more sense later on.