Circling your prey with Recursion in Elixir
Looping is a very common construct in programming, It is usually how we handle sets of data we almost always want to apply some transformation to sets filtered by certain constraints.
Say you have a budget app and it has a list of items that need to be bought let’s go about finding a total.
Here is our simple example that uses multiple clauses which happen when several functions have the same name however elixir uses pattern matching to determine what function to run depending on the parameters provided when binding the function.
Recursion is incredibly common in Elixir
So what is happening in the example
Here we see we have a totaller function within a total module. This function takes in a list and default sum value then proceeds to calculate the current total by adding the head of the list to it.
Note that the last thing this function does is call itself here elixir knows that this function is recursive and uses Tail Call Optimization for efficiency.
Recursion is incredibly common in elixir however actions such as traversing through lists and sets are provided for in the Enum module. We will rarely use recursion for such operations.
How do you use recursion?
Back to code 😝
State is can be maintained in Elixir through recursion