Why is repeat defined in Prelude as it is? [duplicate]

*爱你&永不变心* 提交于 2019-12-30 04:06:35

问题


Repeat is defined as follows:

repeat :: a -> [a]
repeat x = xs where xs = x:xs

Is there any reason that the following isn't used?

repeat :: a -> [a]
repeat x = x : repeat x

(Obviously there are many equivalent definitions for many Prelude functions, but my latter description just feels much more obvious. I wonder if there's a performance or style reason for the way it is.)


回答1:


It is for performance and space complexity reasons.

The first version of the code uses explicit sharing; it basically looks like a one-element circular linked list in memory (the xs in the code is a list node that has x as value and its tail points to the very same list node). When you evaluate more and more elements of the list it will just take the same node repeatedly.

In contrast, the second version creates a list that actually grows in memory as it is evaluated, because different invocations of repeat x are always recomputed (and not memoized). There will be always yet another unevaluated thunk at end of the generated list.



来源:https://stackoverflow.com/questions/17031972/why-is-repeat-defined-in-prelude-as-it-is

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!