How to access a list in OCaml - find

I want to write a function that could check every item in a list is true or false. If at least one element is false, it will return true, so that:
assert_eq "checkFalse [true; false; true]" (checkFalse [true; true; true]) false;
assert_eq "checkFalse [false; false]" (checkFalse [false; true]) true;
I am an absolute beginner in OCaml and I don't know how to approach this. I tried using a for loop, something like:
let rec checkFalse (bools: bool list) : bool =
for i = 0 to bools.length do
if bools.length == false then false
else... (I don't know how to continue)
Then it said "Unbound record field...."
I also tried using find like:
if (find false bools != Not_found) then true else false
But my ways did not work. I came from a Java background.

Take a look at the List module: http://caml.inria.fr/pub/docs/manual-ocaml/libref/List.html specifically the exists method. For what you want, you can simply do this:
List.exists (fun x -> not x) [true;true;...;false;...]
The exists function will return true if any element in the list satisfies the predicate (the function). In this case, the predicate is fun x -> not x which will return true if x is false.
For general list access, you generally do this using pattern matching and recursion, or using the functions iter, map, fold_left, and fold_right (among others). Here's an implementation of exists using pattern matching:
let rec exists f l = match l with
| [] -> false (* the list is empty, return false *)
| h::t -> if (f h) then true (* the list has a head and a (possibly empty) tail. Check the return value of the predicate 'f' when applied to the head *)
else exists f t (* the predicate is false, recursively call the `exists` function on the tail *)
edit: as Chuck has posted, instead of fun x -> not x you can just simply use not.
Another possibility is to use the mem function:
List.mem false bools

let rec checkFalse xs =
match xs with [] -> false
| false :: _ -> true
| _ :: tl -> checkFalse tl;;

The simplest way would just be let checkFalse = List.exists not.
List.exists takes a function and a list as arguments, and tells if the function you passed returns true for any element in the list. not returns the negation of a bool.

let checkFalse = List.exists (fun elem -> elem = false) your_list in
doc:
val exists : ('a -> bool) -> 'a list -> bool
exists p [a1; ...; an] checks if at least one element of the list satisfies the predicate p.
That is, it returns (p a1) || (p a2) || ... || (p an).

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.

Found a constructor of inductive type bool while a constructor of list is expected

I have the following question : Define the fonction value : list bool -> nat that return the value represented by a list of booleans(binary number to decimal number). For example, value [false;true;false;true] = 10.
I wrote this:
Fixpoint value (l: list bool) := match l with
|true=> 1
|false=> 0
|x::r => (value [x])+2*(value r)
end.
but I get this error : "Found a constructor of inductive type bool
while a constructor of list
is expected."
I have tried to put false and true as bool list : [false] [true]
but it still doesn't work... What should I do?
Indeed, Coq rightfully complains that you should use a constructor for list, and true and false are booleans, not lists of booleans. You are right that [true] and [false] should be used.
Then after this, Coq should still complain that you did not specify your function on the empty list, so you need to add a case for it like so:
Fixpoint value (l: list bool) :=
match l with
| [] => 0
| [ true ] => 1
| [ false ] => 0
| x :: r => value [x] + 2 * value r
end.
This time Coq will still complain but for another reason: it doesn't know that [x] is smaller than x :: r. Because it isn't the case syntactically.
To fix it, I suggest to simply deal with the two cases: true and false. This yields something simpler in any case:
From Coq Require Import List.
Import ListNotations.
Fixpoint value (l: list bool) :=
match l with
| [] => 0
| true :: r => 1 + 2 * value r
| false :: r => 2 * value r
end.

Dependent functions in Coq

I am very new to Coq, and hope my question is not too basic. I am simply wondering how I define dependent functions in Coq. For example, how could I define a function from Booleans that sends true to true and false to the natural number seven ? I assume one can use the usual (f x) notation to apply a dependent function f to an input x.
To define dependent functions in Coq, you refer back to the parameter when specifying the type. In your example, you take a Boolean, let's call it b, and your return type is match b with true => bool | false => nat end (or if b then bool else nat).
In code, that looks like the following:
Definition foo (b : bool)
: match b with true => bool | false => nat end
:= match b with true => true | false => 7 end.
Compute foo true. (* = true *)
Compute foo false. (* = 7 *)
There is a little bit of magic that goes on in figuring out the type of the match construct here, if you give more type annotations it looks like
Definition foo'
: forall b : bool, match b return Set with true => bool | false => nat end
:= fun b : bool =>
match b as b'
return match b' return Set with true => bool | false => nat end
with true => true | false => 7 end.
Here, since the match construct can have different types depending on the value of b (which can be an arbitrary term, not just a variable), we use the annotation as b' return ... to give b a new name, and then specify the type of the match depending on the value of b'.
However, particularly when matching on a variable, Coq can often figure out the return ... annotation on it's own.
You can find some documentation of the match construct here, in the reference manual

How to check if a value exists in a list in smlnj

I'm working on some homework and I need to create a function that checks if a value exists in a list. If it does it will return true, otherwise it returns false. I have an idea of how to do it but I keep getting errors. I think it may be due to my lack of knowledge of syntax and style as this is my first time coding in sml.
I created the function exist and am passing a value and list in as a tuple.
fun exist (x, []) =
if x = hd ([]) then true
else if x = tl ([]) then true
else false;
Sorry if this code is laughably incorrect but I get the error message:
" stdIn:2.6 Warning: calling polyEqual
stdIn:3.11 Warning: calling polyEqual
stdIn:1.6-4.11 Warning: match nonexhaustive
(x,nil) => ...
val exist = fn : ''a list * 'b list -> bool "
and I'm not really sure how to fix this. Any help would be great.
Your function is pattern-matching on [], so it can only ever match the empty list.
Also, hd [] and tl [] are both errors since the empty list has neither head nor tail.
Further, if some_condition then true else false is equivalent to some_condition.
(And if some_condition then false else true is equivalent to not some_condition.)
Logical expressions are usually more readable than chains of conditionals.
And you forgot to recurse; you need to use exist on the tail of the list if the first element is not what you're looking for.
Either stick to pattern matching:
fun exist (_, []) = false
| exist (x, y::ys) = x = y orelse exist (x, ys)
or don't use it:
fun exist (x, xs) = not (null xs) andalso (x = hd xs orelse exist (x, tl xs))
Pattern matching is often the most readable solution and gives a clear picture of the various cases.
(You seem to have mixed the two forms, treating [] as an identifier rather than a type constructor.)

Too many possible configurations in z3 using scala^z3

This is mainly a logic problem I guess...
I use this smtlib formula:
(declare-fun a () Bool)
(declare-fun b () Bool)
(declare-fun c () Bool)
(declare-fun d () Bool)
(assert (xor (and a (xor b c)) d))
Which is a term of this structure(in my opinion, at least):
XOR
| |
AND d
| |
a XOR
| |
b c
My guess: The resultSet would look like this:
{ab, ac, d}
But its this using scala^z3 ctx.checkAndGetAllModels():
{ab, d, ac, ad, abcd}
Why is ad and abcd in there?
Is it possible to get only the results I would expect?
Using Scala (without Z3) to show that there are, in fact, more solutions to the constraint:
val tf = Seq(true, false)
val allValid =
for(a <- tf; b <- tf; c <- tf; d <- tf;
if((a && (b ^ c)) ^ d)) yield (
(if(a) "a" else "") + (if(b) "b" else "") +
(if(c) "c" else "") + (if(d) "d" else ""))
allValid.mkString("{ ", ", ", " }")
Prints:
{ abcd, ab, ac, ad, bcd, bd, cd, d }
So unless I'm missing something, the question is, why does it not find all solutions? Now here is the answer to that one. (Spoiler alert: "getAllModels" doesn't really get all models.) First, let's reproduce what you observed:
import z3.scala._
val ctx = new Z3Context("MODEL" -> true)
val a = ctx.mkFreshConst("a", ctx.mkBoolSort)
val b = ctx.mkFreshConst("b", ctx.mkBoolSort)
val c = ctx.mkFreshConst("c", ctx.mkBoolSort)
val d = ctx.mkFreshConst("d", ctx.mkBoolSort)
val cstr0 = ctx.mkXor(b, c)
val cstr1 = ctx.mkAnd(a, cstr0)
val cstr2 = ctx.mkXor(cstr1, d)
ctx.assertCnstr(cstr2)
Now, if I run: ctx.checkAndGetAllModels.foreach(println(_)), I get:
d!3 -> false
a!0 -> true
c!2 -> false
b!1 -> true
d!3 -> true // this model is problematic
a!0 -> false
d!3 -> false
a!0 -> true
c!2 -> true
b!1 -> false
d!3 -> true
a!0 -> true
c!2 -> false
b!1 -> false
d!3 -> true
a!0 -> true
c!2 -> true
b!1 -> true
Now, the problem is that the second model is an incomplete model. Z3 can return it, because whatever the values for b and c are, the constraint is satisfied (b and c are don't-care variables). The current implementation of checkAndGetAllModels simply negates the model to prevent repetition; in this case, it will ask for another model such that (not (and d (not a))) holds. This will prevent all other models with this two values from being returned. In a sense, the incomplete model actually represents four valid, completed, models.
By the way, what happens if you use the DSL of ScalaZ3 with the findAll function is that all models will be completed with default values when they are incomplete (and before they are used to compute the next one). In the context of the DSL we can do this, because we know the set of variables that appear in the formula. In this case, it's harder to guess how the model should be completed. One option would be for ScalaZ3 to remember which variables were used. A better solution would be for Z3 to have an option to always return values for don't-care variables, or perhaps simply to list all don't-care variables in a model.