这篇文章来自著名的《向你学习哈斯克尔》一书的第三章。下面的代码解释了我的问题和困惑:
-- 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]发布于 2014-03-23 05:48:33
函数应用程序比Haskell中的任何中缀操作符具有更高的优先级。因此,如果您编写
head' 3:[]它解析为
(head' 3) : []而不是
head' (3 : [])将head'应用于3是不正确的,因为列表通常没有Num实例,因此会出现类型错误。
https://stackoverflow.com/questions/22583984
复制相似问题