Exercise: Define forall and exists in terms of filter.
As before, since class List cannot be extended in scala, the methods are implemented as pure functions taking a list parameter.
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
object ListFilter { | |
def forall(xs: List[Int], p: Int => Boolean): Boolean = | |
xs.isEmpty || xs.filter(p) == xs | |
def exists(xs: List[Int], p: Int => Boolean): Boolean = | |
!xs.isEmpty && !xs.filter(p).isEmpty | |
def main(args: Array[String]) { | |
println("Are members of list (1,2,3,4,5) less than 10? : " + | |
forall(List(1,2,3,4,5), (x => x < 10))); | |
println("Is there at least one member of list (1,2,3,4,5) thats greater than 5? : " + | |
exists(List(1,2,3,4,5), (x => x > 5))); | |
} | |
} |
No comments:
Post a Comment