FoMS Experts

News / World of Mulesoft

PILLARS OF ITERATION

The big three: map, filter, reduce

The big three: map, filter, reduce
Share
FacebookGoogle plusLinkedInStumbleuponTwitter
M. Petricevic11.8.2021

The big three of functional programming are functions map, filter and reduce. All three take functions as arguments which makes them functions of higher order. They can also be used in languages following the imperative programming approach if, for whatever reason, we want to avoid using classical loops to iterate over a sequence of elements.

Map

Let us take a look at map, a higher order function. From map's function signature found in the documentation we can see that it takes two arguments (an array and a lambda expression) and returns an array.

map(Array, (item: T, index: Number) -> R): Array

T in Array is a type parameter in this function's signature and means that the array can contain elements of any type. Type parameters include Number, String, Null, etc. Since map is a higher order function, it can take functions as arguments. In this context, the second argument of the map function is called a function type. It is a lambda expression which takes two single values as arguments: a value of any type and a value of type Number. R in the function signature denotes a value of any type which is not necessarily of the same type as T.

Map transforms elements in an array, creates a new array and saves the modified values into it. In simpler words, map maps elements of one array to the elements of another. The role of a lambda expression in map is to describe the transformation to be applied to each of the elements of the input array.

Filter

Filter removes elements in an array according to a lambda expression. Given the nature of the filter function, the purpose of its second argument, the lambda expression, is to return a boolean. The lambda expression serves as a condition here.

filter(Array, (item: T, index: Number) -> Boolean): Array

Of course, filter does not really remove any data since data in DataWeave is immutable. It selects elements based on a condition, i.e. filters an array, to be saved into the returned array of the same type.

Reduce

Reduce reduces all the elements in an array down to a single element.

reduce(Array, (item: T, accumulator: A) -> A): A

Its lambda expression should return a new value to the accumulator. The accumulator can be a single value but also a multi-value type like an array or an object. The output type of reduce is set by the accumulator and the lambda expression.

Reduce could therefore be used instead of map or filter. However, even if it is just due to inertia, it is often easier to stick to map and filter as usual and use reduce for simpler reduction tasks. Most developers encounter map and filter much more often than reduce.

Register now