【问题标题】:Erlang - pattern matching with tuplesErlang - 与元组匹配的模式
【发布时间】:2017-02-10 17:28:07
【问题描述】:

如果我写简单的话:

 [X || X <- [1,2,3,4,5,6,7,8,9,10]].

它返回:

 [1,2,3,4,5,6,7,8,9,10]

如果我写:

[{a,b} || {a,b} <- [{1,2},{2,3}]].

返回

[]

简单的问题 - 为什么?

【问题讨论】:

  • 虽然下面的答案是正确的,但我想提一下,您可能打算这样做[{A,B} || {A,B} &lt;- [{1,2},{2,3}]].
  • 符号来自数学,应该以声明的方式阅读。在第二种情况下,如果您将生成器读取为“对于列表中的所有对 {A,B}”,则很清楚为什么会忽略任何不匹配的元素。除了模式之外,您还可以添加更多条件;例如,[... || {A,B} B] 只选择 A 大于 B 的对。

标签: erlang


【解决方案1】:

生成器 {a,b} 同时是一个过滤器。因此,当元素与模式不匹配时,它就会被跳过。

Erlang/OTP 19 [erts-8.2] [source] [64-bit] [smp:8:8] [async-threads:10] [hipe] [kernel-poll:false] [dtrace]

Eshell V8.2  (abort with ^G)
1>  [X || X <- [1,2,3,4,5,6,7,8,9,10]].
[1,2,3,4,5,6,7,8,9,10]
2> [{a,b} || {a,b} <- [{1,2},{2,3}]].
[]
3> [{a,b} || {a,b} <- [{1,2},{2,3},{a,b}]].
[{a,b}]
4>

你可以从learnyousomeerlang阅读更多关于列表推导的内容

7> Weather = [{toronto, rain}, {montreal, storms}, {london, fog},{paris, sun}, {boston, fog}, {vancouver, snow}].
[{toronto,rain},
 {montreal,storms},
 {london,fog},
 {paris,sun},
 {boston,fog},
 {vancouver,snow}]
8>  FoggyPlaces = [X || {X, fog} <- Weather].
[london,boston]
9>  FoggyPlaces = [X || {X, fog1} <- Weather].
** exception error: no match of right hand side value []
10>  [X || {X, fog1} <- Weather].
[]
11>

【讨论】:

    【解决方案2】:

    如果我写:

    [{A,B} || {A,B} <- [{1,2},{2,3}]].
    

    返回

    [{1,2},{2,3}]
    

    【讨论】:

    • 它只是意味着大写表示数字而小写表示原子'值'?非常感谢
    • @Kornelia:差不多,大写表示变量,小写表示原子以及'Atom with Uppercase'
    猜你喜欢
    • 2015-05-06
    • 2014-06-27
    • 1970-01-01
    • 2017-11-26
    • 2015-02-09
    • 1970-01-01
    • 1970-01-01
    • 2015-01-30
    • 2018-12-08
    相关资源
    最近更新 更多