With-else and refactoring to pure functions

In your are working toward a true state machine and want to refactor code that isn’t comprised of pure functions, do you need to refactor with-else and if-else? If so, what’s the recommended best practice?

Also I was thinking this might be the case for “case” until I learned it was a macro for a group of functions.

Any assertions on my part have not been tested so please correct the premise of my question if I’m totally off-base.

Thanks!

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