DEV Community

Cover image for foldLeft, map and filter in Scala
Mitch Henderson
Mitch Henderson

Posted on

foldLeft, map and filter in Scala

What exactly are foldLeft, map, and filter in Scala? They are higher order functions, they operate on lists by taking in functions and applying these functions to a list(s). These are a way of NOT writing loops, we don't need to think about the implementation of the loop. But, with these higher order functions, we are still thinking about what we want to do with each element in a list, and even though this method is not any faster, it's about 'expressivity' and can simplify what we want to say with our code.

Let's start with foldLeft, it is a useful method that takes a list, a function and a starting point and uses the function to operate on the list element by element.

For example, how can we get the sum of a list using foldLeft? Note that 'a' here is what we are folding into, whereas the 'b' is the next element from the list.

//Get sum of a list using fold
List(1,2,3).foldLeft(0)((a,b) => a+b)

In another example, here I show how can we add 1 to a list using foldLeft:

//Add a 1 to the list using fold
List(1,2,3).foldLeft(List[Int]())((a,b) => a++List(b+1))

Here I show how can we return a list containing only even numbers using foldLeft:

//Return a list w/ only even numbers using fold
List(1,2,3).foldLeft(List[Int]())((a,b) => if (b%2 ==0) a ++ List(b) else a)

Looking at map, on the other hand, we see that it takes a list and a function, and returns another list made up from the result of the function applied to each element. map does not take a starting element. Here, 'a' is an element of the list, and 'a+1' is our operation.

//adding one to each element of a list using map
List(1,2,3).map((a) => a+1)

Now we look at filter. filter takes a list and a function, and the function takes an element from the list and returns a boolean. Here we have our list, we are using filter, using element 'a' and applying the modulo 2 in order to keep the even elements of the list.

//return a list of only even elements using filter
List(1,2,3).filter((a) => (a%2 == 0))

As can be seen, foldLeft, map, and filter are more about making our code more readable. We also see the concept 'expressivity', allowing us to more easily convey an idea to the reader of the code what we are trying to accomplish without necessitating a 'for' loop. Although so much of what I've learned has been about speed, this is a concept where the runtime speed is not decreased (or increased for that matter), but it does make the code more legible to the next person having to read it.

Top comments (0)