有点新手问题,但我在Haskell的教程示例中遇到了这个例子.对于"查找列表的最后一个元素",有一些明显的版本,比如
last' [x] = x
last' (_:xs) = last' xs
Run Code Online (Sandbox Code Playgroud)
但我无法理解所提出的替代版本:
myLast' = foldr1 (const id)
Run Code Online (Sandbox Code Playgroud)
所以,在尝试理解id函数的应用程序正在做什么时,我尝试了ghci:
const id 1 2 -> gives 2
Run Code Online (Sandbox Code Playgroud)
这绑定如下:
(const id) 1 2 -> gives 2
Run Code Online (Sandbox Code Playgroud)
而不是这样的:
const (id 1) 2 -> gives 1
Run Code Online (Sandbox Code Playgroud)
但我没理解这一点.(const id)应该翻译成类似的东西
`(\x y->x) (\x->x)`
Run Code Online (Sandbox Code Playgroud)
这不应该返回一个只返回其第一个元素的id的函数吗?或者,函数顺序(const id)与const的行为有何不同?
Chr*_*way 30
定义const是
const x = \_ -> x
Run Code Online (Sandbox Code Playgroud)
因此,(const id)是一个函数,它接受一个参数并始终返回id和
const id 1 2 = (\_ -> id) 1 2
= id 2
= 2
Run Code Online (Sandbox Code Playgroud)
定义foldr1是
foldr1 f [x] = x
foldr1 f (x:xs) = f x (foldr1 f xs)
Run Code Online (Sandbox Code Playgroud)
如果我们有
myLast' = foldr1 (const id)
Run Code Online (Sandbox Code Playgroud)
然后
myLast' [x] = foldr1 (const id) [x]
{- definition of foldr1 -}
= x
Run Code Online (Sandbox Code Playgroud)
和
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
Run Code Online (Sandbox Code Playgroud)
这与...的定义一致last'.
:t在尝试理解Haskell时,我非常依赖.在这种情况下:
Prelude> :t const id
const id :: b -> a -> aRun Code Online (Sandbox Code Playgroud)
可能会帮助你了解发生了什么.
| 归档时间: |
|
| 查看次数: |
2410 次 |
| 最近记录: |