Created
April 23, 2011 13:37
-
-
Save akihiro4chawon/938616 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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