0

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?

Mario Galic
  • 47,285
  • 6
  • 56
  • 98
Frankie Boyle
  • 29
  • 1
  • 4
  • 2
    Here `case l::for(ls <- ls) {` you are doing **pattern matching**. Basically you are deconstructing the list in its parts. Given that. the for does not make any sense at all, how that is a part of the list? Also the `h :: t` _(cons)_ says you have a non-empty list with its head as `h` and tail as `t`. Maybe you wanted this: `case l :: ls => for (l <- ls) { ... }`. However your code is far from being idiomatic in **Scala**, you may try reading a little bit more about recursion, pattern matching and the type system. – Luis Miguel Mejía Suárez May 22 '19 at 13:51

2 Answers2

1

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)  
}
hipjim
  • 118
  • 1
  • 6
0

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.

oybek
  • 630
  • 4
  • 14