Scala: “any” and “all” functions

ScalaFunctional Programming

Scala Problem Overview


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?

  1. predefined somewhere in the Scala libs
  2. circumstantial, and faster written as some one-liner
  3. wrong (I didn’t test it, sorry ;))

*actually SML, but that’s 99% the same, but known by nobody under the sun.

Scala Solutions


Solution 1 - Scala

  1. It's predefined and is called exists. And forall 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
    
  2. You can make it more performant using a for loop with a break (from scala.util.control.Breaks). (See the standard library implementation of exists and forall.)

  3. It's correct.

Solution 2 - Scala

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

Solution 3 - Scala

  1. No it isn't predifined with those names. You can use exists from Traversable package.

  2. The biggest disadvantage of your implementation is that will necessary consume all of your traversible, when, for any, if any is true, if could already give you your answer. The same goes for all. But one could easily implement this so that it doesn't evaluate the whole sequence. Another solution would be to implement a monad for this type of operation. Then you would call:

    a and b and c which is equivalent to a.and(b).and(c)

  3. It is correct.

BTW, another function that I find missing is a sum function.

Solution 4 - Scala

How about exists:

scala> List(1,2,3).exists(_ > 2)
res12: Boolean = true

It's on Traversable.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionflying sheepView Question on Stackoverflow
Solution 1 - ScalamissingfaktorView Answer on Stackoverflow
Solution 2 - ScalaDavid WinslowView Answer on Stackoverflow
Solution 3 - ScalarafalotufoView Answer on Stackoverflow
Solution 4 - ScalaAdam RabungView Answer on Stackoverflow