Skip to content

Instantly share code, notes, and snippets.

@tldeti
Created May 20, 2014 02:39
Show Gist options
  • Save tldeti/281548a0e66ec600f5c2 to your computer and use it in GitHub Desktop.
Save tldeti/281548a0e66ec600f5c2 to your computer and use it in GitHub Desktop.
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