Search⌘ K

Using Recursion with Anonymous Functions

Explore how recursion works with anonymous functions in Elixir and understand the challenges of defining self-referential functions. Learn techniques like function wrapping and delayed evaluation to implement recursive anonymous functions. This lesson teaches you how to create factorial functions using anonymous recursion and introduces the capturing operator to reference named recursive functions effectively.

We'll cover the following...

Problems with anonymous functions

We’ve created and practiced many examples using recursion and named functions. When we make recursive functions, we call functions that have the same name as the function that we’re creating, and it has been working great. The compiler knows how to use that function-name reference to call the function that we are creating. But in the world of anonymous functions, it’s not that easy. We often face problems in the definition of anonymous functions. Let’s see the problems in action, creating the factorial example using anonymous functions:

iex> factorial = fn 
>   0 -> 1
>   x when x > 0 -> x
...