如何在scala中编写函数
我有以下代码:如何在scala中编写函数,scala,Scala,我有以下代码: val ls = List(0, -1, 2, -2) var removeNegative = List[Int]() def removeNegative(ls: List[Int]): Int = ls match { case Nil => 0 case l::for(ls <- ls){ var removeNegative = List[Int]() if(ls >= 0){ re
val ls = List(0, -1, 2, -2)
var removeNegative = List[Int]()
def removeNegative(ls: List[Int]): Int = ls match {
case Nil => 0
case l::for(ls <- ls){
var removeNegative = List[Int]()
if(ls >= 0){
removeNegative = removeNegative :+ ls
}
}
return removeNegative
}
println(removeNegative(ls)
val ls=List(0,-1,2,-2)
var removeNegative=List[Int]()
def removeNegative(ls:List[Int]):Int=ls匹配{
案例Nil=>0
案例l::for(ls=0){
removeNegative=removeNegative:+ls
}
}
返回再激活剂
}
println(移除式(ls)
我将函数体中的代码作为独立代码使用,它可以正常工作,但是我不得不将其添加到函数中,并出现以下错误:
ScalaFiddle.scala:7: error: illegal start of simple pattern
case l::for(ls <- ls){
^
ScalaFiddle.scala:16: error: '=>' expected but '}' found.
}
^
ScalaFiddle.scala:7:错误:简单模式的非法启动
案例l::for(ls在解构列表时不是有效的模式匹配
请参阅下面的代码片段,了解更惯用的方法
val ls = List(0, -1, 2, -2)
def removeNegative(ls: List[Int]):List[Int] = ls match {
case Nil => ls
case l::tail =>
if (l < 0) l :: removeNegative(tail) else removeNegative(tail)
}
val ls=List(0,-1,2,-2)
def removeNegative(ls:List[Int]):List[Int]=ls匹配{
案例Nil=>ls
案例l::tail=>
if(l<0)l::removeNegative(tail)else removeNegative(tail)
}
实现所需功能的最简单方法是使用过滤器
def removeNegative(xs:List[Int]):List[Int]=xs.filter(>=0)
val ls=列表(0,-1,2,-2)
removeNegative(ls)//列表(0,2)
如果您想要递归版本:
def removeNegative(xs:List[Int],ans:List[Int]=List.empty[Int]):List[Int]=xs-match{
//xs中没有剩余元素时的情况
案例Nil=>ans
//我们得到xs的第一个元素,然后
//如果它是非负的,则将其附加到ans
案例x::tail=>removeNegative(tail,if(x<0)ans-else ans:+x)
}
val ls=列表(0,-1,2,-2)
removeNegative(ls)//列表(0,2)
它是尾部递归的,这意味着它不会为每个递归调用消耗堆栈
如果您想了解更多关于尾部递归的信息
这是一个很好的开始解释。这里case l::for(ls for)(l)最好提到这种方法可以放大堆栈,并提供尾部递归版本。