Say I have a Scala List("apple", "orange", "banana", "chinese gooseberry") *. I want to search this list and return either the previous item in the list with respect to the item that I already have.
For example: getPrevious(fruit: String, fruits: List[String]): Option[String] should return
Some("apple") if I call it with fruit arg "orange" ;Some("banana") for "chinese gooseberry" ;None if I call it using "apple" (the previous item does not exist) or "potato" (not on the list).
Easily made for real, but how can I do it in an elegant, functional way? The best I can think of is the following:
def previous(fruit: String, fruits: List[String]): Option[String] = fruits.sliding(2) .filter { case List(previous, current) => current == fruit } .toList .headOption .map { case List(previous, current) => previous }
It works, but it is not elegant and not efficient. I especially hate filter toList iterator toList . How can I improve it?
(* as an aside, is List best collection used to iterate sliding ?)
source share