Use of the forall construct in Stainless - scala

I'm trying to proof in Stainless that if two lists have the same contents and one list is bounded by x then the other list is also bounded by x. For doing so, I'm told to use the construct:
forall(x => list.content.contains(x) ==> p(x))
The lemma would be written (in a verbose way) as:
def lowerBoundLemma(l1: List[BigInt],l2: List[BigInt],x:BigInt) : Boolean = {
require(l1.content == l2.content && forall(y => l1.content.contains(y) ==> y <= x))
forall(z => l2.content.contains(z) ==> z <= x) because{
forall(z => l2.content.contains(z) ==> z <= x) ==| l1.content == l2.content |
forall(z => l1.content.contains(z) ==> z <= x) ==| trivial |
forall(y => l1.content.contains(z) ==> y <= x)
}
}.holds
The problem is that I get the following errors:
exercise.scala:12:48: error: missing parameter type
require(l1.content == l2.content && forall(y => l1.content.contains(y) ==> y <= x))
Once I add the type to y I get this error (pointing to the left brace of the contains parentheses):
exercise.scala:12:81: error: ')' expected but '(' found.
require(l1.content == l2.content && forall(y : BigInt => l1.content.contains(y) ==> y <= x))
Any idea why this is happening?
I also tried the syntax l.forall(_ <= x) but I get errors when combining with constructs like because and ==| of the type: because is not a member of Boolean.

The issues you are facing are coming from the Scala compiler frontend to Stainless. In Scala, the syntax for a closure (with specified parameter type) is (x: Type) => body (note the extra parentheses!)
If you want to use because and ==|, you'll have to add import stainless.proof._ at the beginning of your source file.

Related

multiplication of two binary numbers

