Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- val list = List(5,8,6,9)
- def forall(p: Int => Boolean, as: List[Int]): Boolean = as match {
- case Nil => true
- case x::xs => p(x) && forall(p, xs)
- }
- forall(x => x > 2 && x < 10, list)
- // a) tail recursive
- def forallTR(p: Int => Boolean, as: List[Int], acc: Boolean): Boolean = as match {
- case Nil => acc && true
- case x::xs => forallTR(p, xs, acc && p(x))
- }
- forallTR(x => x > 2 && x < 10, list, true)
- // b) using fold
- def foldRight[A,B](as: List[A])(e: B)(f: (A,B) => B) : B = as match {
- case Nil => e
- case x::xs => f(x, foldRight(xs)(e)(f))
- }
- def forall3(p: Int => Boolean, as: List[Int]) = foldRight(list)(true)(p(_) && _)
- forall3(x => x > 2 && x < 10, list)
- // c) generic and curried
- // curried only version
- def forallTRCurried(p: Int => Boolean)(as: List[Int])(acc: Boolean): Boolean = as match {
- case Nil => acc && true
- case x::xs => forallTRCurried(p)(xs)(acc && p(x))
- }
- forallTRCurried(x => x > 2 && x < 10)(list)(true)
- // generic and curried
- def forallTRCurriedGeneric[A](p: A => Boolean)(as: List[A])(acc: Boolean): Boolean = as match {
- case Nil => acc && true
- case x::xs => forallTRCurriedGeneric(p)(xs)(acc && p(x))
- }
- forallTRCurriedGeneric[Int](x => (x > 2 && x < 10))(list)(true)
- forallTRCurriedGeneric[Boolean](x => (x == true))(List(true, true, true))(true)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement