Advertisement
Guest User

Untitled

a guest
Dec 9th, 2019
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.32 KB | None | 0 0
  1. val list = List(5,8,6,9)
  2.  
  3. def forall(p: Int => Boolean, as: List[Int]): Boolean = as match {
  4.   case Nil => true
  5.   case x::xs => p(x) && forall(p, xs)
  6. }
  7.  
  8. forall(x => x > 2 && x < 10, list)
  9.  
  10. // a) tail recursive
  11.  
  12. def forallTR(p: Int => Boolean, as: List[Int], acc: Boolean): Boolean = as match {
  13.   case Nil => acc && true
  14.   case x::xs => forallTR(p, xs, acc && p(x))
  15. }
  16.  
  17. forallTR(x => x > 2 && x < 10, list, true)
  18.  
  19. // b) using fold
  20.  
  21. def foldRight[A,B](as: List[A])(e: B)(f: (A,B) => B) : B = as match {
  22.     case Nil => e
  23.     case x::xs => f(x, foldRight(xs)(e)(f))
  24. }
  25.  
  26. def forall3(p: Int => Boolean, as: List[Int]) = foldRight(list)(true)(p(_) && _)
  27. forall3(x => x > 2 && x < 10, list)
  28.  
  29.  
  30. // c) generic and curried
  31.  
  32. // curried only version
  33. def forallTRCurried(p: Int => Boolean)(as: List[Int])(acc: Boolean): Boolean = as match {
  34.   case Nil => acc && true
  35.   case x::xs => forallTRCurried(p)(xs)(acc && p(x))
  36. }
  37.  
  38. forallTRCurried(x => x > 2 && x < 10)(list)(true)
  39.  
  40. // generic and curried
  41.  
  42. def forallTRCurriedGeneric[A](p: A => Boolean)(as: List[A])(acc: Boolean): Boolean = as match {
  43.   case Nil => acc && true
  44.   case x::xs => forallTRCurriedGeneric(p)(xs)(acc && p(x))
  45. }
  46.  
  47. forallTRCurriedGeneric[Int](x => (x > 2 && x < 10))(list)(true)
  48. forallTRCurriedGeneric[Boolean](x => (x == true))(List(true, true, true))(true)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement