If Then
From Erlang Community
(Difference between revisions)
| Revision as of 10:15, 16 November 2008 (edit) Rjmh (Talk | contribs) (If...then... construction, with no else branch) ← Previous diff |
Current revision (10:16, 16 November 2008) (edit) (undo) Rjmh (Talk | contribs) (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]] | ||
Current revision
[edit] 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?
[edit] 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.

Digg It
Del.icio.us
Reddit
Facebook
Stumble Upon
Technorati

