With-else and refactoring to pure functions

Any of with, if and case can be used in pure functions without affecting their purity, just like conditionals like if or switch in other languages.

  • case is not a macro but a special form: it gets compiled as an erlang case expression (and it cannot introduce any side effect)
  • both with and if are macros that get expanded as case at compile time, so there are literally the same thing in terms of resulting code

So when you write:

if foo() do
  bar()
end

It is exactly the same as writing the code it would expand into:

case foo() do
  x when x in [false, nil] -> nil
  _ -> bar()
end

In this example, the purity of this expression only depends on the purity of foo/0 and bar/0.

1 Like