Scala forall example? - 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).

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.

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

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)

Related

Forcing evaluation of terms before extraction, or other ways to test extracted functions?

In many parts of the standard library, there are a bunch of OCaml-native functions with no Coq counterpart. I implemented a Coq version of some of them (with added proofs to show that the Coq versions behave as I think they ought to), but now how do I check that this actually matches the OCaml version's behavior?
The easiest / most "obvious" way I can think of would be to take a test input x, compute f x in Coq, and extract a comparison f x = [[f x]] (where [[…]] marks evaluation in Coq), then repeat for some number of test cases. Unfortunately, I can't find a way to force evaluation in Coq.
Is there a trick to make this possible? Or is there some other standard way for testing behavior across extraction? (Manually going Compute (f x). and plugging the resulting terms as literals back into the sanity checks would be an ugly fallback… Unfortunately, those won't update automatically when the function is changed, and it would also be a lot of manual work that doesn't exactly encourage exhaustive tests…)
Minimal sample:
Definition foo (b : bool) : bool :=
match b with | true => false | false => true end.
Extract Inlined Constant foo => "not".
Extract Inlined Constant bool_eq => "(=)".
Definition foo_true := foo true.
Definition foo_false := foo false.
Definition foo_test : bool :=
andb (bool_eq (foo true) foo_true) (bool_eq (foo false) foo_false).
Recursive Extraction foo_test.
results in
(** val foo_true : bool **)
let foo_true = not true
(** val foo_false : bool **)
let foo_false = not false
(** val foo_test : bool **)
let foo_test = (&&) ((=) (not true) foo_true) ((=) (not false) foo_false)
which is unhelpful. All the ways I could think of to change the definition of foo_true/foo_false to try and have them pre-evaluated didn't work. I can't find any flag in the extraction mechanism to force evaluation… Both the reference manual's attribute index and the flags/options/tables index didn't contain anything that looks useful. Is there anything that I missed?
Starting a definition with Eval compute in evaluates it before registering the definition.
Definition foo_true := Eval compute in foo true.
Definition foo_false := Eval compute in foo false.
Definition foo_test : bool :=
andb (bool_eq (foo true) foo_true) (bool_eq (foo false) foo_false).
Recursive Extraction foo_test.

Boolean condition affected by inputs

I was testing what happens when I pass random values to an arbitrary boolean condition in Python. I ran a loop 10 times and declared each time a random choice of True or False to A and B. I then saw if the condition returned True or False and outputted the values of A and B.
for i in range(10):
A = random.choice([True, False])
B = random.choice([True, False])
if (A and (A or B)) == True:
print("Pass:")
print("A: {} B: {}".format(A, B))
else:
print("Fail:")
print("A: {} B: {}".format(A, B))
Outputs:
Pass: Fail: Pass: Pass:
A: True B: True A: False B: True A: True B: False A: True B: False
Pass: Pass: Pass:
A: True B: True A: True B: False A: True B: True
Pass: Pass: Fail:
A: True B: True A: True B: True A: False B: False
The boolean condition I chose was sort of randomly written (meaning no particular reason for that one), but I found a sort of pattern in the outputs.
The value of B in all the Passes was different (same for the Fails), but the value of A was always True in the Passes and False in the Fails. Remember that a Pass is the result of the condition being True, hence it seems the condition happens to return a boolean value which is the same as the input A.
Since I found this particular condition odd, I ran another test. This time I checked if this boolean expression always gave the same as the initial input of A. I also ran it 20 times to get more random values for the inputs.
for i in range(20):
A = random.choice([True, False])
B = random.choice([True, False])
if (A and (A or B)) == A:
print("Pass")
else:
print("Fail")
Output:
Pass
Pass
Pass
. . .
Pass
Pass
Pass
I have simplified the output, but when I ran the code, it gave all 20 passes and the same when the code was run a few times.
My question is why does this condition, I guess "simplify", to just the input A? And can boolean expressions be "simplified" (as in this situation the whole expression renders pointless if the result is always just A) in order to shorten conditions?
This is a trivial result in symbolic logic.
If A is true, then your expression evaluates as follows:
True and (True or B)
True or B
True
This field of mathematics is called Boolean algebra. Your specific example is the Absorption Law, eg form 10a or "X • (X + Y) = X" here:
https://www.mi.mun.ca/users/cchaulk/misc/boolean.htm
(In Boolean algebra, "and" is sometimes written as • and "or" is sometimes written as +. This makes analogies to integer algebra more obvious, eg X + 0 = X and X • 0 = 0.)
Your larger question of "can boolean expressions be simplified" depends on the expression! Often they can, but certain forms are fully simplified. A full discussion is beyond the scope of Stack Overflow - there are various web resources or online classes. It's not particularly difficult but it's a bigger subject than one answer can cover.

Scala forall to compare two lists?

