We can use the concept of guards with pattern matching to implement somewhat complex functions as simple ones. For instance, let’s say we have a function where we want to implement the Fibonacci sequence in elixir. The simplest way for handling fibonacci functions is to use recusion, for instance:
defmodule Math do def fibonacci(x) when x <= 1, do: x def fibonacci(x), do: fibonacci(x - 1) + fibonacci(x - 2) end
Although this might look complex from the outset, it’s a fairly succinct method for defining such a complex algorithm.
Erlang (and elixir) implement recursive functions efficiently, so we can rely on recursive statements as a safe, fast method for dealing with recursive functions.
One operator that we’ll see often is the pipe operator
|> pipe operator looks scary but really just passes the result of one function on to the next function. Conceptually, it’s like running the function:
The equivalent version using pipes is
b(:atom) |> d() |> f()
pipe operator helps our code stay clean and readable. We’ll use it for cases where we want to transform a request type.
Go on to Creating a Chat App.
Go back to Guards and Pattern Matching.