This document introduces the Enum module in Elixir, which provides functions for looping and iterating over enumerables without using explicit loops. It describes common use cases for looping like transforming or aggregating elements. The Enum module uses recursion under the hood to handle each case. Key functions like Enum.map and Enum.reduce are explained, with Enum.map transforming each element and Enum.reduce collecting results into a single value. The document recommends learning the Enum module as it is very useful and provides a functional approach to looping.
7. But seriously, how do you loop?
The correct answer is actually recursion 🤪
…but the easier/more common answer is the
Enum module
8. Why do we actually loop?
Common use cases:
Doing something to/with a sequence of elements, e.g.
Change every element to something else
Count the elements
Sum all the elements
Doing something until a condition is triggered e.g.
Do something x number of times
Do something until `foo == true` or event is triggered
9. Why do we actually loop?
Common use cases:
Doing something to/with a sequence of elements, e.g.
Change every element to something else
Count the elements
Sum all the elements
Doing something until a condition is triggered e.g.
Do something x number of times
Do something until `foo == true` or event is triggered Recursion
Enum
10. Non-functional languages
output = []
for x in [1,2,3,4] do
output << x*x
end
output == [1,4,9,16]
output =
[1,2,3,4]
|> Enum.map(fn x -> x*x end)
output == [1,4,9,16]
Non-functional (pseudo) Functional (Elixir)
12. Enum functions - Little factories
Takes an input
Takes a function to deal with a single element
Outputs the result
Input is NEVER changed (immutable data)
13. Enumerable
Input must be an Enumerable
Something that can be enumerated
e.g. Maps, Lists, Strings, …
Tuples, Structs are not enumerable
X elements
15. Enum.reduce
The most important function in Enum. Pretty much every other
function in Enum is built from reduce
Go through each element and collect the result
Quite complicated to wrap your head around initially but well
worth the effort - see Paul’s talk
X elements Single object/collection
f( , ) =
17. Tip
Use the function that changes your input size
to the required output size
X elements X elements
X elements Single object/collection
<= X elementsX elements
18. Conclusion
Enum module is super handy and well worth
the effort to learn, most bang for buck
Think of them as inputs, f(x), output
Deep down it's all recursion (but we can let
someone else worry about that)