Multiple filters in list comprehension in Erlang

只谈情不闲聊 提交于 2019-12-10 10:24:46

问题


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].
[london,boston]

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].
[vancouver,vancouver]

where I was expecting [london,boston,vancouver].

How can I include multiple filters?


回答1:


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.



来源:https://stackoverflow.com/questions/14321265/multiple-filters-in-list-comprehension-in-erlang

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!