Scala: “any” and “all” functions
my Haskell* is a bit rusty, so i can imagine that I’m missing the obvious:
def any[A](s: Traversable[A], f: A => Boolean): Boolean = {
s.foldLeft(false)((bool, elem) => bool || f(elem))
}
Does one of these properties apply to the it?
- predefined somewhere in the Scala libs
- circumstantial, and faster written as some one-liner
- wrong (I didn’t test it, sorry ;))
*actually SML, but that’s 99% the same, but known by nobody under the sun.
Solution 1:
-
It's predefined and is called
exists
. Andforall
would be the "all" function you are looking for.scala> Vector(3, 4, 5).exists(_ % 2 == 0) res1: Boolean = true scala> Vector(3, 4, 5).forall(_ % 2 == 0) res2: Boolean = false
You can make it more performant using a
for
loop with abreak
(fromscala.util.control.Breaks
). (See the standard library implementation ofexists
andforall
.)It's correct.
Solution 2:
Methods exist on the Traversable trait which are equivalent to any
and all
:
def all[A](xs: Traversable[A], p: A => Boolean): Boolean = xs forall p
def any[A](xs: Traversable[A], p: A => Boolean): Boolean = xs exists p