I need to do the function that multiplicates two binary numbers represented by a list of booleans.
Here what I wrote :
Fixpoint brmul_r (x y res: list bool): list bool :=
match x,y,res with
|x,y,res-> if value x >0 then res else if (value x) mod 2 = 0 then brmul_r ((value x/2) (value y*2) (badd res y))
else brmul_r (x y*2 res)
end.
but it doesn't work.. what should I do?
Thank you in advance!
There are many problems with that code:
Syntax error: you want to use => instead of -> inside the match.
Actually, you are not taking advantage of the patter matching, so you can remove it entirely and start your definition with if ....
Then Coq complains that _ > _ has type Prop. You need to use the boolean version _ <? _ instead, and the same for the equality later: _ =? _ instead of _ = _.
In brmul_r ((value x/2) (value y*2) (badd res y)), the outer brackets are not supposed to be there; brmul_r is supposed to receive three arguments, not one argument, and similarly for brmul_r (x y*2 res)
What do you mean by value x/2? Is it value (x / 2) or (value x) / 2? The former does not type-check unless you redefined the _ / _ notation to work over lists of booleans. But the latter has type nat, and brmul_r expects something of type list bool, so it doesn't work either. A similar observation holds for value y*2.
This is not something Coq complains about yet (the problem in 5 would have to be solved first), but it will not be clear for Coq that your definition terminates, since you are using brmul_r to define brmul_r and feeding it non-structurally decreasing arguments. In fact, you even feed it increasing arguments in the final branch (I'm talking about brmul_r x y*2 res).
So what should one do? Convincing Coq that the function terminates is the real issue here, the rest is just confusion over syntax. Since this is a function on lists, it should recurse on the list structure, so it should have the following basic shape (I am assuming the context of Require Import List. Import ListNotations.):
Fixpoint brmul_r (xs ys : list bool) : list bool :=
match xs with
| [] => (* TODO *)
| hd :: tl => (* TODO *)
end.
Assuming the first element of the list is the least significant bit, it will be useful to match on it as well, so the structure becomes:
Fixpoint brmul_r (xs ys : list bool) : list bool :=
match xs with
| [] => (* TODO *)
| false :: tl => (* TODO *)
| true :: tl => (* TODO *)
end.
Now the goal is to express the product of false :: tl with ys when we already know the product of tl with ys. Translating to numbers (for intuition's sake), we want to find (2 * (value tl)) * (value ys) when we already know how to compute (value tl) * (value ys). Putting it like this, it becomes clear that we just need to duplicate the result of the latter. Going back to our list representation, we observe that duplicating corresponds to preppending false, so we can update our definition as follows:
Fixpoint brmul_r (xs ys : list bool) : list bool :=
match xs with
| [] => (* TODO *)
| false :: tl => false :: brmul_r tl ys
| true :: tl => (* TODO *)
end.
Now you can use the same reasoning to complete the function.
For the future:
Please include the necessary context. In this case it would be the modules you imported and the custom defined functions such as value.
It might be useful to follow a Coq tutorial to help with all the syntax issues and with the intuitions behind recursive and functional programming. Software Foundations is very good. There are also others.
There is now a dedicated Stack Exchange site for Proof Assistant-related questions.

Working with options in SML, pattern matching

I am trying to build a get element from list function in SML:
fun get_nth e =
case e of
[] => NONE
| (x::xs, n) => if n = 1
then SOME x
else SOME get_nth(xs, n-1)
This produces the following error:
hw1pm.sml:72.24-72.45 Error: operator is not a function [tycon mismatch]
operator: ('Z -> 'Y) option
in expression:
(SOME get_nth) (xs,n - 1)
hw1pm.sml:68.5-72.45 Error: types of rules do not agree [tycon mismatch]
earlier rule(s): 'Z list -> 'Y option
this rule: _ list * [- ty] -> _ option
in rule:
(:: (x,xs),n) =>
if n = 1 then SOME x else (SOME get_nth) (xs,<exp> - <exp>)
I don't think I understand options well enough, what am I doing wrong?
get_nth already produces an option, so there's no need to wrap it in another "option layer" with SOME.
Also, function application binds very tightly - as SML says, you actually have the equivalent of (SOME get_nth) (xs, n-1), which means that SOME get_nth would be a function.
(If adding SOME had been correct, it would have been SOME (get_nth(xs, n-1)).)
The second error occurs because your pattern matching is also wrong; you can't have a list ([]) in one case, and a pair in another.
With those two fixes, you get
fun get_nth e =
case e of
([], _) => NONE
| (x::xs, n) => if n = 1
then SOME x
else get_nth(xs, n-1)
but it's more common to define a function with several pattern clauses than to use case:
fun get_nth ([], _) = NONE
| get_nth (x::xs, n) = if n = 1
then SOME x
else get_nth(xs, n-1)

Scala - error: type not found

I am a newbie in Scala and I have an error that i cannot understand. Here is my array of int : (numbers from 1 to 100)
val rdd = sc.parallelize(1 to 100)
Next I wrote a function, which is returning the MAX value of my array:
rdd.reduce((x, y) => x > y ? x : y)
But I always get this error:
<console>:30: error: not found: type y
rdd.reduce((x, y) => x > y ? x : y)
^
I don't really know what the error means so i can't find a solution. But if i use my function like this, it works:
rdd.reduce((x, y) => if(x > y) x else y)
Thank you for your answers !
There is no ? : operator in Scala, use if instead:
rdd.reduce((x, y) => if (x > y) x else y)
Or use max instead of building it on your own:
rdd.reduce((x, y) => x max y)
Or with _ syntax for anonymous function:
rdd.reduce(_ max _)
Or avoid building collection max on your own:
rdd.max

decoding scalacheck and scalatest code

I was trying to decipher what this actually means
check { (n: Int) =>
n > 1 ==> n / 2 > 0
}
from http://www.scalatest.org/user_guide/writing_scalacheck_style_properties
I am first trying to decipher whether that body is
((n: Int) => n > 1) ==> n/2 > 0
or
(n: Int) => (n > 1 ==> n/2 > 0)
Which one would it be? I am guessing the latter since check method takes a function though the method '==>' could be returning a function as well?
Next, I look at the check method signature at https://searchcode.com/codesearch/view/12336175/
def check[A1,P](f: A1 => P)
(implicit
p: P => Prop,
a1: Arbitrary[A1], s1: Shrink[A1]
) {
check(Prop.property(f)(p, a1, s1))
}
I believe A1 would be the Int unless ==> returns a function and changes the return type(doubtful though I think). I am not sure how to find the implicit function P => Prop in the scalacheck library.
I do notice there is an ExtendedBoolean that has a function ==> https://github.com/rickynils/scalacheck/blob/master/src/main/scala/org/scalacheck/Prop.scala
Perhaps (n > 1) was converted to an ExtendedBoolean assuming the function was (n: Int) => (n > 1 ==> n/2 > 0) and then we get
ExtendedBoolean( n > 1 ).==>( n / 2 > 0 ) is called then.
Since the implementation of ==> for ExtendedBoolean is Prop(b) ==> p, I end up with
Prop( n > 1 ) ==> (n / 2 > 0)
I get really confused here as in call by name, the values are usually captured except there is no value for n at this point since it was originally a function. ignoring my confusion for a second, the implementation of ==> for Prop is thus
def ==>(p: => Prop): Prop = flatMap { r1 =>
if(r1.proved) p map { r2 => mergeRes(r1,r2,r2.status) }
else if(!r1.success) Prop(r1.copy(status = Undecided))
else p map { r2 => provedToTrue(mergeRes(r1,r2,r2.status)) }
}
so, we are calling this like so I think with another implicit version to Prop here
Prop( n > 1 ) ==> Prop(n / 2 > 0)
ok, and flatmap is
Prop(prms => f(this(prms))(prms))
hmmm, there must have been another conversion to Prop . I start to trace prms and then look at the object Prop apply method for Booleans which is
def apply(b: Boolean): Prop = if(b) proved else falsified
but I can't resolve b to true or false since those functions have not been evaluated yet. How is all this working together? I think I am missing a few concepts here just barely. Can someone explain this a bit better?
Yours is really a ScalaCheck question, but one way to avoid the whole question is to use ScalaTest's PropertyChecks syntax instead of ScalaCheck's (which is supported in ScalaTest by Checkers):
import org.scalatest.prop.Checkers._
check { (n: Int) =>
n > 1 ==> n / 2 > 0
}
becomes:
import org.scalatest.MustMatchers._
import org.scalatest.prop.PropertyChecks._
forAll { (n: Int) =>
whenever (n > 1) {
n / 2 must be > 0
}
}

Make [StackExp] instance of Expr class

I make class Expr for arithmetic operations
class Expr a where
mul :: a -> a -> a
add :: a -> a -> a
lit :: Integer -> a
i want to "parse" something like this: mul ( add (lit 3) (lit 2)) (lit 4) = (3+2)*4
and i have data type:
data StackExp = PushI Integer
| PushB Bool
| Add
| Mul
| And
| Or
deriving Show
and
type Program = [StackExp] --i use this type for function of stack calculator later
my task is: i need to make instance of Expr for type Program
more concrete - i want to make this transformation:
mul ( add (lit 3) (lit 2)) (lit 4) ->>> [PushI 2, PushI 3, Add, PushI 4, Mul]
i have problems because i receive [[StackExp]] at the output of my instance declaration.
my try:
instance Expr Program where
lit n = (PushI n):[]
add exp1 exp2 = exp1:(exp2:[Add])
mul exp1 exp2 = exp1:(exp2:[Mul])
i don't know how to concatenate all sub-expressions into list
---------------- compiler error looks like this------------------------
Couldn't match type `[StackExp]' with `StackExp'
Expected type: StackExp
Actual type: Program
..........
So, what you basically want to do is you want to compile from the abstract syntax of your expression language (the type class Expr) to code for a simple stack machine (a list of elements of type StackExpr).
One problem that you immediately run into then is that, in just Haskell 98 or Haskell 2010, you cannot declare [StackExpr] an instance of a class. For example, GHC will complain with
Illegal instance declaration for `Expr [StackExp]'
(All instance types must be of the form (T a1 ... an)
where a1 ... an are *distinct type variables*,
and each type variable appears at most once in the instance head.
Use -XFlexibleInstances if you want to disable this.)
In the instance declaration for `Expr [StackExp]'
To work your way around this, you could define Program as a type isomorphism (rather than as a mere type synonym as you have now):
newtype Program = P [StackExp] deriving Show
and then make Program an instance of the class Expr. (Alternatively, you could enable FlexibleInstances as suggested by the error message above.)
Now we can write the required instance declaration:
instance Expr Program where
mul (P x) (P y) = P (x ++ y ++ [Mul])
add (P x) (P y) = P (x ++ y ++ [Add])
lit n = P [PushI n]
That is, for multiplication and addition, we first compile the operands and then produce, respectively, the Mul or Add instruction; for literals we produce the corresponding push instruction.
With this declaration, we get, for your example:
> mul (add (lit 3) (lit 2)) (lit 4) :: Program
P [PushI 3,PushI 2,Add,PushI 4,Mul]
(Not quite as in your example. You swap the order of the operands to Add. As addition is commutative, I will assume that this version is acceptable as well.)
Of course it is more fun to also write a small evaluator for stack programs:
eval :: Program -> [Integer]
eval (P es) = go es []
where
go [] s = s
go (PushI n : es) s = go es (n : s)
go (Add : es) (m : n : s) = go es ((m + n) : s)
go (Mul : es) (m : n : s) = go es ((m * n) : s)
(Note that I am ignoring instructions that deal with Booleans here as you only seem to deal with integer expressions anyway.)
Now we have, for your example,
> eval (mul (add (lit 3) (lit 2)) (lit 4))
[20]
which seems about right.