I have the following code:
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)
and I used the code in the function body as a standalone and it works, however I have had to add it into a function and I get the following errors:
ScalaFiddle.scala:7: error: illegal start of simple pattern
case l::for(ls <- ls){
^
ScalaFiddle.scala:16: error: '=>' expected but '}' found.
}
^
What have I done wrong here?
Not a valid pattern match when deconstructing the list.
See the code snippet below for a more idiomatic way of doing this.
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)
}
The simplest way to realize the function you want is to use filter
def removeNegative(xs: List[Int]): List[Int] = xs.filter(_ >= 0)
val ls = List(0, -1, 2, -2)
removeNegative(ls) // List(0, 2)
If you want recursive version:
def removeNegative(xs: List[Int], ans: List[Int] = List.empty[Int]): List[Int] = xs match {
// case when there is no elements left in xs
case Nil => ans
// we get first element of xs and
// if it is non-negative, append it to ans
case x::tail => removeNegative(tail, if (x < 0) ans else ans:+x)
}
val ls = List(0, -1, 2, -2)
removeNegative(ls) // List(0, 2)
It is tail recursive, which means it doesn't consume stack for each recursive call.
If you want to know more about tail recursion
here is a good start explanation.