我最近在用Scala编程,有时我很难解决一些错误。
我想要一个 Vector[Map[String, Any],我试图在某个函数中声明它,但出现错误"块不能包含声明"。我已经用谷歌搜索过这个问题,但我不明白此错误的原因。
def reproduce(selected: Vector[Map[String, Any]]): Vector[Map[String, Any]] ={
var children : Vector[Map[String, Any]]] = Vector()
var p1 : Map[String, Any] = Map()
var p2 : Map[String, Any] = Map()
var child : Map[String, Any] = Map("genome" -> null)
for (i <- 0 to pop_size-1){
p1 = selected(i)
if (i%2 == 0){
p2 = selected(i+1)
}else{
p2 = selected(i-1)
}
if(i == selected.size - 1) p2 = selected(0)
child("genome") = crossover( p1("genome").asInstanceOf[Vector[Int]], p2("genome").asInstanceOf[Vector[Int]])
child("genome") = point_mutation( child("genome").asInstanceOf[Vector[Int]])
children = children :+ child
}
children
}
正如我之前所说,我在第 2 行收到错误(块不能包含声明((var 子项:Vector[Map[String, Any]]] = Vector(((
那行有太多的右括号。它应该是:
var children: Vector[Map[String, Any]] = Vector()
或者,更好:
var children = Vector[Map[String, Any]]()
这里有一些关于你的代码的提示,使它更像Scala,以及一个编译没有错误的版本。
避免使用var
并在必要时创建新值
尽可能val
首次使用时放置
如果要构建集合,请使用for
/yield
而不是追加到var
集合
def reproduce(selected: Vector[Map[String, Any]]): Vector[Map[String, Any]] = {
val children =
for (i <- 0 until pop_size) yield {
val p1 = selected(i)
val p2 =
if (i == selected.size - 1) {
selected(0)
} else if (i % 2 == 0) {
selected(i + 1)
} else {
selected(i - 1)
}
val cross = crossover(p1("genome").asInstanceOf[Vector[Int]], p2("genome").asInstanceOf[Vector[Int]])
Map[String, Any]("genome" -> point_mutation(cross))
}
children.toVector
}