scala - 如何在 Scala 中将列表用作堆栈
问题描述
我正在尝试在 Scala 中使用 Stack ,我已经在 Class 中完成了 Stack val s = Stack [Int]并且它运行良好,但是我被要求使用一个用作 Stack 的 List ,怎么能那是做什么的?
import scala.collection.mutable.Stack
object string_Search
{
def main(args:Array[String])
{
trait push extends Stack {
def push(i:Int) {
s.push(i)
println(s)
}
}
trait pop extends Stack {
def pop() {
s.pop()
println(s)
}
}
trait view1 extends Stack {
def view() {
println(s)
}
}
class Stack {
protected val s = List[Int]()
}
val b = new Stack with push with pop with view1
println("Filling the Stack")
b.push(15)
b.push(20)
b.push(25)
b.push(30)
println("\nDeleting from the Stack")
b.pop()
b.pop()
b.pop()
println("\nOutput")
b.view()
}
}
解决方案
scala.List
是不可变的集合,这意味着你不能像普通的那样推送或弹出mutable.Stack
。每次更改时都会创建新列表。
//it is immutable, then we need to use var instead of val
var stack = List.empty[Int]
//we can always assign fresh value to it. It is immutable... this is the only thing we can do here.
stack = List(1,2,3)
//peek() will look like this
def peek() = stack.head
//push(5) will assign new list that has prepended our value:
def push(x:Int) = stack = 5 :: stack
//pop() will be slightly complicated:
def pop() = {
val popped = stack.head
stack = stack.tail
popped
}
PS:编写这样的对全局变量进行操作的函数可能不是一个好主意。这只是为了展示......在实际代码中,您将直接使用List
或Seq
直接使用 Api。
推荐阅读
- ruby - 将变量的名称作为输入并输出其值 - Ruby
- svg - 如何在处理过程中为 svg 着色并保持亮度?
- linux - Grep 并用特殊字符替换文本
- vim - 将位于寄存器内存中的字符串粘贴到“vimL 正常执行”中
- javascript - 在 sessionStorage.setitem 中存储值时仅获取最后输入的值
- pandas - 列包含第 4 列
- r - R if else for write.table 如果字符变量有值
- c# - Type.GetTypeFromCLSID() 不返回 COM Wrapper
- hadoop - 如何编辑 Hadoop 存储日志文件的位置?
- ionic-framework - 如何在组件中注入服务