这是着名的Learn You a Haskell一书中的第3章。我的问题和困惑在此代码中解释:
-- simple lyah tutorial function. by itself this makes sense.
head' :: [a] -> a
head' [] = error "'head' on empty list"
head' (x:_) = x
-- It is my understanding that [3] is the same as 3:[]. Why do they don't work the same?
head' [3] -- works. returns 3.
head' 3:[] -- doesn't work. I can not understand error.
head' (3:[]) -- works. returns 3.
-- Now in GHCi, I can look at the types.
-- Why do some use the variable name t and the others use a?
-- Beyond the t/a discrepancy, the types are identical. why?
*Main> :t [3]
[3] :: Num t => [t]
*Main> :t (3:[])
(3:[]) :: Num a => [a]
*Main> :t 3:[]
3:[] :: Num a => [a]
答案 0 :(得分:8)
函数应用程序的优先级高于Haskell中的任何中缀运算符。因此,如果你写
head' 3:[]
它解析为
(head' 3) : []
而不是
head' (3 : [])
将head'
应用于3
并不是正确的,因为列表通常没有Num
个实例,因此您可以获得类型错误。