Étude 7-2: List Comprehensions and Pattern Matching
Is it possible to use pattern matching inside a list comprehension? Try it and find out.
Presume you have this list of people’s names, genders, and ages:
People = [{"Federico", $M, 22}, {"Kim", $F, 45}, {"Hansa", $F, 30}, {"Tran", $M, 47}, {"Cathy", $F, 32}, {"Elias", $M, 50}].
Part One
In erl
(or in a module, if you prefer), write a list comprehension
that creates a list consisting of the names of all males who are over 40.
Use pattern matching
to separate the tuple into three variables, and two guards to do the
tests for age and gender.
Part Two
When you use multiple guards in a list comprehension, you get the moral
equivalent of and
for each condition you are testing. If you want an
or
condition, you must test it explicitly. Write a list comprehension
that selects the names of all the people who are male or over 40. You
will need one guard with an or
; you may also use orelse
.
Note
Because or
has higher priority than comparison operators like <
and
==
, an expression like X > 5 or X < 12
will generate an error, as
Erlang interprets it to mean X > (5 or X) < 12
. Use parentheses to force
the correct evaluation: (X > 5) or (X < 12)
. If you use orelse
, which
has a lower priority than the comparison operators, you don’t need the
parentheses, though it doesn’t hurt to have them. Another advantage of
orelse
is that it doesn’t do any unnecessary comparisons.
Get Études for Erlang now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.