为什么在Prelude中重复定义? [英] Why is repeat defined in Prelude as it is?

查看:100
本文介绍了为什么在Prelude中重复定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

重复定义如下:

  repeat :: a  - > [a] 
重复x = xs其中xs = x:xs

是否有任何原因以下是不使用的?

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



<显然有很多等价的定义对于许多Prelude函数,但我后面的描述只是感觉更明显,不知道是否有性能或风格的原因。)

解决方案这是出于性能和空间复杂性的原因。

代码的第一个版本使用显式共享;它基本上看起来像内存中的一个元素循环链表(代码中的 xs 是一个列表节点,它具有 x 作为值,其尾部指向相同的列表节点)。当你评估越来越多的列表元素时,它会重复使用同一个节点。

相比之下,第二个版本创建了一个列表,它在评估时实际在内存中增长,因为不同调用重复x 总是重新计算(而不是记忆)。在生成的列表结尾处总会有另一个未评估的thunk。

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.)

解决方案

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.

这篇关于为什么在Prelude中重复定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