Wednesday, October 05, 2011

Scala By Example Chapter 9 Solutions - Unnamed Exercise after 9.4.1

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.

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: