Erlang Central

If Then

From ErlangCentral Wiki

Problem

You want the equivalent of if...then... in other programming languages.

For example, to print a list if it is non-empty, you could write

case L/=[] of
  true ->
    io:format("~p~n",[L]);
  false ->
    ok
end

or

if L/=[] -> io:format("~p~n",[L]);
   true  -> ok
end

but in both cases you have to include an "else" branch that is just noise.

How can you avoid this?

Solution

Use

[io:format("~p~n",[L]) || L/=[]]

instead.

This is a list comprehension without a generator. If L/=[] is true, then it evaluates the io:format call (and returns its result in a list of one element), while if it is false, then it just returns the empty list.

This generates a compiler warning, but if you can put up with that, then it's a concise and readable notation. As of Erlang/OTP R13A, this does not generate a compiler warning (ticket OTP-7846).

As of Erlang/OTP R13A (ticket OTP-7748), the operators
orelse
and
andalso
no longer require their second argument to be a boolean, so you can use the following Perl-inspired patterns:
L /= [] andalso io:format("~p~n",[L])
L == [] orelse io:format("~p~n",[L])