gpt4 book ai didi

haskell - 理解 Haskell 中的折叠

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

根据我对 Haskell 中折叠的理解,foldl (-) 0 [1..5] 通过计算 0- 给出了 -15 的结果1-2-3-4-5,而foldr (-) 0 [1..5]通过计算得到-5的结果>5-4-3-2-1-0。为什么 foldl (++) ""["a", "b", "c"]foldr (++) ""["a", "b", "c"] 给出 "abc" 的结果,而 foldr 的结果不是 "cba"?

在理解 foldlfoldr 之间的区别时,我是否遗漏了什么?

最佳答案

我认为this part from the docs让它更清楚:


In the case of lists, foldr, when applied to a binary operator, a starting value (typically the right-identity of the operator), and a list, reduces the list using the binary operator, from right to left:

foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...)

. . .

In the case of lists, foldl, when applied to a binary operator, a starting value (typically the left-identity of the operator), and a list, reduces the list using the binary operator, from left to right:

foldl f z [x1, x2, ..., xn] == (...((z `f` x1) `f` x2) `f`...) `f` xn

如果您查看示例分解,串联 foldr 等同于:

"a" ++ ("b" ++ ("c" ++ ""))

对于 foldl,它等同于:

(("" ++ "a") ++ "b") ++ "c"

对于字符串连接,这些是相同的。


但是对于减法,

1 - (2 - (3 - 0))

给出的结果不同于:

((0 - 1) - 2) - 3

关于haskell - 理解 Haskell 中的折叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52044046/

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