首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >关于列表类型的菜鸟Haskell lyah教程

问关于列表类型的菜鸟Haskell lyah教程
EN

Stack Overflow用户
提问于 2014-03-23 05:44:08
回答 1查看 63关注 0票数 1

这篇文章来自著名的《向你学习哈斯克尔》一书的第三章。下面的代码解释了我的问题和困惑:

代码语言:javascript
复制
-- 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]
EN

回答 1

Stack Overflow用户

发布于 2014-03-23 05:48:33

函数应用程序比Haskell中的任何中缀操作符具有更高的优先级。因此,如果您编写

代码语言:javascript
复制
head' 3:[]

它解析为

代码语言:javascript
复制
(head' 3) : []

而不是

代码语言:javascript
复制
head' (3 : [])

将head'应用于3是不正确的,因为列表通常没有Num实例,因此会出现类型错误。

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22583984

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档