Skip to content

Instantly share code, notes, and snippets.

@akihiro4chawon
Created April 23, 2011 13:37
Show Gist options
  • Save akihiro4chawon/938616 to your computer and use it in GitHub Desktop.
Save akihiro4chawon/938616 to your computer and use it in GitHub Desktop.
def find2[A](x:A, xs:List[A]):Option[A] = {
if(xs.nonEmpty){
if(xs.head == x) Some(xs.head)
else find2(x, xs.tail)
} else {
None
}
}
def find3[A](x:A, xs:List[A]):Option[A] =
xs.headOption match {
case Some(y) if y == x => Some(y)
case Some(y) => find3(x, xs.tail)
case None => None
}
def find4[A](x:A, xs:List[A]):Option[A] =
xs.headOption flatMap { y => if(y == x) Some(y) else find4(x, xs.tail) }
// filter...
def find5[A](x: A, xs: List[A]): Option[A] = xs.view.filter{x.==}.headOption
// in scala 2.9 or later, collectFirst is available. :)
def find6[A](x: A, xs: List[A]): Option[A] = xs collectFirst {case `x` => x}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment