Created
May 20, 2014 02:39
-
-
Save tldeti/281548a0e66ec600f5c2 to your computer and use it in GitHub Desktop.
This file contains 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 lazyFoldRight[A,B](as: List[A], z: B)(f: (A, =>B) => B): B = | |
as match { | |
case Nil => z | |
case x :: xs => f(x, lazyFoldRight(xs, z)(f)) | |
} | |
def findWithPriority[T](xs: List[T], high: T => Boolean, low: T => Boolean): Option[T] = { | |
val t = lazyFoldRight(xs,(None,None):(Option[T],Option[T]))((x,result)=> | |
if(high(x)) (Some(x),None) | |
else if(low(x)){ | |
if(result._1.isDefined) result else (None,Some(x)) | |
}else | |
result | |
) | |
t._1.orElse(t._2) | |
} | |
assert(findWithPriority(List(1, 3, 4, 2), (x: Int) => x > 3, (x: Int) => x > 2) == Some(4)) | |
assert(findWithPriority(List(1, 4, 3, 2), (x: Int) => x > 2, (x: Int) => x > 3) == Some(4)) | |
assert(findWithPriority(List(1, 3, 4, 2), (x: Int) => x > 3, (x: Int) => x > 4) == Some(4)) | |
assert(findWithPriority(List(1, 3, 4, 2), (x: Int) => x > 4, (x: Int) => x > 3) == Some(4)) | |
assert(findWithPriority(List(1, 3, 4, 2), (x: Int) => x > 4, (x: Int) => x > 4) == None) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment