I am trying to prove the following lemma in Coq:
Require Import Lists.List.
Import ListNotations.
Lemma not_empty : forall (A : Type) (a b : list A),
(a <> [] \/ b <> []) -> a ++ b <> [].
Right now my current strategy was to destruct on a, and after breaking the disjunction I could ideally just state that if a <> [] then a ++ b must also be <> []... That was the plan, but I can't seem to get past a subgoal that resembles the first " a ++ b <> []", even when my context clearly states that " b <> []". Any advice?
I've also looked through a lot of the pre-existing list theorems and haven't found anything particularly helpful (minus app_nil_l and app_nil_r, for some subgoals).
Starting with destruct a is a good idea indeed.
For the case where a is Nil, you should destruct the (a <> [] \/ b <> []) hypothesis. There will be two cases:
the right one the hypothesis [] <> [] is a contradiction,
the left one, the hypothesis b <> [] is your goal (since a = [])
For the case where a is a :: a0, you should use discriminate as Julien said.
You started the right way with your destruct a.
You should end up at some point with a0::a++b<>0. It ressembles a++b<>0 but it is quite different as you have a cons here, thus discriminate knows that it is different from nil.
first, I am not sure which Coq version you are using, the syntax certainly looks odd. Seconds, it is hard for us to help if you don't show us the proof you have so far. I should say that indeed your strategy seems correct, you should destruct both lists, tho it is better if you first inspect the or to see which list is not empty.
Another option is to use computation to show your lemma, in this case, equality will compute and thus you will get the result of the comparison. It suffices to destroy only one list in this case due the order or arguments:
From mathcomp Require Import all_ssreflect.
Lemma not_empty (A : eqType) (a b : seq A) :
[|| a != [::] | b != [::]] -> a ++ b != [::].
Proof. by case: a. Qed.
Related
I am working on a program that adds matrices. (The same size) I have the vector add (adding 2 lists together), but my matadd doesn't work. It keeps returning the second list. Any ideas?
let rec vecadd a b =
match a, b with
| [], [] -> []
| a::at, b::bt -> (a + b) :: (vecadd at bt)
//vecadd [1;2;3] [4;5;6];; Would return [5;7;9]
let rec matadd a b =
match [[a;b];[a;b]] with
|[[h::t] ; [h2::t2]]-> (vecadd h h2 ) :: (matadd t t2)
//matadd [[1;2];[3;4];[5;6]];[[1;2];[3;4];[5;6]];; Would return [[2;4][6;8];[10;12]]
See earlier question Adding 2 Int Lists Together F# related to vecadd.
I think you have the concept of pattern matching all jumbled up in your head.
When you match [ [a;b]; [a;b] ] with [ [h::t]; [h2::t2] ], it matches [a;b] with [h::t] and [a;b] with [h2::t2] respectively. This means that you always get h = h2 = a and t = t2 = [b]. So when you vecadd h and h2, you're essentially just doubling a. I'm not going to explain further, because it just doesn't make any sense. I hope you'll be able to see it by now.
To add two lists of lists, you can apply the exact same logic that I gave you for adding the vectors themselves: the sum of two empty lists is an empty list; otherwise, the sum is the sum of lists' tails prepended by the sum of their heads. Or to translate it into F#:
let rec matadd a b =
match a, b with
| [], [] -> []
| a::atail, b::btail -> (vecadd a b) :: (matadd atail btail)
Also:
When I gave you the vecadd code in your previous question, I didn't mean that you should just take it as a finished solution. In fact, I even told you outright that it's incomplete (which, by the way, applies just as well to the matadd example above).
It's great to understand recursion while you're learning, but for actual production code you shouldn't use it a lot. Recursion is tricky and easy to get wrong. Instead, you should try to hide recursion in small, general, easily testable functions, and then build all other operations on top of them. For lists, F# already gives you a bunch of such functions. One of them, the one that combines two lists in one, is called zip. Or, if you want to apply a transforming function to the item pairs as you go, use map2.
For example:
let vecadd a b = List.map2 (+) a b
let matadd a b = List.map2 vecadd a b
So I have a lost of String tuples in Haskell.
I declared a type for that:
type Book = [(String, String)]
Then I declared an empty book:
emptyBook :: Book
emptyBook = []
And now I want to create a function that inserts elements to a book. My solution:
insert :: String -> String -> Book -> Book
insert a b emptyBook = (a,b) : []
insert a b (x : xs)= (a, b) : (x:xs)
But the function insert is not working. The compiler loads the module but gives the warning 'Pattern match is redundant'.
Executing insert "a" "1" [("b","2")] gives [("a","1")]
instead of [("a","1"),("b","2")]
Do you know whats going wrong here?
I don't get why you:
use emptybook in your pattern matching part, instead of [];
why you repeat (x:xs) both in the left and in the right part of the expression;
make a distinction between an empty book and a non-empty book.
Why it doesn't work
Because Haskell, like many other languages uses variable scopes, and Haskell sees emptybook in your function as a variable. It does not see (at least not there) that emptybook is a function somewhere defined. So could have written:
insert a b c = (a,b) : []
as well (as second line in your function definition). Now since you define a variable c and did not put any constraints (guards, patterns,...) on it, it matches with everything: so a non-empty book as well. Therefore Haskell will always take the first line. In fact the compiler already warns you for this. It says:
haskell.hs:9:1: Warning:
Pattern match(es) are overlapped
In an equation for ‘insert’: insert a b (x : xs) = ...
This means that the last line of your function definition overlaps with the previous lines. In that case you have probably done something wrong.
Alternative
You can simply use:
insert :: String -> String -> book -> book
insert a b xs = (a,b) : xs
or even shorter:
insert :: String -> String -> book -> book
insert a b = (:) (a,b)
Furthermore types are usually denoted with a capital letter, so you better use Book instead of book.
The clause
insert a b emptyBook = (a,b) : []
defines insert as a function of three general arguments a, b and emptyBook. Well, the last isn't actually used, but that makes no difference – that clause will succeed, no matter what arguments you pass in.
The third argument also shadows the top-level definition emptyBook – basically this makes it so that within the scope of the function, emptyBook is now whatever book you pass in, no matter whether it's empty.
GHC can actually give a warning highlighting this real problem with your code, if you tell it to give generous warnings:
sagemuej#sagemuej-X302LA:~$ runhaskell -Wall /tmp/wtmpf-file2776.hs
/tmp/wtmpf-file2776.hs:7:12: Warning:
This binding for ‘emptyBook’ shadows the existing binding
defined at /tmp/wtmpf-file2776.hs:4:1
/tmp/wtmpf-file2776.hs:7:12: Warning:
Defined but not used: ‘emptyBook’
If you want emptyBook to be a constant that should be matched on, you have to make it explicit that this is not a newly-bound argument variable. A couple of options:
(Not recommended) use equality comparison instead of pattern matching
insert a b book
| book==emptyBook = (a,b) : []
insert a b (x : xs) = (a, b) : (x:xs)
We generally avoid equality comparison in Haskell – it's less general, less efficient and more error-prone than pattern matching.
(Very not recommended) use a C-preprocessor macro (Template Haskell would also work) to actually insert literally [] in that pattern matching. You can't have a variable named [], so this will do the right thing:
{-# LANGUAGE CPP #-}
#define emptyBook []
insert :: String -> String -> Book -> Book
insert a b emptyBook = (a,b) : []
insert a b (x : xs) = (a, b) : (x:xs)
Such macro definitions don't work very well with Haskell – they're completely oblivious of the languages scopes, can't be exported etc..
(Not very recommended) use pattern synonyms. Those are essentially the modern, Haskell-native way of achieving the behaviour I did above with a CPP macro:
{-# LANGUAGE PatternSynonyms #-}
pattern EmptyBook :: Book
pattern EmptyBook = []
insert :: String -> String -> Book -> Book
insert a b emptyBook = (a,b) : []
insert a b (x : xs) = (a, b) : (x:xs)
So, what would be the recommended solution? Well, as Willem Van Onsem says, you just don't need that clause at all – it's already a special case of the second clause!
insert :: String -> String -> Book -> Book
insert a b (x : xs) = (a, b) : (x:xs)
...which is the same as
insert a b (x : xs) = (a, b) : x : xs
or
insert a b xxs = (a, b) : xxs
or
insert a b = ((a, b) :)
or
import Data.Function.Pointless
insert=(:).:(,)
I try to define function with the following protocol:
[(1,2), (6,5), (9,10)] -> [3, 11, 19]
Here is what I have now:
fun sum_pairs (l : (int * int) list) =
if null l
then []
else (#1 hd(l)) + (#2 hd(l))::sum_pairs(tl(l))
According to type checker I have some type mismatch, but I can't figure out where exactly I'm wrong.
This code runs in PolyML 5.2:
fun sum_pairs (l : (int * int) list) =
if null l
then []
else ((#1 (hd l)) + (#2 (hd l))) :: sum_pairs(tl l)
(* ------------^-------------^ *)
The difference from yours is subtle, but significant: (#1 hd(l)) is different from (#1 (hd l)); the former doesn't do what you think - it attempts to extract the first tuple field of hd, which is a function!
While we're at it, why don't we attempt to rewrite the function to make it a bit more idiomatic? For starters, we can eliminate the if expression and the clunky tuple extraction by matching on the argument in the function head, like so:
fun sum_pairs [] = []
| sum_pairs ((a, b)::rest) = (a + b)::sum_pairs(rest)
We've split the function into two clauses, the first one matching the empty list (the recursive base case), and the second one matching a nonempty list. As you can see, this significantly simplified the function and, in my opinion, made it considerably easier to read.
As it turns out, applying a function to the elements of a list to generate a new list is an incredibly common pattern. The basis library provides a builtin function called map to aid us in this task:
fun sum_pairs l = map (fn (a, b) => a + b) l
Here I'm using an anonymous function to add the pairs together. But we can do even better! By exploiting currying we can simply define the function as:
val sum_pairs = map (fn (a, b) => a + b)
The function map is curried so that applying it to a function returns a new function that accepts a list - in this case, a list of integer pairs.
But wait a minute! It looks like this anonymous function is just applying the addition operator to its arguments! Indeed it is. Let's get rid of that too:
val sum_pairs = map op+
Here, op+ denotes a builtin function that applies the addition operator, much like our function literal (above) did.
Edit: Answers to the follow-up questions:
What about arguments types. It looks like you've completely eliminate argument list in the function definition (header). Is it true or I've missed something?
Usually the compiler is able to infer the types from context. For instance, given the following function:
fun add (a, b) = a + b
The compiler can easily infer the type int * int -> int, as the arguments are involved in an addition (if you want real, you have to say so).
Could you explain what is happening here sum_pairs ((a, b)::rest) = (a + b)::sum_pairs(rest). Sorry for may be dummy question, but I just want to fully understand it. Especially what = means in this context and what order of evaluation of this expression?
Here we're defining a function in two clauses. The first clause, sum_pairs [] = [], matches an empty list and returns an empty list. The second one, sum_pairs ((a, b)::rest) = ..., matches a list beginning with a pair. When you're new to functional programming, this might look like magic. But to illustrate what's going on, we could rewrite the clausal definition using case, as follows:
fun sum_pairs l =
case l of
[] => []
| ((a, b)::rest) => (a + b)::sum_pairs(rest)
The clauses will be tried in order, until one matches. If no clause matches, a Match expression is raised. For example, if you omitted the first clause, the function would always fail because l will eventually be the empty list (either it's empty from the beginning, or we've recursed all the way to the end).
As for the equals sign, it means the same thing as in any other function definition. It separates the arguments of the function from the function body. As for evaluation order, the most important observation is that sum_pairs(rest) must happen before the cons (::), so the function is not tail recursive.
I have an ocaml type :
type t = A | B | ...
and a function to print things about that type :
let pp_t fmt x = match x with
| A -> Format.fprintf fmt "some nice explanations about A"
| B -> Format.fprintf fmt "some nice explanations about B"
| ...
How could I write a function to print all the explanations ? Something equivalent to :
let pp_all_t fmt =
Format.fprintf fmt A;
Format.fprintf fmt B;
...
but that would warn me if I forget to add a new constructor.
It would be even better to have something that automatically build that function,
because my problem is that t is quiet big and changes a lot.
I can't imagine how I can "iterate" on the type constructors, but maybe there is a trick...
EDIT: What I finally did is :
type t = A | B | ... | Z
let first_t = A
let next_t = function A -> B | B -> C | ... | Z -> raise Not_found
let pp_all_t fmt =
let rec pp x = pp_t fmt x ; try let x = next_t x in pp x with Not_found -> ()
in pp first_t
so when I update t, the compiler warns me that I have to update pp_t and next_t, and pp_all_t doesn't have to change.
Thanks to you all for the advices.
To solve your problem for a complicated and evolving type, in practice I would probably write an OCaml program that generates the code from a file containing a list of the values and the associated information.
However, if you had a function incr_t : t -> t that incremented a value of type t, and if you let the first and last values of t stay fixed, you could write the following:
let pp_all_t fmt =
let rec loop v =
pp_t fmt v;
if v < Last_t then loop (incr_t v)
in
loop First_t
You can't have a general polymorphic incr_t in OCaml, because it only makes sense for types whose constructors are nullary (take no values). But you can write your own incr_t for any given type.
This kind of thing is handled quite nicely in Haskell. Basically, the compiler will write some number of functions for you when the definitions are pretty obvious. There is a similar project for OCaml called deriving. I've never used it, but it does seem to handle the problem of enumerating values.
Since you say you want a "trick", if you don't mind using the unsafe part of OCaml (which I personally do mind), you can write incr_t as follows:
let incr_t (v: t) : t =
(* Please don't use this trick in real code :-) ! See discussion below.
*)
if t < Last_t then
Obj.magic (Obj.magic v + 1)
else
failwith "incr_t: argument out of range"
I try to avoid this kind of code if at all possible, it's too dangerous. For example, it will produce nonsense values if the type t gets constructors that take values. Really it's "an accident waiting to happen".
One needs some form of metaprogramming for such tasks. E.g. you could explore deriving to generate incr_t from the Jeffrey's answer.
Here is a sample code for the similar task : https://stackoverflow.com/a/1781918/118799
The simplest thing you can do is to define a list of all the constructors:
let constructors_t = [A; B; ...]
let pp_all_t = List.iter pp_t constructors_t
This is a one-liner, simple to do. Granted, it's slightly redundant (which gray or dark magic would avoid), but it's still probably the best way to go in term of "does what I want" / "has painful side effects" ratio.
I've managed to get xUnit working on my little sample assembly. Now I want to see if I can grok FsCheck too. My problem is that I'm stumped when it comes to defining test properties for my functions.
Maybe I've just not got a good sample set of functions, but what would be good test properties for these functions, for example?
//transforms [1;2;3;4] into [(1,2);(3,4)]
pairs : 'a list -> ('a * 'a) list //'
//splits list into list of lists when predicate returns
// true for adjacent elements
splitOn : ('a -> 'a -> bool) -> 'a list -> 'a list list
//returns true if snd is bigger
sndBigger : ('a * 'a) -> bool (requires comparison)
There are already plenty of specific answers, so I'll try to give some general answers which might give you some ideas.
Inductive properties for recursive functions. For simple functions, this amounts probably to re-implementing the recursion. However, keep it simple: while the actual implementation more often than not evolves (e.g. it becomes tail-recursive, you add memoization,...) keep the property straightforward. The ==> property combinator usually comes in handy here. Your pairs function might make a good example.
Properties that hold over several functions in a module or type. This is usually the case when checking abstract data types. For example: adding an element to an array means that the array contains that element. This checks the consistency of Array.add and Array.contains.
Round trips: this is good for conversions (e.g. parsing, serialization) - generate an arbitrary representation, serialize it, deserialize it, check that it equals the original.
You may be able to do this with splitOn and concat.
General properties as sanity checks. Look for generally known properties that may hold - things like commutativity, associativity, idempotence (applying something twice does not change the result), reflexivity, etc. The idea here is more to exercise the function a bit - see if it does anything really weird.
As a general piece of advice, try not to make too big a deal out of it. For sndBigger, a good property would be:
let ``should return true if and only if snd is bigger`` (a:int) (b:int) =
sndBigger (a,b) = b > a
And that is probably exactly the implementation. Don't worry about it - sometimes a simple, old fashioned unit test is just what you need. No guilt necessary! :)
Maybe this link (by the Pex team) also gives some ideas.
I'll start with sndBigger - it is a very simple function, but you can write some properties that should hold about it. For example, what happens when you reverse the values in the tuple:
// Reversing values of the tuple negates the result
let swap (a, b) = (b, a)
let prop_sndBiggerSwap x =
sndBigger x = not (sndBigger (swap x))
// If two elements of the tuple are same, it should give 'false'
let prop_sndBiggerEq a =
sndBigger (a, a) = false
EDIT: This rule prop_sndBiggerSwap doesn't always hold (see comment by kvb). However the following should be correct:
// Reversing values of the tuple negates the result
let prop_sndBiggerSwap a b =
if a <> b then
let x = (a, b)
sndBigger x = not (sndBigger (swap x))
Regarding the pairs function, kvb already posted some good ideas. In addition, you could check that turning the transformed list back into a list of elements returns the original list (you'll need to handle the case when the input list is odd - depending on what the pairs function should do in this case):
let prop_pairsEq (x:_ list) =
if (x.Length%2 = 0) then
x |> pairs |> List.collect (fun (a, b) -> [a; b]) = x
else true
For splitOn, we can test similar thing - if you concatenate all the returned lists, it should give the original list (this doesn't verify the splitting behavior, but it is a good thing to start with - it at least guarantees that no elements will be lost).
let prop_splitOnEq f x =
x |> splitOn f |> List.concat = x
I'm not sure if FsCheck can handle this though (!) because the property takes a function as an argument (so it would need to generate "random functions"). If this doesn't work, you'll need to provide a couple of more specific properties with some handwritten function f. Next, implementing the check that f returns true for all adjacent pairs in the splitted lists (as kvb suggests) isn't actually that difficult:
let prop_splitOnAdjacentTrue f x =
x |> splitOn f
|> List.forall (fun l ->
l |> Seq.pairwise
|> Seq.forall (fun (a, b) -> f a b))
Probably the only last thing that you could check is that f returns false when you give it the last element from one list and the first element from the next list. The following isn't fully complete, but it shows the way to go:
let prop_splitOnOtherFalse f x =
x |> splitOn f
|> Seq.pairwise
|> Seq.forall (fun (a, b) -> lastElement a = firstElement b)
The last sample also shows that you should check whether the splitOn function can return an empty list as part of the returned list of results (because in that case, you couldn't find first/last element).
For some code (e.g. sndBigger), the implementation is so simple that any property will be at least as complex as the original code, so testing via FsCheck may not make sense. However, for the other two functions here are some things that you could check:
pairs
What's expected when the original length is not divisible by two? You could check for throwing an exception if that's the correct behavior.
List.map fst (pairs x) = evenEntries x and List.map snd (pairs x) = oddEntries x for simple functions evenEntries and oddEntries which you can write.
splitOn
If I understand your description of how the function is supposed to work, then you could check conditions like "For every list in the result of splitOn f l, no two consecutive entries satisfy f" and "Taking lists (l1,l2) from splitOn f l pairwise, f (last l1) (first l2) holds". Unfortunately, the logic here will probably be comparable in complexity to the implementation itself.