Skip to content

Instantly share code, notes, and snippets.

@kyo-ago
Last active December 27, 2015 08:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kyo-ago/7299747 to your computer and use it in GitHub Desktop.
Save kyo-ago/7299747 to your computer and use it in GitHub Desktop.
import scala.util._
def binarySearch(number: Int, numbers: List[Int]): Try[Int] = {
def Y[A,B]( f:((A => B), A ) => B, x:A ):B = f( (y:A) => Y(f,y),x)
Success(Y( (f: ((Int, Int)) => (Int, Int), n: (Int, Int)) => {
if (n._1 == n._2) return Failure(new NoSuchElementException)
((mid: Int) => {
((numbers(mid), number) match {
case (l, r) if l > r => f(n._1, mid)
case (l, r) if l < r => f(mid + 1, n._2)
case _ => (mid, -1)
})
})((n._1 + n._2) / 2)
}, (0, numbers.length))._1)
}
println(binarySearch(50, Range(10, 100, 20).toList).getOrElse(None) != None)
println(binarySearch(10, Range(10, 100, 20).toList).getOrElse(None) != None)
println(binarySearch(5, Range(10, 100, 20).toList).getOrElse(None) == None)
println(binarySearch(500, Range(10, 100, 20).toList).getOrElse(None) == None)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment