Question

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.

Was it helpful?

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?

OTHER TIPS

In Erlang everything is an expression that returns a value. You don't need the true -> true statement, however, if you don't include it and there are no matches, an error will be raised because it's impossible for the interpreter to determine the return value of the expression.

It's a feature of the language.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top