[英]Scala: how to append to a Seq
I am struggling with the following piece of code:我正在努力处理以下代码:
type DB = Map[Int, Seq[String]]
var grades: DB = Map.empty
def add(name: String, grade: Int) = {
var names: Seq[String] = Seq(name)
if(grades isDefinedAt grade) {
names = names ++ grades(grade)
}
grades += (grade -> names)
}
When I call the "add" method, as follow:当我调用“add”方法时,如下:
add(2, "Mike")
add(2, "Michelle")
add(2, "John")
I would expect grades
to be (2, Seq(Mike, Michelle, John))
but, instead, it contains only the last addition (2, John)
.我希望grades
是(2, Seq(Mike, Michelle, John))
但相反,它只包含最后一个加法(2, John)
。
How can I solve that?我该如何解决?
Thanks!!!谢谢!!!
If you want to do the same in more Scala way (no side effects, pure functional), take a look to this:如果你想以更多的 Scala 方式做同样的事情(没有副作用,纯函数式),看看这个:
type DB = Map[Int, Seq[String]]
def add(db: DB, name: String, grade: Int): DB = {
db.get(grade) match {
case Some(seq) => // key exists, let's update the value
val newSeq = seq :+ name // create new sequence
db.updated(grade, newSeq)
case None => // key does not exist, let's add new key
db + (grade -> Seq(name))
}
}
val db: DB = Map.empty
val db1 = add(db, name = "A", grade = 1)
println(s"db1: $db1")
val db2 = add(db1, name = "B", grade = 1)
println(s"db2: $db2")
val db3 = add(db2, name = "C", grade = 2)
println(s"db3: $db3")
Works fine for me.对我来说很好用。 Only thing I'd mention is that add
expects Int, String
, where you're calling it as add(2, "Mike")
(ie Int, String
) - this won't compile.我唯一要提到的是add
需要Int, String
,您将其称为add(2, "Mike")
(即Int, String
) - 这不会编译。 Here's the output of my Scala console (after flipping the order of the input variables when calling your add
method):这是我的 Scala 控制台的输出(在调用add
方法时翻转输入变量的顺序之后):
scala> type DB = Map[Int, Seq[String]]
defined type alias DB
scala> var grades: DB = Map.empty
grades: DB = Map()
scala> def add(name: String, grade: Int) = {
| var names: Seq[String] = Seq(name)
| if(grades isDefinedAt grade) {
| names = names ++ grades(grade)
| }
| grades += (grade -> names)
| }
add: (grade: Int, name: String)Unit
scala>
scala> add("Mike", 2)
scala> add("Michelle", 2)
scala> add("John", 2)
scala> grades
res3: DB = Map(2 -> List(John, Michelle, Mike))
I'm not sure why it didn't work for you.我不确定为什么它对你不起作用。 If you had got the first two inputs the wrong way around like I initially thought, ie add(2, "Mike")
etc, you would expect the output to be (2, List(John))
and not just (2, John)
.如果您像我最初想的那样以错误的方式获得前两个输入,即add(2, "Mike")
等,您会期望输出为(2, List(John))
而不仅仅是(2, John)
。 I think you broke the laws of Scala there.我认为你在那里违反了 Scala 的法律。
Just as a "best practice" thing, it would be better to avoid var
where possible.正如“最佳实践”一样,最好尽可能避免使用var
。 This could be rewritten without mutable variables.这可以在没有可变变量的情况下重写。 There's a good article by alvinalexander which explains the preference for immutable variables. alvinalexander有一篇很好的文章,解释了对不可变变量的偏好。 Worth a read.值得一读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.