Refactoring to Functional– Basic Primitives

This is a multi-part series on Refactoring to Functional Programming

  1. Getting Started
  2. Basic Primitives
  3. Reducing and Flattening Lists
  4. Why Class?

Say we have a list of great albums (i.e. Pink Floyd’s discography*)

We want to get a list of all albums that were number one in both the US and the UK.

The Imperative Approach

Let’s go for the simple approach. A for loop iterating the length of the list and adding the new items to another list.

This works and is simple enough. But there are a couple of issues, if we’re trying to abide by the functional paradigms highlighted in the previous post. In particular, treating things as infinite. Here we’re consciously aware of the length of the list.

Refactoring to infinite lists

We want to avoid having to deal with indices, lengths and counts and worrying whether we have some element in or out of bounds. So the first step is to refactor to remove the actual loop index. In Kotlin, there is a for in loop which allows us to iterate through anything that has an iterator() function. In other words, anything that implements Iterable<T>.

Now we no longer need to deal with lengths.

Adding some syntactic sugar

The previous is better, but we can add some syntactic sugar. Instead of explicitly having a for in we can use an extension function that Kotlin provides, forEach which does the same thing

Since we no longer have the actual album element we can reference the current item the iterator is on using the it reserved word in Kotlin.

What we want instead of how we want it

If we look at the previous code, what we’re doing is removing elements that don’t match a certain criteria. We’re doing this by creating another list and adding the ones that do match to this new list. But if we were to remove the name of the function, to understand what we’ve just described, we’d need to mentally envision it taking into account the for loop, the temporary list, etc.

Of course, with this code it isn’t that hard but add another embedded for loop and things can start to get ugly.

The problem here is that we’re telling the computer how we want something done, instead of what we want done. What we want is to filter a list. What we’ve done is create another list and copy items to it, then return that list. Why not instead just filter the list?

Refactoring to asking versus telling

In Kotlin there is a filter function that takes a list and returns a new one that matches a certain predicate.

We can therefore refactor the code to

The reason we’re omitting the parenthesis is that by convention in Kotlin, if the last parameter to a function is another function, we can omit these.

As a side-effect of this refactoring, we’ve also removed the temporary list, and while in the previous code, hits was declared as immutable, the list itself (declared as ArrayList) was mutable. Win?

Changing data types

What happens now if we need something slightly different? We’re not always bound to work with the same type of data. Let’s assume for instance we want to return the years where an album made it to number one in both the UK and the US. We could of course do the following

The problem is that we re-introduce again some of the issues we had previous, namely using a temporary variable and again telling the computer how we want something versus what we want.

Using Map to transform results

Much like filter, Kotlin offers another function to help us do this: map.

which takes a function that given an input of type T produces an output of type R, returning a list of R. We can therefore refactor the previous code to

Once again we’ve gone from saying how to do something to asking for it.

Basic Primitives

The two functions we’ve just used: map and filter are some of the main primitives in functional programming. With them we can start to treat lists as infinite, chain them and transform results to what we need without having to deal with for loops, lengths, indices or complicated loops. We’ll see if they actually do help dramatically as we start working on more complex scenarios.

Until next time.

*The true Pink Floyd.

12 thoughts on “Refactoring to Functional– Basic Primitives

    1. Hadi Hariri Post author

      LINQ is nothing but map, filter, reduce under the covers. But the point here isn’t to compare languages but to build up towards functional thinking.

    2. rarelyProgramming

      c# is a hassle, logic wise linq is just about the same, except here we use an intuitive verb… filter. I dont really see the hassle here.
      @Hadi, thanks for the posts. this is already making me smarter. its a paradigm shift form using control structure to using intelligent verbs/functions that know how to work with your data.

    1. Hadi Hariri Post author

      Yes it is but it’s a concern that I no longer have, right? And we’re assuming (or hoping) that the language/library can handle things correctly

  1. His awesomeness (@chrissie1)

    Yep, we are relying on some more black magic. But we already do that a lot, so yeah, why not. As long as you know both ways of doing things, because you might need to optimize later on when that piece of black magic might not do what you think it does or is slow.

    And no I am not capable of coherent thought let alone write it down.

    1. Hadi Hariri Post author

      You mean in my examples or in Kotlin? In the former, because Kotlin does not have these functions. In the latter because filter, map, reduce, are all operations that are common in functional languages and predate LINQ.

  2. Pingback: Dew Drop – November 11, 2013 (#1664) | Morning Dew

  3. Pingback: Refactoring to Functional–Getting Started | Hadi Hariri's Blog

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s