[erlang-questions] List comprehension question
Rich Neswold
rich.neswold@REDACTED
Thu May 22 21:44:25 CEST 2014
On Thu, Jan 16, 2014 at 10:39 AM, Rich Neswold <rich.neswold@REDACTED>
wrote:
> This morning I became aware of a (powerful) feature of list
> comprehensions. Take the following example:
>
> [ X + Y || {X, Y} <- L].
>
> If we set L to [{1,2}, ok, {1,3}], we get the result [3,4] instead of
> a pattern match exception (as I was expecting.) This means that list
> comprehensions give you a "free" lists:filter/2 in the generator
> expressions!
So having learned about the filtering abilities of comprehensions, I
stumbled upon another way to use it effectively.
I have a list of data that needs to be transformed, but some of resulting
data is pulled from a lookup table (I'm using gb_trees.) I can do the
following (please ignore the short variable names; I'm trying to emphasis
the generators and filters):
[{{S, NC}, SF} || {S, C} <- Reqs,
case gb_trees:lookup({S, C}, T) of
{value, {NC, SF}} -> true;
none -> false
end]
It would be much nicer to use pattern matching and use the comprehension's
ability to treat bad matches as a filter. But I can't replace the case
statement above with:
[{{S, NC}, SF} || {S, C} <- Reqs,
{value, {NC, SF}} = gb_trees:lookup({S, C}, T)]
However, I can do this:
[{{S, NC}, SF} || {S, C} <- Reqs,
{value, {NC, SF}} <- [gb_trees:lookup({S, C}, T)]]
Wrap the function in a single element array and now you have a generator!
Now I can add more filters or more generators to it.
I don't know how many people already use this trick, but I thought it might
of use to others.
--
Rich
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20140522/00c0ebaa/attachment.htm>
More information about the erlang-questions
mailing list