有点新手问题,但我在Haskell的tutorial examples中遇到了这个例子。对于“查找列表的最后一个元素”,有一些明显的版本,比如
last' [x] = x
last' (_:xs) = last' xs
但我无法理解所提出的替代版本:
myLast' = foldr1 (const id)
所以,在尝试理解id函数的应用程序正在做什么时,我尝试了ghci:
const id 1 2 -> gives 2
这样绑定:
(const id) 1 2 -> gives 2
而不是这样:
const (id 1) 2 -> gives 1
但我没理解这一点。 (const id)
应转换为类似
`(\x y->x) (\x->x)`
这不应该返回一个只返回其第一个元素的id的函数吗?或者,函数顺序(const id)与const的行为有何不同?
答案 0 :(得分:30)
const
的定义是
const x = \_ -> x
因此,(const id)
是一个函数,它接受一个参数并始终返回id
和
const id 1 2 = (\_ -> id) 1 2
= id 2
= 2
foldr1
的定义是
foldr1 f [x] = x
foldr1 f (x:xs) = f x (foldr1 f xs)
如果我们有
myLast' = foldr1 (const id)
然后
myLast' [x] = foldr1 (const id) [x]
{- definition of foldr1 -}
= x
和
myLast' (x:xs) = foldr1 (const id) (x:xs)
{- definition of foldr1 -}
= (const id) x (foldr1 (const id) xs)
{- definition of const -}
= (\_ -> id) x (foldr1 (const id) xs)
{- function application -}
= id (foldr1 (const id) xs)
{- definition of id -}
= foldr1 (const id) xs
{- definition of myLast' -}
= myLast' xs
同意last'
的定义。
答案 1 :(得分:9)
在尝试理解Haskell时,我非常依赖:t
。在这种情况下:
Prelude> :t const id
const id :: b -> a -> a
可能会帮助您了解发生了什么。