[erlang-questions] List comprehension question

Dmitry Kolesnikov dmkolesnikov@REDACTED
Mon May 26 10:50:17 CEST 2014


Hello,

Your fist suggestion fails in shell with
* 1: variable 'NC' unsafe in 'case' (line 2)

The last suggestion with two generators looks pretty cool. 
I’ve got an impression that its complexity is N * log(N). 
This technique has not been highlighted anywhere in Erlang documentation :-(

Thanks for sharing

Best Regards, 
Dmitry

On 22 May 2014, at 22:44, Rich Neswold <rich.neswold@REDACTED> wrote:

> 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
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions

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


More information about the erlang-questions mailing list