为什么使用 scala.collection.immutable.Stack [英] Why use scala.collection.immutable.Stack

查看:34
本文介绍了为什么使用 scala.collection.immutable.Stack的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些东西来存储 LIFO.除了push和pop,不需要遍历等功能.

我在 Scala 集合中找到了一个特殊的类来创建堆栈.但它在模式匹配和其他方便的 scala 习语中缺少 Nil 对象.不可变列表乍一看很适合,它们在构造和提取方面有缺点,而这正是 LIFO 所需要的.

scala.collection.immutable.Stack 存在背后有什么原因吗?为什么我更喜欢使用它,哪些用例可以展示它的好处?

解决方案

来自 API 文档:

<块引用>

注意:该类仅出于历史原因而存在并作为模拟可变堆栈.您可以只使用一个列表.

更多细节:><块引用>

不可变栈在 Scala 程序中很少使用,因为它们功能包含在列表中:不可变堆栈上的 push 是与列表上的 :: 和堆栈上的 pop 相同 与上的 tail 相同一个列表.

所以回答你的问题:

  1. 是的,它的存在是有原因的.
  2. 不,您不应该更喜欢它而不是列表.

I need something to store a LIFO. No need for traversing and other functions except for push and pop.

I've found special class in scala collection for creating a stack. But it lacks Nil object in pattern matching and other handy scala idioms. Immutable lists suit well at first glance, they have cons for construction and for extraction and that is all needed from LIFO.

Is there any reason behind scala.collection.immutable.Stack existence? Why I should prefer to use it, what are use cases to show its benefits?

解决方案

From the API documentation:

Note: This class exists only for historical reason and as an analogue of mutable stacks. Instead of an immutable stack you can just use a list.

And in a little more detail:

Immutable stacks are used rarely in Scala programs because their functionality is subsumed by lists: A push on an immutable stack is the same as a :: on a list and a pop on a stack is the same as a tail on a list.

So to answer your questions:

  1. Yes, there's a reason for its existence.
  2. No, you shouldn't prefer it over lists.

这篇关于为什么使用 scala.collection.immutable.Stack的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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