1

Consider the following Scala Array x definition

scala> val x = Array(10, 32, 45, 54, 44, 37)
x: Array[Int] = Array(10, 32, 45, 54, 44, 37)

and an index selector, which is provided, and is guaranteed not to include out of bounds index values:

scala> val selector = Seq(0, 3, 5)
selector: Seq[Int] = List(0, 3, 5)

In Scala, what is a concise way to use selector in combination with x to select only those indices of x which match the desired indices in selector to produce a new result Array? Specifically, result is expected as:

result: Array(10, 54, 37)

Any help is appreciated. Thank you.

2 Answers 2

5

Event shorter :)

 import scala.collection.breakOut
 val result: Array[Int]= selector.map(x)(breakOut)

.map takes a parameter of type Function1[Int,_], and when we pass x there, the compiler is smart enough to figure out, that what me mean is x.apply, which is a method Int => Int, and it uses eta-expansion to convert it into a function, so that we don't have to spell it out explicitly, creating an anonymous function like .map { idx => x(idx) }.

breakOut is a collection factory, that tells .map to return the result as Array rather than List (because the expected return type on the LHS is Array). This avoids building an intermediate collection and then copying it into an array in (.map(x).toArray)

Sign up to request clarification or add additional context in comments.

1 Comment

I had no idea about breakOut. Short, simple, and I learned something new today. Thank you for the insight.
1

Access x with each selector using map.

scala> selectors.map(s => x(s)).toArray
res1: Array[Int] = Array(10, 54, 37)

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.