1

I'm starting to learn Scala and while reading Scala for the Impatient, got to the following solution to one of the exercises:

//No function
def positivesThenZerosAndNegatives(values: Array[Int]) = {
    Array.concat(for (value <- values if value > 0) yield value,
        for (value <- values if value == 0) yield value,
        for (value <- values if value < 0) yield value)
}

But now I was trying to pass as param the function that applies the filter on each comprehensive for:

//Trying to use a function (filter)
def positivesThenZerosAndNegatives2(values: Array[Int]) = {
    Array.concat(filter(values, _ > 0), filter(values, _ == 0), filter(values, _ < 0))
}

def filter[T: Int](values: Array[T], f: (T) => Boolean) = {
    for (value <- values if f(value)) yield value
}

I haven't found the right way to refer to an element array.

1 Answer 1

3

You can either writer your filter method as following:

import scala.reflect.ClassTag

def filter[T: ClassTag](values: Array[T], f: T => Boolean): Array[T] = {
  for(value <- values; if f(value)) yield value
}

or as this:

def filter(values: Array[Int], f: Int => Boolean): Array[Int] = {
  for(value <- values; if f(value)) yield value
}

Anyway, you can simply re-write your method positivesThenZerosAndNegatives like this:

scala> def positivesThenZerosAndNegatives(values: Array[Int]) = {
     |   values.filter(0 <) ++ values.filter(0 ==) ++ values.filter(0 >)
     | }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.