by Example

If/Else


In Erlang, the `if` is an expression which can have
multiple branches.




The branches are scanned sequentially,
until a guard sequence evaluates to `true`.








If no guard sequence is true, an if_clause run-time error
will occur. If necessary, the guard `true` can be used
in the last branch, as that guard sequence is always true,
and is to be considered the `else` part.













-module (if_else).
-compile(export_all).




compare(X, Y) ->
    Result = if
        X > Y -> greater;
        X == Y -> equal;
        X < Y -> less
    end,
    io:format("~p is ~p than ~p ~n", [X, Result, Y]).





ascii(Letter) ->
    Code = if
        Letter =:= "A" -> 101;
        Letter =:= "B" -> 102;
        true -> unknown
    end,
    io:format("~p = ~p~n", [Letter, Code]).


run() ->
    compare(5, 1),
    ascii("A").
1> if_else:run().
5 is greater than 1
"A" = 101
ok


Next: Case of