Home > DeveloperSection > Forums > Multiple filters in list comprehension in Erlang
sandy taylor
sandy taylor

Total Post:46

Posted on    May-22-2015 4:29 AM

 erlang Functional Programming  Concurrent Programming  OTP 

 1 Reply(s)
 915  View(s)
Rate this:
Say I have a list that contains weather:

1> Weather = [{toronto, rain}, {montreal, storms}, {london, fog}, 
    {paris, sun}, {boston, fog}, {vancouver, snow}].
To get foggy places, I could do this:

2> FoggyPlaces = [X || {X, fog} <- Weather].
Now I want to retrieve places that are both foggy and snowy. I tried this, but it retrieves only snowy places,

3> FoggyAndSnowyPlaces = [X || {X, fog} <- Weather, {X,snow} <- Weather].
where I was expecting [london,boston,vancouver].

How can I include multiple filters?

Mayank Tripathi
Mayank Tripathi

Total Post:397

Posted on    May-22-2015 8:07 AM

FoggyAndSnowyPlaces = [X || {X, Y} <- Weather, (Y == fog) or (Y == snow)].
You are confusing generators (Pattern <- List) and filters (boolean conditions). Multiple generators work like nested loops in other languages, so in your 3> you get vancouver twice because the first generator produces two values.

Don't want to miss updates? Please click the below button!

Follow MindStick