Imperative programming vs Functional programming – a Beginner’s approach Part 4: FlatMap

1. Introduction

Computer programming is about solving problems and getting things done the right way. However, as a beginner, you don’t care how you do it as long as you get it done. It works so why bother tackling it in a completely different way after all?

I thought the same way when I first stumbled upon functional programming in Swift. I knew about functional programming languages like Haskell or Scala, but I was under the impression that they are only good for research at an academic level and have no practical value of any kind. So I approached it reluctantly at first and soon asked myself how I lived without it.

The biggest challenge you face when discovering new programming paradigms is changing the way you think. This can be scary at first because you are used to doing things in a certain way and now you suddenly feel overwhelmed. It takes time and patience to get used to anything new but it’s worth doing it in the long run – being able to choose the right technique for a certain problem is a skill that any software developer should have in his toolbox.

OK, enough talking – let’s see what functional programming is all about.

2. The imperative approach

Your task for this tutorial is an easy one: create a plain array with the elements of a nested array – an array of arrays. Before diving into coding, think how you would solve the problem and break it into steps. This is how I would do it:

  • create the initial array and populate it with default values;
  • create the new array;
  • loop through the original array and do two things for each iteration:
    • extract the current array from the nested array;
    • loop through the array and do two things for each iteration:
      • extract the current value from the array;
      • add the value to the new array;
  • print the new array to the console;

That’s it for the algorithm – let’s move on to the implementation.

3. The imperative implementation

Fire up Xcode and open a playground. Delete everything from it and add this line to kick things off:

let nestedArray = [[1, 2], [3, 4]]

This creates the initial constant nested array and assigns its default values.

Note: There are many different ways of creating arrays in Swift – this is the easiest approach of all because it uses type inference to determine the array’s type – Int in this case.

Next create the new array:

var simpleArray = [Int]()

This line creates a variable array of integers – it is variable because you are going to add values to it soon.

Now loop through the original array with the for in control flow statement:

for array in nestedArray {

}   

Note: There are many ways of looping in Swift – this is the best approach for nested arrays because it gives you access to the current array for each iteration.

There is only one thing you should do inside the for loop for each array of the nested array – loop through it:

for value in array {

}   

Note: There are many ways of looping in Swift – this is the best approach for plain arrays because it gives you access to the current value for each iteration.

There is only one thing you should do inside the for loop for each value of the current array – add it to the new array:

simpleArray.append(value)

Finally, print the new array to the console:

print(simpleArray, terminator: "")

Note: There are other ways to print to the console as well – this approach doesn’t print the newline “\n” character in the playground.

That’s it – let’s analyse the implementation.

4. The imperative implementation analysed

The imperative implementation focuses on how to solve the problem by dividing the task into clear simple steps. This approach is easy to understand but it adds boilerplate code. Functional programming to the rescue!

5. The functional approach

Functional programming focuses only on what needs to be done – flatten the array in this case – and doesn’t care how you actually do it. The flatMap function does exactly this: it creates a plain array with the elements of a nested array.

Enough theory – let’s see the flatMap function in action!

6. The functional implementation

Add this line to the playground to get started:

let simplefArray = nestedArray.flatMap{$0}

The flatMap function uses a closure – a fancy word for anonymous function – as its parameter. The closure’s body is the rule that maps the elements of both arrays. The closure’s argument – $0 – is the nested array’s current array.

Note: The closure’s body can be written in many other ways in Swift – this is the simplest approach of all because it uses trailing closure syntax and shorthand argument names.

Now print the new array to the console:

print(simplefArray, terminator: "")

That’s it – it can’t get any simpler than that! Let’s analyse the implementation.

7. The functional implementation analysed

The functional implementation is straightforward – define the mapping rule in the closure and let the flatMap function do the rest – no more boilerplate code.

8. Imperative vs functional comparison

Imperative advantages:

  • clear steps
  • easy to understand

Imperative disadvantages:

  • boilerplate code

Functional advantages:

  • no boilerplate code
  • short and sweet

Functional disadvantages:

  • difficult to understand

9. Conclusion

Both paradigms have their pros and cons – feel free to try them both and choose the one that suits you best. Happy coding! 🙂

Note: All the code in this tutorial was tested in a playground in Xcode 7.1 and Swift 2.1 (Download).

Advertisements
Posted in Functional programming
2 comments on “Imperative programming vs Functional programming – a Beginner’s approach Part 4: FlatMap
  1. sachin says:

    I am bit confused on what exactly flatMap function does ?

    Like

  2. What don’t you understand exactly?

    Like

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

Enter your email address to receive notifications of new posts by email.

Simple Programmer
%d bloggers like this: