As we saw in the previous post, pattern matching with different function clauses can be used in order to control the execution flow in Erlang. Erlang also provides the if, case, and receive control flow constructs that can be used in a function body. In this post I will only present the if and casestatements since receive is used for message passing and I will write a dedicated post about the subject. Both if and case are similar to the statements of other programming languages.
If Statement
Syntax:
1 2 3 4 5 6 7 8 9 |
|
The different clauses, except the last one are like “else if” in other languages, while the last one (true ->) is like the “else”; it succeeds when all the previous clauses have failed.
Example:
1 2 3 4 5 6 7 |
|
Case Statement
Syntax:
1 2 3 4 5 6 7 8 |
|
Notice that the last clause (_Other) is like the default clause in other programming languages. The Expression should always return a value (if it is a function call) that will be used to perform the pattern matching.
Example:
1 2 3 4 5 6 7 8 9 |
|