遍历Haskell中的列表拆分功能 [英] Walk through a list split function in Haskell
问题描述
这是我之前的问题的后续操作./p>
我试图从此处了解Haskell中的列表拆分示例:
文件夹(\ a〜(x,y)->(a:y,x))([],[])
我可以阅读Haskell并知道 folder
是什么,但不理解此代码.您能否指导我看一下这段代码,并对其进行更详细的说明?
让我们尝试在示例输入列表上运行此功能,例如 [1,2,3,4,5]
:>
- 我们从
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]
. Herea
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中的列表拆分功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!