折叠和折叠进一步的解释和例子 [英] foldr and foldl further explanations and examples
本文介绍了折叠和折叠进一步的解释和例子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我查看了不同的页面和一般折叠以及其他一些内容,并且它们很好地解释了它。
I've looked at different folds and folding in general as well as a few others and they explain it fairly well.
在这种情况下,lambda的工作方式仍然存在问题。
I'm still having trouble on how a lambda would work in this case.
foldr (\y ys -> ys ++ [y]) [] [1,2,3]
有人可以一步一步地尝试向我解释这一点。
Could someone go through that step by step and try to explain that to me.
此外, foldl
也能如何工作。
And also how would foldl
work as well.
推荐答案
foldr f z [] = z
foldr f z (x:xs) = x `f` foldr f z xs
And
k y ys = ys ++ [y]
:
Let's unpack:
foldr k [] [1,2,3]
= k 1 (foldr k [] [2,3]
= k 1 (k 2 (foldr k [] [3]))
= k 1 (k 2 (k 3 (foldr k [] [])))
= (k 2 (k 3 (foldr k [] []))) ++ [1]
= ((k 3 (foldr k [] [])) ++ [2]) ++ [1]
= (((foldr k [] []) ++ [3]) ++ [2]) ++ [1]
= ((([]) ++ [3]) ++ [2]) ++ [1]
= (([3]) ++ [2]) ++ [1]
= ([3,2]) ++ [1]
= [3,2,1]
这篇关于折叠和折叠进一步的解释和例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文