Last active
August 29, 2015 14:11
-
-
Save r-wheeler/5b5247f2a0de69357e49 to your computer and use it in GitHub Desktop.
Scala Exists, forAll, takeWhile and simple fun with functions
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
type predicate[A] = A => Boolean | |
def exists[A](ls: List[A], p: A => Boolean): Boolean = { | |
ls match { | |
case x :: xs => p(x) || exists(xs,p) | |
case _ => false | |
} | |
} | |
def exists2[A](ls: List[A], p: predicate[A]): Boolean = { | |
ls.foldRight(false)((a,z) => p(a) || z) | |
} | |
exists2(List(1,2,3,4),(x: Int) => x > 3) | |
def forAll[A](ls: List[A])( p: predicate[A]): Boolean = { | |
ls.foldRight(true)((a, z) => p(a) && z) | |
} | |
forAll(List(1,2,3,4))(_>0) | |
def takeWhile[A](ls: List[A])(p: predicate[A]): List[A] = { | |
ls.foldRight(List[A]())((a, z) => | |
if (p(a)) a :: z | |
else z) | |
} | |
takeWhile(List(1,2,3,4,5))(_<4) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment