Erlang list matching -
i'm working through book thinking in erlang. in "figure 10: example of case" has following example:
many(x) -> case x of [] -> none; [ _one ] -> one; [ _one, _two ] -> two; [ _one, _two , _three | _tail ] -> many end. it says :
if wondering why line 9 not match against [ _one, _two | _tail ], review list matching rules list tails @ end of previous section.
but if match against [ _one, _two | _tail ] still works expected. there error in book or getting wrong ?
i think might not error.
the semantics of
[_one, _two, _three | _tail] is list of 3 elements or more.
the semantics of
[_one, _two | _tail] is list of 2 elements or more.
since third pattern [ _one, _two ] indicates case "a list of 2 elements", using [_one, _two | _tail] little bit redundant.
there reason "everything's working expected". if place fourth pattern before third one, gives:
many(x) -> case x of [] -> none; [_one] -> one; [_one, _two | _tail] -> %% switched many; [_one, _two] -> %% switched 2 end. then won't work expected. mod:many([a,b]) yield many instead of expected two. because when "case" expression evaluated, x matched in turn against patterns. , sequential order guaranteed. many returned because [a,b] matches [_one, _two | _tail] first, _tail being [](an empty list).
so, though [ _one, _two | _tail ] work in case, using [ _one, _two , _three | _tail ] considered practice in case switch patterns afterwards.
Comments
Post a Comment