Reputation: 6003
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
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
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