使用此代码:
-- 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时不需要方括号吗?
发布于 2015-05-10 20:27:33
getAge Person "a" 1 Cabbage被解析为
(((getAge Person) "a") 1) Cabbage也就是说,这必须是一个接受Person-constructor的函数和另外三个参数,而不是一个接受单个Person-value的函数。
为什么是这样做的?嗯,它使多参数函数更好。例如,Person本身就是一个函数,包含三个参数(数据类型的字段)。如果Haskell不只是一个接一个地输入参数,您还需要编写Person ("Brent", 31, Sealingwax)。
Haskell使用的解析规则实际上比大多数其他语言要简单得多,它们非常自然地允许部分应用,这是非常有用的。例如,
GHCi>地图(个人“布伦特”31)甘蓝,SealingWax
https://stackoverflow.com/questions/30156255
复制相似问题