1
votes

I wrote a simple function in Erlang which converts a tuple to list. But I don't understand why pattern matching order matters here :

Example

tupleToList(Tuple) -> tupleToList(Tuple, size(Tuple), []).
tupleToList(_, 0, L) -> L;
tupleToList(Tuple, S, L) -> tupleToList(Tuple, S - 1, [element(S, Tuple) | L]).

Why is the following code not correct?

tupleToList(Tuple) -> tupleToList(Tuple, size(Tuple), []).
tupleToList(Tuple, S, L) -> tupleToList(Tuple, S - 1, [element(S, Tuple) | L]);
tupleToList(_, 0, L) -> L.
1

1 Answers

5
votes

Because that's how functions work in Erlang:

If the function is found, the function clauses are scanned sequentially until a clause is found that fulfills both of the following two conditions:

  • The patterns in the clause head can be successfully matched against the given arguments.
  • The guard sequence, if any, is true.

Since variables match everything, and there's no guard sequence, the tupleToList(Tuple, S, L) clause is always chosen in the second case, before the tupleToList(_, 0, L) is ever considered.