[erlang-questions] wierd outome on my match method

Jesper Louis Andersen jesper.louis.andersen@REDACTED
Sat Jan 31 16:40:55 CET 2015

On Sat, Jan 31, 2015 at 3:11 PM, Roelof Wobben <r.wobben@REDACTED> wrote:

> match_key( Key, [Head | Tail], List ) ->
>   case element(1, Head) of
>     Key -> match_key(Key, Tail, [element(2,Head) | List] );
>     _ -> match_key(Key, Tail,  List )
>    end.

This is a very imperative solution to the matcher. If you have a tuple, T =
{X, Y} you can use element(1, T) and element(2, T) to project the X and Y
elements "out of" the tuple. The equation rule is:

T = {element(1, T), element(2, T)},

That is, if we split the tuple and reform it, we obtain the same tuple

But there is another semantics possible, namely matching. Most main-stream
languages did not add this form since it was not commonly known at the
time, but for some problems, it is a far more succinct:

T = case T of {X, Y} -> {X, Y} end,

which, we can use to rewrite the code:

match_key(K, [H|T], L) ->
  case H of
    {K, V} -> match_key(K, T, [V | L]);
    _ -> match_key(Key, T, L)

Note how this is more direct[0], since we don't have to worry about
projecting out of `Head` anymore. We simply match on H and depending on the
match, we do the right thing. If the key matches, then the value, V, is
already deconstructed, so we can avoid having to write that.

Now, we can refactor some more. The match can be carried out at the top
level of the function:

match_key(_K, [], L) -> L;
match_key(K, [{K, V} | T], L) -> match_key(K, T, [V | L]);
match_key(K, [_ | T], L) -> match_key(K, T, L).

which should remove a lot of clutter and make the function operate on the
structure of the 2nd argument directly.

[0] It avoids what is called boolean blindness.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20150131/0e9b8d6f/attachment.htm>

More information about the erlang-questions mailing list