If I wan't to see if each element in a list corresponds correctly to an element of the same index in another list, could I use forall to do this? For example something like
val p=List(2,4,6)
val q=List(1,2,3)
p.forall(x=>x==q(x)/2)
I understand that the x isn't an index of of q, and thats the problem I'm having, is there any way to make this work?
The most idiomatic way to handle this situation would be to zip the two lists:
scala> p.zip(q).forall { case (x, y) => x == y * 2 }
res0: Boolean = true
You could also use zipped, which can be slightly more efficient in some situations, as well as letting you be a bit more concise (or maybe just obfuscated):
scala> (p, q).zipped.forall(_ == _ * 2)
res1: Boolean = true
Note that both of these solutions will silently ignore extra elements if the lists don't have the same length, which may or may not be what you want.
Your best bet is probably to use zip
p.zip(q).forall{case (fst, snd) => fst == snd * 2}
Sequences from scala collection library have corresponds method which does exactly what you need:
p.corresponds(q)(_ == _ * 2)
It will return false if p and q are of different length.

scala filter of 2 sets

def intersect(s: Set, t: Set): Set = (x => s(x) && t(x))
def filter(s: Set, p: Int => Boolean): Set = intersect(s, p)
I have this code.
I don't understand how does "filter" function be a valid one.
First of all, it uses intersect, but second parameter p is a method, not a Set as intersect function prototype requres.
Secondly, how does intersect(s, p) work as filter?
thanks
These are two different ways of looking at the same thing. As I mentioned in my previous answer, representing sets as their indicator functions makes lots of things more convenient, and one of those things is filtering.
Usually when we have a collection of some type A we can filter it using a predicate function A => Boolean that tells us whether or not we want to keep each element. In this case, the type of the predicate function is the same type we're using to represent the collection, and filtering is the same thing as taking the intersection of two sets.
To address your second question: intersect needs to return a function that will return true if the item is in both set s and set t and false otherwise. We can check that using the apply method on each (or in this case its syntactic sugar). The implementation is then a simple function literal (x => s(x) && t(x)) that takes an argument x and returns true if and only if x is in both sets.

Explain some scala code - beginner

I've encountered this scala code and I'm trying to work out what its doing except the fact it returns an int. I'm unsure of these three lines :
l match {
case h :: t =>
case _ => 0
Function :
def iterate(l: List[Int]): Int =
l match {
case h :: t =>
if (h > n) 0
case _ => 0
}
First, you define a function called iterate and you specified the return type as Int. It has arity 1, parameter l of type List[Int].
The List type is prominent throughout functional programming, and it's main characteristics being that it has efficient prepend and that it is easy to decompose any List into a head and tail. The head would be the first element of the list (if non-empty) and the tail would be the rest of the List(which itself is a List) - this becomes useful for recursive functions that operate on List.
The match is called pattern matching.. it's essentially a switch statement in the C-ish languages, but much more powerful - the switch restricts you to constants (at least in C it does), but there is no such restriction with match.
Now, your first case you have h :: t - the :: is called a "cons", another term from functional programming. When you create a new List from another List via a prepend, you can use the :: operator to do it.
Example:
val oldList = List(1, 2, 3)
val newList = 0 :: oldList // newList == List(0, 1, 2, 3)
In Scala, operators that end with a : are really a method of the right hand side, so 0 :: oldList is the equivalent of oldList.::(0) - the 0 :: oldList is syntactic sugar that makes it easier to read.
We could've defined oldList like
val oldList = 1 :: 2 :: 3 :: Nil
where Nil represents an empty List. Breaking this down into steps:
3 :: Nil is evaluated first, creating the equivalent of a List(3) which has head 3 and empty tail.
2 is prepended to the above list, creative a new list with head 2 and tail List(3).
1 is prepended, creating a new list with head 1 and tail List(2, 3).
The resulting List of List(1, 2, 3) is assigned to the val oldList.
Now when you use :: to pattern match you essentially decompose a List into a head and tail, like the reverse of how we created the List above. Here when you do
l match {
case h :: t => ...
}
you are saying decompose l into a head and tail if possible. If you decompose successfully, you can then use these h and t variables to do whatever you want.. typically you would do something like act on h and call the recursive function on t.
One thing to note here is that your code will not compile.. you do an if (h > n) 0 but there is no explicit else so what happens is your code looks like this to the compiler:
if (h > n) 0
else { }
which has type AnyVal (the common supertype of 0 and "nothing"), a violation of your Int guarentee - you're going to have to add an else branch with some failure value or something.
The second case _ => is like a default in the switch, it catches anything that failed the head/tail decomposition in your first case.
Your code essentially does this:
Take the l List parameter and see if it can be decomposed into a head and tail.
If it can be, compare the head against (what I assume to be) a variable in the outer scope called n. If it is greater than n, the function returns 0. (You need to add what happens if it's not greater)
If it cannot be decomposed, the function returns 0.
This is called pattern matching. It's like a switch statement, but more powerful.
Some useful resources:
http://www.scala-lang.org/node/120
http://www.codecommit.com/blog/scala/scala-for-java-refugees-part-4