考虑到它对我来说似乎是一项非常强大的 Assets ,我正试图深入研究。但是,你能帮我解决这个问题吗:

foldr  (/) 2 [1,2,3] -- (1/(2/(3/2))), result 0,75 {where 2 is base)
foldr1 (/)   [2,2,3] -- (1/(2/(3/2))), result 3.00 {where 2 is base)

我想我正在认真监督褶皱之间的本质区别。谢谢

最佳答案

foldr :: (a -> b -> b) -> b -> [a] -> b 具有作为实现:

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

所以这意味着如果我们输入 foldr f z [x1, x2, x3] ,那么它被评估为:
   foldr f z [x1, x2, x3]
-> f x1 (foldr f z [x2, x3])
-> f x1 (f x2 (foldr f z [x3]))
-> f x1 (f x2 (f x3 (foldr f z [])))
-> f x1 (f x2 (f x3 z))

因此,对于您的示例,它将评估为:
  (/) 1 ((/) 2 ((/) 3 2))
= 1 / (2 / (3 / 2))
= 1 / (2 / 1.5)
= 1 / 1.33333...
= 0.75
foldr1 :: (a -> a -> a) -> [a] -> a 函数几乎相似,除了如果我们看到一个 1 元素的列表,我们返回那个元素,所以区别是:
foldr1 :: (a -> a -> a) -> [a] -> a
foldr1 _ [x] = x
foldr f (x:xs) = f x (foldr1 f xs)

所以这意味着对于 foldr1 f [x1, x2, x3] 我们得到:
   foldr1 f [x1, x2, x3]
-> f x1 (foldr1 f [x2, x3])
-> f x1 (f x2 (foldr1 f [x3]))
-> f x1 (f x2 x3))

所以对于样本输入,我们得到:
  (/) 2 ((/) 2 3)
= 2 / (2 / 3)
= 2 / 0.6666...
= 3.0

因此,如果 zxi 具有相同的类型,则 foldr f z [x1, ..., xn] 等于 foldr1 f [x1, ..., xn, z]

关于haskell - foldr 和 foldr1 Haskell,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48611896/

10-10 14:13