Using Recursion with Anonymous Functions

We’ve created and practiced many examples using recursion and named functions. When we create recursive functions, we call functions that have the same name of 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 creating. It’s very practical! But in the world of anonymous functions, it’s not that easy—we face problems in the anonymous functions’ definition. Let’s see the problems in action, creating the factorial example using anonymous functions:

 iex>​ factorial = ​fn
  0 -> 1
  x when x > 0 -> x ​*​ factorial.(x - 1)
 end
 **​ (CompileError) undefined function factorial/0

We can’t do a recursive ...

Get Learn Functional Programming with Elixir now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.