Freelance iOS Developer, Rapidly Aging Punk

Functional Programming for Jerks: Filter

Jul 27, 2015 at 05:14PM

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.


Wikipedia says:

filter is a higher-order function that processes a data structure (typically a list) in some order to produce a new data structure containing exactly those elements of the original data structure for which a given predicate returns the boolean value true.

What I Think That Means

We're going to take an array and run a function on each element that will return true or false to determine whether that element should be in a new array. Like our new friend map this sounds a lot like a for-in loop in disguise.

The Old Way

var nums = [100, 1, 200, 2, 300, 3]

var newNums = [Int]()
for num in nums {
    if num > 99 {
nums = newNums

The Functional Way

var nums = [100, 1, 200, 2, 300, 3]

filter(nums, { (num: Int) -> Bool in
    num > 99


Like map, I maybe see what they're going for here. I still think the more verbose for-in is an easier read but at least the name filter makes it pretty obvious what's happening.