gpt4 book ai didi

haskell - 了解不同的文件夹语句

转载 作者:行者123 更新时间:2023-12-01 08:58:51 26 4
gpt4 key购买 nike

我理解简单的 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/

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