gpt4 book ai didi

function - 为什么这些褶皱停在头/尾?

转载 作者:行者123 更新时间:2023-12-03 14:31:49 24 4
gpt4 key购买 nike

我正在阅读 learnyouahaskell.com,目前正在研究折叠。书中有这些例子:

maximum' :: (Ord a) => [a] -> a  
maximum' = foldr1 (\x acc -> if x > acc then x else acc)

reverse' :: [a] -> [a]
reverse' = foldl (\acc x -> x : acc) []

product' :: (Num a) => [a] -> a
product' = foldr1 (*)

filter' :: (a -> Bool) -> [a] -> [a]
filter' p = foldr (\x acc -> if p x then x : acc else acc) []

head' :: [a] -> a
head' = foldr1 (\x _ -> x)

last' :: [a] -> a
last' = foldl1 (\_ x -> x)

除了 head'我都懂和 tail' .

我的理解是二元函数应该依次应用于累加器和列表中的每个元素,从而遍历所有列表。为什么这会停在头部(或尾部)?

我明白 _ (下划线)表示“随便”或“我不在乎”,但这如何停止遍历所有列表?

最佳答案

一个文件夹组合了两个项目——当前的“运行总计”项目和新项目。
(\x _ -> x)获取新项目并丢弃它,保留原始项目,因此所有剩余项目都将被忽略。

让我们扩展它:

foldr1 (\x _ -> x) [1..100000]
= (\x _ -> x) 1 (foldr (\x _ -> x) [2..100000])
= 1

(foldr (\x _ -> x) [2..100000])不需要 term ,它没有被评估(这是在行动中的懒惰评估,或者更确切地说是不作为),所以它运行得很快。

(\_ x -> x) ,新项目被采用,旧项目被忽略——这种情况一直发生到列表的末尾,所以你得到了最后一个元素。它并没有避免其他的,它只是忘记了除了最后一个之外的所有其他的。

一个更易于理解的名称 (\_ x -> x)指的是它忽略它的第一个参数并返回它的第二个参数的事实。我们叫它 secondArg .
foldl1 (\_ x -> x) [1..4]
= let secondArg = (\_ x -> x) in foldl secondArg 1 [2..4]
= foldl (1 `secondArg` 2) [3..4]
= foldl ((1 `secondArg` 2) `secondArg` 3) [4]
= foldl (((1 `secondArg` 2) `secondArg` 3) `secondArg` 4) []
= (((1 `secondArg` 2) `secondArg` 3) `secondArg` 4)
= 4

关于function - 为什么这些褶皱停在头/尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16678440/

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