An anonymous recursive function in Elixir

Mohamed Elsharnouby
1 min readFeb 2, 2018

As I was experimenting in iex I needed to make a recursive anonymous function as I was lazy to write a module for just experimenting. Sadly, Elixir doesn’t have a way to create an anonymous recursive function yet because the right-hand side is always evaluated before the left-hand side and hence the name of the function is undefined inside its body.

We have to do a little trick and pass the function to itself when calling it to get recursion. The first code example shows this in a simple way. The problem though is it looks ugly if we’re designing an API, so to overcome this we have to wrap this function in another to expose a cleaner API.

Until Elixir introduces a better way to do it.

That’s all folks

--

--

Mohamed Elsharnouby

Software Engineer. Starter of many unfinished things. Love hiking.