为什么foldBack无法执行与fold相同的副作用? [英] Why does foldBack not execute the same side-effects that fold does?
问题描述
我正在研究 List.fold和List.foldBack之间的区别的示例,试图让我绕过fold
和foldBack
之间的差异.我现在了解了应用程序顺序的差异,但是我不了解副作用的差异.
I was working through the answers to Example of the difference between List.fold and List.foldBack trying to get my head around the difference between fold
and foldBack
. I understand the difference in application order now, but there's a difference in side-effects that I don't understand.
我使用了 List.fold
和
I used List.fold
and List.foldBack
for my testing. My accumulator functions that were basically equivalent to ::
, so that accumulation order would matter. The accumulator functions I used were as follows:
let f acc x =
// printfn "Folding %A into %A" x acc // Side-effect!
x :: acc
let f2 x acc =
// printfn "Folding %A into %A" x acc // Side-effect!
x :: acc
我从F#参考资料中了解到:
I understand from the F# reference that:
List.fold f [] [1; 2; 3; 4; 5] = (f (f (f (f (f [] 1) 2) 3) 4) 5)
和:
List.foldBack f2 [] [1; 2; 3; 4; 5] = (f2 1 (f2 2 (f2 3 (f2 4 (f2 5 [])))))
都应该返回true
,并且确实如此.太好了,我想;我了解它是如何工作的.但是只是为了确保,我取消了f
和f2
的副作用行的注释,然后再次运行List.fold f
和List.foldBack f2
. List.fold f [] [1; 2; 3; 4; 5]
的结果,其中printfn
行未注释:
should both return true
, and they do. Great, I thought; I understand how it works. But just to make sure, I uncommented the side-effect lines from f
and f2
and ran List.fold f
and List.foldBack f2
again. Result of List.fold f [] [1; 2; 3; 4; 5]
with the printfn
line uncommented:
Folding 1 into []
Folding 2 into [1]
Folding 3 into [2; 1]
Folding 4 into [3; 2; 1]
Folding 5 into [4; 3; 2; 1]
val it : bool = true
List.foldBack f2 [] [1; 2; 3; 4; 5]
的结果,其中printfn
行未注释:
Result of List.foldBack f2 [] [1; 2; 3; 4; 5]
with the printfn
line uncommented:
val it : bool = true
我希望折叠N到[列表]"在这两种情况下都会出现.但是List.fold
执行了其累加器功能的副作用,而List.foldBack
没有执行.
I was expecting "Folding N into [list]" to show up in both cases. But List.fold
executed the side effects of its accumulator function, and List.foldBack
did not.
为什么fold
的两种形式之间的副作用执行方式有所不同?
Why is there a difference in side-effect execution between the two forms of fold
?
推荐答案
您输入的参数顺序错误.
You have the arguments in the wrong order.
应该是
> List.foldBack f2 [1; 2; 3; 4; 5] [];;
Folding 5 into []
Folding 4 into [5]
Folding 3 into [4; 5]
Folding 2 into [3; 4; 5]
Folding 1 into [2; 3; 4; 5]
val it : int list = [1; 2; 3; 4; 5]
这篇关于为什么foldBack无法执行与fold相同的副作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!