哈斯克尔:从后访问列表 [英] Haskell: accessing lists from back

查看:58
本文介绍了哈斯克尔:从后访问列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我开始学习Haskell。我是那种用函数式语言的新的,而且我很享受哈斯克尔了不少。

Today I started learning Haskell. I'm kind of new with functional languages, and I'm enjoying Haskell a lot.

不过我有一个关于它的设计是窃听我的问题:从我了解到目前为止,它看起来像访问到一个列表后面的元素是一个复杂得多的访问元素前面(的东西像 XS:X ,其中 XS :: [A] X ::一似乎并不可能)。

However I've got a question about its design which is bugging me: from what I understood so far it looks like accessing an element to the back of a list is a lot more complicated that accessing the element to the front (something like xs:x where xs::[a] and x::a doesn't seem to be possible).

(从我的理解),这是可能的一个列表追加到另一个( XS ++ [A] ),但它会花费更多的在运行时(它需要遍历整个列表),并且它不能被用于模式匹配。

(From what I understood) it's possible to append a list to another one (xs++[a]), but it'll cost more at run time (it requires to traverse the whole list) and it cannot be used for pattern matching.

为什么哈斯克尔缺少这样的操作?

Why is Haskell missing such operation?

推荐答案

该列表的数据类型

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

定义如上。这里只有两种模式可以匹配: [] X:XS ,其中 X 是头部和 XS 是尾巴。

is defined like above. There's only two patterns you can match: [] and x : xs, where x is the head and xs is the tail.

prepending到列表

Prepending to a list

a = 1 : 2 : []
b = 0 : a


 (:) <-- b
 / \  
0  (:)  <-- a
   / \
  1  (:)
     / \
    2   []

只是增加了一个新的利弊细胞并重新使用原来的列表作为尾部。

simply adds a new cons cell and reuses the original list as the tail.

但是,请记住,Haskell的数据结构是不变的。追加到列表的尾部

However, keep in mind that Haskell data structures are immutable. Appending to the tail of a list

a = 1 : 2 : []
b = a ++ [3]


 (:) <-- a      (:) <-- b
 / \            / \
1  (:)         1  (:)
   / \            / \
  2   []         2  (:)
                    / \
                   3   []

需要建立一个完全新的列表,因为没有原来的结构的一部分可重复使用。

requires building an entirely new list, because no part of the original structure can be reused.

事实上,考虑

a = 0 : a
b = 0 : [ x+1 | x <- b ]


 (:) <-- a         (:) <-- b
 / \               / \
0  (:) <-- a      0  (:) <-- [ x+1 | x <- b ]
   / \               / \
  0  (:) <-- a      1  (:) <-- [ x+1 | x <- [ x+1 | x <- b ] ]
     ...               ...

会怎么获取列表的最后一个元素,或追加到最后?

How would you ever get the last element of the list, or append to the end?

有其他数据结构如出队■哪些是更适合于既前端和后台的访问。

There are other data structures such as dequeues which are more suited for both front- and back-based access.

这篇关于哈斯克尔:从后访问列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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