When you are writing functional code, it is sometimes difficult to figure out
which of the Enum
functions you want to use. Here are a few common use cases.
Use Enum.map
You can use Enum.map
when you want to transform a set of elements into
another set of elements. Also, note that the count of elements remains
unchanged. So, if you transform a list of 5 elements using Enum.map
, you get
an output list containing exactly 5 elements, However, the shape of the elements
might be different.
Examples
1 | # transform names into their lengths |
If you look at the count of input and output elements it remains the same, However, the shape is different, the input elements are all strings whereas the output elements are all numbers.
1 | # get ids of all users from a list of structs |
In this example we transform a list of maps to a list of numbers.
Use Enum.filter
When you want to whittle down your input list, use Enum.filter
, Filtering
doesn’t change the shape of the data, i.e. you are not transforming elements,
and the shape of the input data will be the same as the shape of the output
data. However, the count of elements will be different, to be more precise it
will be lesser or the same as the input list count.
Examples
1 | # filter a list to only get names which start with `m` |
The shape of data here is the same, we use a list of strings as the input and get a list of strings as an output, only the count has changed, in this case, we have fewer elements.
1 | # filter a list of users to only get active users |
In this example too, the shape of the input elements is a map (user) and the shape of output elements is still a map.
Use Enum.reduce
The last of the commonly used Enum
functions is Enum.reduce
and it is also
one of the most powerful functions. You can use Enum.reduce
when you need to
change the shape of the input list into something else, for instance a map
or a
number
.
Examples
Change a list of elements into a number by computing its product or sum
1 | iex> Enum.reduce( |
Enum.reduce
takes three arguments, the first is the input enumerable, which is
usually a list or map, the second is the starting value of the accumulator and
the third is a function which is applied for each element
whose result is then sent to the next function application as the accumulator.
Let’s try and understand this using an equivalent javascript example.
1 |
|
Let’s look at another example of converting an employee list into a map containing an employee id and their name.
1 | iex> Enum.reduce( |
So, in a map you end up reducing an input list into one output value.