我们从 foldr(\ a〜(x,y)->((a:y,x))([],[])[1,2,3,4,5] .这里的 a 是列表的第一个元素,而(x,y)的开头是([[],[]),所以(a:y,x)返回([1],[]).输入列表的下一个元素是 a = 2 ,而(x,y)=([1],[]),所以(a:y,x)=([2],[1]).请注意,列表的顺序已交换.每次迭代将再次交换列表.但是,输入列表的下一个元素将始终添加到第一个列表中,这就是拆分的方式.输入列表的下一个元素是 a = 3 和(x,y)=([2],[1]),所以(a:y,x)=([3,1],[2]).输入列表的下一个元素是 a = 4 和(x,y)=([3,1],[2]),所以(a:y,x)=([4,2],[3,1]).输入列表的下一个元素是 a = 4 和(x,y)=([4,2],[3,1]),因此(a:y,x)=([5,3,1],[4,2]).没有更多元素了,所以返回值为([5,3,1],[4,2]).如演练所示,split函数的工作方式是维护两个列表,在每次迭代时交换它们,并将输入的每个元素附加到另一个列表中.This is a follow up to my previous question.I am trying to understand the list splitting example in Haskell from here:foldr (\a ~(x,y) -> (a:y,x)) ([],[])I can read Haskell and know what foldr is but don't understand this code. Could you walk me through this code and explain it in more details ? 解决方案 Let’s try running this function on a sample input list, say [1,2,3,4,5]:We start with foldr (\a ~(x,y) -> (a:y,x)) ([],[]) [1,2,3,4,5]. Here a is the first element of the list, and (x,y) start out as ([],[]), so (a:y,x) returns ([1],[]).The next element of the input list is a = 2, and (x,y) = ([1],[]), so (a:y,x) = ([2],[1]). Note that the order of the lists has swapped. Each iteration will swap the lists again; however, the next element of the input list will always be added to the first list, which is how the splitting works.The next element of the input list is a = 3, and (x,y) = ([2],[1]), so (a:y,x) = ([3,1],[2]).The next element of the input list is a = 4, and (x,y) = ([3,1],[2]), so (a:y,x) = ([4,2],[3,1]).The next element of the input list is a = 4, and (x,y) = ([4,2],[3,1]), so (a:y,x) = ([5,3,1],[4,2]).There are no more elements left, so the return value is ([5,3,1],[4,2]).As the walkthrough shows, the split function works by maintaining two lists, swapping them on each iteration, and appending each element of the input to a different list. 这篇关于遍历Haskell中的列表拆分功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-14 09:27