-
Notifications
You must be signed in to change notification settings - Fork 2
Elixir Recursion Basics
How do I use recursion in Elixir?
The easiest way to handle recursion in elixir is when parsing a list. This is nearly identical to Enum.map or Enum.reduce in most cases, but let's you see the idea behind it.
The benefit of this approach is you can add other parameters fairly easily and keep state between calls in larger examples.
To write a recursive function, you want at minimum two things: a base case, and the recursive case.
The base case is where recursion breaks and a value is returned instead of calling itself again. You can see this in the simple example below.
def sum_orders([]), do: 0
def sum_orders([order | orders]) do
order.total + sum_orders(order)
endThe final thing to be aware of in Elixir's recursion, is tail call optimization (TCO). When using recursion, as often as you possibly can make sure the last thing a function calls is itself.
The simple version of this is you will never receive a stack overflow error with TCO. So use as often as you can, this is how GenServers work.
🏳️🌈🦄 Sharing is caring. 🦄🏳️🌈
TODO: can we recreate the tag system here roughly with sections about certain subjects?