Imperative programming vs Functional programming – a Beginner’s approach Part 7: Contains

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: check if all the elements of a given array are equal. 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 array and populate it with default values;
  • create the equal variable and assign its initial value;
  • test if the array is empty and update the equal variable if the test succeeds;
  • create the first item variable and set its initial value;
  • loop through the array and do three things for each iteration:
    • extract the current value from the array;
    • test if it isn’t equal to the first element;
    • update the equal variable if the test succeeds;
  • print the equal variable’s value 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:

import Darwin

This imports the Darwin module into the playground – you use it to stop the program’s execution in case anything goes wrong.

Note: This tutorial is not about the evolution theory – sorry for the disappointed fans out there. 🙂

Next create the array:

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

This line creates a 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.

Now create the equal variable and assign its initial value:

var allEqual = true

This line creates a variable and sets its initial value to true, since you assume that all the array’s items are equal – it is variable because you are going to change its value soon.

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

Next test if the array isn’t empty with the guard statement:

guard !array.isEmpty else {

    allEqual = false
    
    print(allEqual, terminator: "")
   
    abort()

}

If the array is empty, you update the equal variable, print its value to the console and stop the program’s execution with the abort function.

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

Note: You can’t use return instead of abort here because you are not calling the guard statement inside a function or method.

Note: You can read more about the guard statement here.

Now create the first item variable and set its initial value to be the first element of the array:

let first = array.first

Then loop through the 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 loop for each value of the array. First test if it isn’t equal with the array’s first item:

guard value != first else {
        
    continue
    
}

If the value is equal to the first element, you go to the next iteration with the continue statement, since the array’s items are equal at this point.

If the value isn’t equal to the first item, you update the equal variable and exit the loop with the break statement.

allEqual = false

break

Note: You can also do it like this using the if statement – the initial version takes the happy path approach:

if value != first {
    
      allEqual = false
    
      break
    
}

Finally, print the equal variable to the console:

print(allEqual, terminator: "")

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 – test if the array’s elements are equal in this case – and doesn’t care how you actually do it. The contains function does exactly this: it checks if a certain condition is satisfied.

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

6. The functional implementation

Add this line to the playground to get started:

allEqual = !array.contains{$0 != first}

The contains function uses a closure – a fancy word for anonymous function – as its parameter. The closure’s body is the condition that tests if the array’s items are equal and the closure’s argument – $0 – is the array’s current value.

The function’s logic is straightforward – if the current value isn’t equal to the first item, the array’s elements aren’t equal.

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 equal variable to the console:

print(allEqual, 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 equality condition in the closure and let the contains 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 with a playground in Xcode 7.2 and Swift 2.1 (Download).

Note: The tutorial was inspired by this excellent raywenderlich.com generics tutorial.

Advertisements
Posted in Functional programming

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: