我理解简单的 foldr 语句,例如

foldr (+) 0 [1,2,3]

但是,我在处理更复杂的 foldr 语句时遇到了麻烦,即在函数中带有 2 个参数的语句,以及/和 - 计算。谁能解释一下获得这些答案的步骤?
foldr (\x y -> (x+y)*2) 2 [1,3] = 22

foldr (/) 2 [8,12,24,4] = 8.0

谢谢。

最佳答案

foldr 函数定义如下:

foldr :: (a -> b -> b) -> b -> [a] -> b
foldr _ a []     = a
foldr f a (x:xs) = f x (foldr f a xs)

现在考虑以下表达式:
foldr (\x y -> (x + y) * 2) 2 [1,3]

我们将为 lambda 命名:
f x y = (x + y) * 2

因此:
foldr f 2 [1,3]
-- is
f 1 (foldr f 2 [3])
-- is
f 1 (f 3 (foldr f 2 []))
-- is
f 1 (f 3 2)
-- is
f 1 10
-- is
22

相似地:
foldr (/) 2 [8,12,24,4]
-- is
8 / (foldr (/) 2 [12,24,4])
-- is
8 / (12 / (foldr (/) 2 [24,4]))
-- is
8 / (12 / (24 / (foldr (/) 2 [4])))
-- is
8 / (12 / (24 / (4 / (foldr (/) 2 []))))
-- is
8 / (12 / (24 / (4 / 2)))
-- is
8 / (12 / (24 / 2.0))
-- is
8 / (12 / 12.0)
-- is
8 / 1.0
-- is
8.0

希望有所帮助。

关于haskell - 了解不同的文件夹语句,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23189768/

10-12 06:16