Daniel Wu
Daniel Wu

Reputation: 6003

How to get a set of elements in a list based on element index in Scala?

I have one list and another list contains the index I am interested in. e.g

val a=List("a","b","c","d")
val b=List(2,3)

Then I need to return a list whose value is List("b","c"), since List(2,3) said I like to take the 2nd and 3rd element from element "a". How to do that?

Upvotes: 3

Views: 666

Answers (3)

samthebest
samthebest

Reputation: 31515

I like the order of my expressions in the code to reflect the order of evaluation, so I like using the scalaz pipe operator to do this kind of thing |>

b.map(_ - 1 |> a)

It's especially natural when one is used to writing bash scripts.

Upvotes: 2

elm
elm

Reputation: 20405

Consider this apply method which checks (avoids) possible IndexOutOfBoundsException,

implicit class FetchList[A](val in: List[A]) extends AnyVal { 
  def apply (idx: List[Int]) = for (i <- idx if i < in.size) yield in(i-1) 
}

Thus

a(b)
res: List[String] = List(b, c)

Upvotes: 1

Lee
Lee

Reputation: 144126

val results = b.map(i => a(i - 1))

Upvotes: 4

Related Questions