Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala forall example?

Tags:

scala

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).

like image 592
Jus12 Avatar asked Sep 22 '12 19:09

Jus12


People also ask

How do you use forall in Scala?

Scala List forall() method with example. The forall() method is utilized to check if the given predicate satisfies all the elements of the list or not. Return Type: It returns true if the stated predicate holds true for all the elements of the list else it returns false.

How do you check if an element is in a list Scala?

contains() function in Scala is used to check if a list contains the specific element sent as a parameter. list. contains() returns true if the list contains that element.


1 Answers

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.

like image 70
dhg Avatar answered Sep 28 '22 07:09

dhg