<div dir="ltr">On Thu, Jan 16, 2014 at 10:39 AM, Rich Neswold <<a href="mailto:rich.neswold@gmail.com" target="_blank">rich.neswold@gmail.com</a>> wrote:<br>> This morning I became aware of a (powerful) feature of list<br>
> comprehensions. Take the following example:<br>
><br>>     [ X + Y || {X, Y} <- L].<br>><br>> If we set L to [{1,2}, ok, {1,3}], we get the result [3,4] instead of<br>> a pattern match exception (as I was expecting.) This means that list<br>> comprehensions give you a "free" lists:filter/2 in the generator<br>

> expressions!<br><br>So having learned about the filtering abilities of comprehensions, I stumbled upon another way to use it effectively.<div><br></div><div>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):</div>

<div><br></div><div><span style="font-family:'courier new',monospace">[{{S, NC}, SF} || {S, C} <- Reqs,</span><br></div><div><font face="courier new, monospace">                  case gb_trees:lookup({S, C}, T) of</font></div>

<div><font face="courier new, monospace">                    {value, {NC, SF}} -> true;</font></div><div><font face="courier new, monospace">                    none -> false</font></div><div><font face="courier new, monospace">                  end]<br>

</font><br>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:</div><div><br></div><div><span style="font-family:'courier new',monospace">[{{S, NC}, SF} || {S, C} <- Reqs,</span><br>

</div><div><span style="font-family:'courier new',monospace">                  </span><span style="font-family:'courier new',monospace">{value, {NC, SF}} = </span><span style="font-family:'courier new',monospace">gb_trees:lookup({S, C}, T)]</span></div>

<div><br></div><div>However, I can do this:</div><div><div><span style="font-family:'courier new',monospace"><br></span></div><div><span style="font-family:'courier new',monospace">[{{S, NC}, SF} || {S, C} <- Reqs,</span><br>

</div><div><span style="font-family:'courier new',monospace">                  </span><span style="font-family:'courier new',monospace">{value, {NC, SF}} <- [</span><span style="font-family:'courier new',monospace">gb_trees:lookup({S, C}, T)]]</span></div>

<div><br></div><div>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.</div><div><br></div><div>I don't know how many people already use this trick, but I thought it might of use to others.</div>

<div><br></div>-- <br>Rich<br></div></div>