Scala forall example?

Scala

Scala Problem Overview


I tried Google search and could not find a decent forall example. What does it do? Why does it take a boolean function?

Please point me to a reference (except the Scaladoc).

Scala Solutions


Solution 1 - Scala

The forall method takes a function p that returns a Boolean. The semantics of forall says: return true if for every x in the collection, p(x) is true.

So:

List(1,2,3).forall(x => x < 3)

means: true if 1, 2, and 3 are less than 3, false otherwise. In this case, it will evaluate to false since it is not the case all elements are less than 3: 3 is not less than 3.

There is a similar method exists that returns true if there is at least one element x in the collection such that p(x) is true.

So:

List(1,2,3).exists(x => x < 3)

means: true if at least one of 1, 2, and 3 is less than 3, false otherwise. In this case, it will evaluate to true since it is the case some element is less than 3: e.g. 1 is less than 3.

Solution 2 - Scala

A quick example of how you can play with this function using a Scala script.

create a myScript.scala file with

println(args.forall(p => (p.equals("a"))))

and call it with

scala myScript.scala a a a  // true
scala myScript.scala a b c  // false

Solution 3 - Scala

Scala's forall is also a great tool to do something like applying logical and to a list of boolean values with the early exist:

val evalResults: List[Boolean] = List(evaluateFunc1(), evaluateFunc2(), evaluateFunc3(), evaluateFunc4(), evaluateFunc5())

evalResults.forall(result => result == true)

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
QuestionJus12View Question on Stackoverflow
Solution 1 - ScaladhgView Answer on Stackoverflow
Solution 2 - ScalaJames RaitsevView Answer on Stackoverflow
Solution 3 - ScalaJohnnyView Answer on Stackoverflow