Erlang Control Flow Statement

Erlang Control Flow Statement

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
if
  BoolbeanExpression1 ->
    IfBody1;
  BooleanExpression2 ->
    IfBody2;
    ...
  true ->
    BodyCathAll
end

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
is_greater_than(X, Y) ->
  if
    X > Y ->
      true;
    true ->
      false
  end

Case Statement

Syntax:

1
2
3
4
5
6
7
8
case Expression of
  Value1 [when Guard1] ->
    CaseBody1;
  Value2 [when Guard2]->
    CaseBody2;
  _Other ->
    CaseBodyCatchAll
end

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
check(List) when is_list(List) ->
  case lists:reverse(List) of
    List ->
      true;
    _ ->
      false
    end;
check(_) ->
    {error, arg_not_list}.