Let's say I have a Scala list List("apple", "orange", "banana", "chinese gooseberry")
*. I want to search this list and return either the previous item in the list in relation to an item I already have.
For example: getPrevious(fruit: String, fruits: List[String]): Option[String]
should return
Some("apple")
if I call it with afruit
arg of"orange"
;Some("banana")
for"chinese gooseberry"
;None
if I call it with"apple"
(no previous element exists) or"potato"
(not present in the list).
Easily done imperatively, but how can I do this in an elegant functional manner? The best I can come up with 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 isn't elegant or efficient. I particularly hate converting the filter
iterator toList
. How can I improve it?
(*as an aside, is List
the best collection to use for a sliding
iteration?)