gpt4 book ai didi

Haskell 函数应用

转载 作者:行者123 更新时间:2023-12-03 12:07:42 25 4
gpt4 key购买 nike

有点像新手 Haskell 的问题,但我在 Haskell 的 tutorial examples 中遇到了这个示例.对于“查找列表的最后一个元素”,有一些明显的版本,比如

last' [x] = x
last' (_:xs) = last' xs

但我无法理解呈现的替代版本:
myLast' = foldr1 (const id)

因此,为了理解 id 函数的应用程序在做什么,我在 ghci 中进行了尝试:
const id 1 2 -> gives 2

这像这样绑定(bind):
(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 函数应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/342954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com