简体   繁体   English

Haskell优化无限列表实现

[英]Haskell optimizing infinite list implementation

My code gives the wanted result but I wonder if there is a better way to code this. 我的代码给出了所需的结果,但我想知道是否有更好的方法对此进行编码。 This is the given example: 这是给定的示例:

pair [ 1 , 2 , 3 , 4 , 5 , 6 , ... ]
[ [ 1 , 2 ] , [ 3 , 4 ] , [ 5 , 6 ] , ... ]

and the given code: 和给定的代码:

pair::[a] -> [[a]]
pair =

My solution: 我的解决方案:

pair :: [a] -> [[a]]
pair (x:y:xs) = ((x:y:[]):[]) ++ pair xs

Using the cons operator : will be much more performant than concatenating lists: 使用cons运算符:将比串联列表具有更高的性能:

pair :: [a] -> [[a]]
pair (x:y:xs) = [x, y] : pair xs

The reasoning is that lists in Haskell are linked lists where each item points to the next until the end of the list. 原因是Haskell中的列表是链接列表,其中每个项目都指向下一个,直到列表末尾。 Pushes and Pops are cheap when done at the head of the list because you are only pointing the head at the head of an existing list. 当您将“推”和“弹出”按钮放在列表的开头时,这种方法很便宜,因为您只需将标题指向现有列表的开头即可。

When you concatenate two linked list, you are essentially rebuilding the complete first list so that its last element can point at the first element of the second list. 连接两个链接列表时,实际上是在重建完整的第一个列表,以便其最后一个元素可以指向第二个列表的第一个元素。

The performance gain is minor in your example since you only have two elements in your list, but as a general rule, if you're dealing with operations on the head of the list, it's almost always going to be more performant to use cons. 在您的示例中,性能提升很小,因为列表中只有两个元素,但是作为一般规则,如果要处理列表顶部的操作,使用cons几乎总是会表现得更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM