← Back to list

An anonymous recursive function in Elixir

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…

Mohamed Elsharnouby · 2018-02-02 16:39 · 133 claps · 0.5 min read
#elixir #functional-programming
Open on Medium ↗
Wiki topics: 💻 · Programming 🔬 · Science · General

An anonymous recursive function in Elixir

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.

[embed]

Until Elixir introduces a better way to do it.

That’s all folks


메타데이터
post_id
2fe1e5e89e59
slug
an-anonymous-recursive-function-in-elixir-2fe1e5e89e59
url
https://medium.com/@sharno/an-anonymous-recursive-function-in-elixir-2fe1e5e89e59
canonical_url
https://medium.com/@sharno/an-anonymous-recursive-function-in-elixir-2fe1e5e89e59
author_url
https://medium.com/@sharno
status
ok
fetched_at
2026-06-11 22:20:54