【问题标题】:When are brackets required for pattern matching?模式匹配何时需要括号?
【发布时间】:2015-05-10 20:21:23
【问题描述】:

使用此代码:

-- Store a person's name, age, and favourite Thing.
data Person = Person String Int Thing
  deriving Show

brent :: Person
brent = Person "Brent" 31 SealingWax

stan :: Person
stan  = Person "Stan" 94 Cabbage

getAge :: Person -> Int
getAge (Person _ a _) = a

访问 stan 使用的年龄:

getAge stan

打印: 94

定义stan不需要括号。

但是getAge Person "a" 1 Cabbage 导致错误:

<interactive>:60:8:
    Couldn't match expected type `Person'
                with actual type `String -> Int -> Thing -> Person'
    Probable cause: `Person' is applied to too few arguments
    In the first argument of `getAge', namely `Person'
    In the expression: getAge Person "a" 1 Cabbage

我需要使用括号:

*Main> getAge (Person "a" 1 Cabbage)
1

为什么在这种情况下需要括号?但是在定义stan = Person "Stan" 94 Cabbage时不需要括号?

【问题讨论】:

    标签: haskell ghci


    【解决方案1】:
    getAge Person "a" 1 Cabbage
    

    被解析为

    (((getAge Person) "a") 1) Cabbage
    

    即这必须是一个接受 Person-constructor 和另外三个参数的函数,而不是一个接受单个 Person-value 的函数。

    为什么是done this way?嗯,它使多参数函数变得更好。例如,Person 本身就是一个函数,接受三个参数(数据类型的字段)。如果 Haskell 不只是一个接一个地提供参数,你还需要写 Person ("Brent", 31, Sealingwax)

    Haskell 使用的解析规则实际上比大多数其他语言要简单得多,并且它们非常自然地允许部分应用,这非常有用。例如,

    GHCi> 地图(人“布伦特”31)[Cabbage, SealingWax]
    [人“布伦特”31卷心菜,人“布伦特”31 SealingWax]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-04
      相关资源
      最近更新 更多