0

I'm trying to use an array of booleans to choose particular elements in another array. For example:

val arr = Seq("A", "B", "C")
val mask = Seq(true,false,true)

and I'd like the output to be a new array:

val arr_new = Seq("A","C")

Is there a way to achieve this in Scala?

Feynman27
  • 3,049
  • 6
  • 30
  • 39

1 Answers1

9
scala> arr.zip(mask).collect { case (v, true) => v }
res0: Seq[String] = List(A, C)
Tzach Zohar
  • 37,442
  • 3
  • 79
  • 85
  • cool! just learnt that partial function is a combination of map and filter i.e. all values that are not valid arguments to the partial function are ignored. – Samar Sep 15 '16 at 16:29
  • 2
    @Samar It isn't a partial function which is the combination of `map` and `filter`. It's `collect`, and it's specifically defined to ignore elements on which its argument is not defined. Other methods which accept partial functions can do other things in this case. – Alexey Romanov Sep 15 '16 at 17:01
  • @AlexeyRomanov: from the docs for collect: `def collect[B](pf: PartialFunction[A, B]): Array[B]` collect accepts a partial function, thats what I meant. – Samar Sep 15 '16 at 17:04
  • Oh ok, I see what you mean. Collect is specially designed to ignore unapplicable arguments to the supplied partial function. – Samar Sep 15 '16 at 17:06