Skip to content

Instantly share code, notes, and snippets.

@robinraju
Created February 20, 2020 16:05
Show Gist options
  • Save robinraju/855e039e52b5e8e6dd5028dd4fe7f6e0 to your computer and use it in GitHub Desktop.
Save robinraju/855e039e52b5e8e6dd5028dd4fe7f6e0 to your computer and use it in GitHub Desktop.
SCALA: Find the previous and next elements of an item in a list
def getPrevAndNext[A](lst: List[A], el: A): Option[(Option[A], A, Option[A])] = {
lst match {
case Nil => None
case x :: Nil if x == el => Some(None, x, None)
case _ :: Nil => None
case x :: y :: Nil if x == el => Some(None, x, Some(y))
case x :: y :: Nil if y == el => Some(Some(x), y, None)
case x :: y :: z :: zs if x == el => Some(None, x, Some(y))
case x :: y :: z :: zs if y == el => Some(Some(x), y, Some(z))
case _ => getPrevAndNext(lst.tail, el)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment