Search code examples
erlangerlang-shell

Erlang if statement and returns true


I'm wondering ,the idea behind the erlang's if statement and the return value (in this case true->true). this is my code snippet

if
 (Velocity > 40) -> io:format(" processing fast !~n") ;
 true -> true
end,

I know Erlang doesn't allow you to have an if without a true statement option. but even i can use true->false but it doesn't matter to the final output.

Actually what is the idea behind in if clause and return value.


Solution

  • Erlang's if is a simple pattern match on boolean expressions and returns a result.

    It really just requires that something matches, you don't need the "true -> true" case at all

    for example:

    if
     (Velocity > 40) -> io:format(" processing fast !~n") ;
     (Velocity < 40) -> io:format(" processing slow !~n") ;
     (Velocity == 40) -> io:format(" processing eh !~n") 
    end,
    

    There is no "true ->" case, but there is also no chance that it doesn't match one of the patterns.

    The reason for this is that "if" is also an expression (like everything in erlang) so, you can do something like:

    X = if 
         (Vel > 40) -> 10;
         (Vel < 40) -> 5
        end,
    

    If Vel == 40, what is the value of X? It would be undefined, so erlang requires that you always have a match.

    The common thing when you don't want to specify an exhaustive match is to use true, like:

    X = if 
         (Vel > 40) -> 10;
         (Vel < 40) -> 5;
         true -> 0
        end,
    

    In the last case, X always has a value (10, 5 or 0)

    Make sense?