Elixir notes from a NodeJs Developer’s perspective — part IV (recursive functions)
1 min readSep 29, 2021
Notes on using recursive functions with Elixir
- An example of recursive functions in use (you need to define a module to use
def
)
defmodule Factorial do
def of(0), do: 1
def of(n) when n > 0 do
n * of(n-1)
end
endIO.puts(Factorial.of(12))
- Using recursive functions via anonymous functions might not be readable and might seem tricky. See more https://github.com/jisaacstone/ex_rfn
- Y-Combinator full example:
iex(1)> yc = fn f -> (fn x -> x.(x) end).(fn y -> f.(fn arg -> y.(y).(arg) end) end) endiex(2)> fac = fn f -> fn n -> if n < 2 do 1 else n * f.(n-1) end end endiex(3)> for i <- 0..9, do: yc.(fac).(i)
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]iex(4)> fib = fn f -> fn n -> if n == 0 do 0 else (if n == 1 do 1 else f.(n-1) + f.(n-2) end) end end endiex(5)> for i <- 0..9, do: yc.(fib).(i)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]