Haskell函数应用
问题描述:
有点新手haskell的问题,但我在Haskell的tutorial examples中遇到了这个例子。对于“查找列表的最后一个元素”,也有一些明显的版本,像Haskell函数应用
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的行为有什么不同?
答
的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'
定义一致。
答
当试图理解Haskell时,我非常依赖:t
。在这种情况下:
Prelude> :t const id
const id :: b -> a -> a
可能帮助您了解发生了什么事情。
欢迎来到10k俱乐部! – 2010-01-28 21:05:44
我想感谢学院,我的制作人,导演...... – 2010-01-28 21:08:43
loooooooool!喜欢:P – Nomics 2011-12-13 13:40:58