菜鸟函数式程序员关于列表访问的问题

发布于 2024-11-07 20:22:16 字数 96 浏览 0 评论 0原文

这可能是一个愚蠢而明显的问题,但为什么列表访问算法示例是在线性时间内实现的?我知道大多数应用程序都涉及遍历列表而不是随机访问它们,但是如果您想通过随机访问对列表进行访问该怎么办?

This might be a silly and obvious question, but why are list access algorithm examples implemented in linear time? I understand that most applications involve traversing lists rather than accessing them randomly, but what if you want to perform an access on a list with random accesses?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

捂风挽笑 2024-11-14 20:22:16

因为列表被设计为线性结构。它们是规范的递归数据类型,定义为:

 data [a] = [] | a : [a]

也就是说,要么是空列表,要么是 cons 节点,由一个元素和一个尾部(也是一个列表)组成。

这种结构精确地对应于数学中的归纳定义,相应地,使得将许多函数编写为简单的递归调用变得微不足道。

然而,递归数据类型不允许非线性时间内的随机访问。为此,您需要硬件支持(我们都有)和更复杂的数据类型(或不太复杂,取决于您的观点)。

总结:列表是计算机科学对归纳法的编码,是一种递归数据结构。这是基础,你需要它,但它不进行随机访问。

Because lists are by design a linear structure. They are the canonical recursive data type, defined as:

 data [a] = [] | a : [a]

That is, either the empty list, or a cons node, consisting of an element, and a tail, which is also a list.

This structure precisely corresponds to inductive definitions in mathematics, and correspondingly, makes it trivial to write many functions as simple recursive calls.

The recursive data type does not admit random access in non-linear time, however. For that you need hardware support (which we all have), and a more sophisticated data type (or less sophisticated, depending on your viewpoint).

Summary: lists are computer science's encoding of induction as a recursive data structure. It's fundamental, you need it, but it doesn't do random access.

生生漫 2024-11-14 20:22:16

Haskell 列表对应于命令式语言中的链表;它们本质上是顺序的,因为您只能访问头部并且需要遍历以查找其他元素。

如果您想要随机访问,您应该选择其他数据类型。也许来自 Data.Array 或 Data.IntMap。

Haskell lists correspond to linked lists in imperative languages; they are inherently sequential since you only have access to the head and need to traverse to find other elements.

If you want random access you should choose some other data type. Perhaps from Data.Array or Data.IntMap.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文