Erlang Central

Difference between revisions of "If Then"

From ErlangCentral Wiki

(If...then... construction, with no else branch)
 
(If...then... construction, with no else branch)
Line 31: Line 31:
  
 
This generates a compiler warning, but if you can put up with that, then it's a concise and readable notation.
 
This generates a compiler warning, but if you can put up with that, then it's a concise and readable notation.
 +
[[Category:CookBook]]

Revision as of 10:16, 16 November 2008

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.