假设我有一个包含天气的列表:
1> Weather = [{toronto, rain}, {montreal, storms}, {london, fog},
{paris, sun}, {boston, fog}, {vancouver, snow}].
Run Code Online (Sandbox Code Playgroud)
为了得到有雾的地方,我可以这样做:
2> FoggyPlaces = [X || {X, fog} <- Weather].
[london,boston]
Run Code Online (Sandbox Code Playgroud)
现在我想要检索有雾和多雪的地方.我尝试了这个,但它只检索了雪地,
3> FoggyAndSnowyPlaces = [X || {X, fog} <- Weather, {X,snow} <- Weather].
[vancouver,vancouver]
Run Code Online (Sandbox Code Playgroud)
在我期待的地方[london,boston,vancouver].
如何添加多个过滤器?
Ale*_*nov 13
FoggyAndSnowyPlaces = [X || {X, Y} <- Weather, (Y == fog) or (Y == snow)].
Run Code Online (Sandbox Code Playgroud)
你混淆了generator(Pattern <- List)和过滤器(布尔条件).多个生成器的工作方式类似于其他语言的嵌套循环,所以在你的工作中3>你会得到vancouver两次因为第一个生成器生成两个值
| 归档时间: |
|
| 查看次数: |
3222 次 |
| 最近记录: |