# Imperative programming vs Functional programming – a Beginner’s approach Part 1: Map 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 an array with the elements of a given array multiplied by 2. 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 three things for each iteration:
• extract the current value from the array;
• compute its new value by doubling the initial one;
• add the new value to the new array;
• print the new array to the console;

That’s it for the algorithm – now 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 array = [1, 2, 3, 4, 5]`

This creates the initial constant 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 doubleArray = [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 value in array {

}
```

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

There are two things you should do inside the for loop for each value of the array. First determine the new value from the old one:

`let doubleValue = value * 2`

Then add it to the new array:

`doubleArray.append(doubleValue)`

Note: You can combine both steps into a single one and get rid of the intermediate constant, but there are still two steps involved. The initial approach maps better to the algorithm discussed in the previous section:

`doubleArray.append(value * 2)`

Finally, print the new array to the console:

`print(doubleArray, 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 – time for your next challenge: create a new array with the elements of the given array multiplied by 3.

4. The imperative implementation revisited

First create the new array:

`var tripleArray = [Int]()`

Next loop through the original array:

```for value in array {

}
```

Now compute the new value and add it to the new array:

```let tripleValue = value * 3
tripleArray.append(tripleValue)
```

Note: You could also do it like this – see why in the previous section:

`tripleArray.append(value * 3)`

Finally, print the new array to the console:

`print(tripleArray, terminator: "")`

That’s it – now let’s compare the two implementations.

5. The imperative implementation analyzed

Both implementations are similar:

• create the new array;
• loop through the original array;
• calculate the new value;
• append it to the new array;
• print the new array to the console;

The only major difference between them is the computation of the new value – you multiply the old value by 2 or 3.

Note: You could refactor the whole thing in two ways:

• determine the values for both arrays and append them to each array in the same loop (Download);

Both approaches avoid code redundancy and respect the DRY (don’t repeat yourself) principle, but they don’t deal with the boilerplate code that is common for both implementations. Functional programming to the rescue!

6. The functional approach

Functional programming is about focusing only on what changes and not caring about what stays the same. The only thing that varies between the two previous implementations is the logic that maps each value in the new array to its corresponding value in the old one, so this is the only thing you have to worry about.

The map function does exactly this: it creates an array with the elements of another array. Each new element is computed from its corresponding initial element according to a certain rule.

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

7. The functional implementation

Add this line to the playground to get started:

`let doublefArray = array.map{\$0 * 2}`

The map 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 old array’s current value. You compute each new value inside the closure based on the current value.

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(doublefArray, terminator: "")`

That’s it – it can’t get any simpler than that! Let’s use the map function some more.

8. The functional implementation revisited

Create a new array with the elements of the given array multiplied by 3:

`let triplefArray = array.map{\$0 * 3}`

Now print the new array to the console:

`print(triplefArray, terminator: "")`

That’s it – now let’s compare the two implementations.

9. The functional implementation analyzed

Both implementations are similar – define the mapping rule in the closure and let the map function do the rest – no more boilerplate code.

Note: You could refactor the whole thing by encapsulating the algorithm in a function of its own to avoid code redundancy and respect the DRY principle (Download).

10. Imperative vs functional comparison

• clear steps
• easy to understand

• boilerplate code

• no boilerplate code
• short and sweet