Is there a more elegant way to write the following Coq code? - coq

match x with
| Some x => Some (Ref x)
| None => None
end.
I have to do this quite a lot, nested matches make code look bad. Is there some more elegant, one liner sort of way to lift things out of Option?

There is option_map function in Coq.Init.Datatypes defined as follows:
Definition option_map (A B:Type) (f:A->B) (o : option A) : option B :=
match o with
| Some a => #Some B (f a)
| None => #None B
end.
You can use it just like #ejgallego showed in the comments: option_map Ref x.
Here is how you can discover this function:
Search (option _ -> option _).

More generally, you may want to consider using monadic syntax; it is easy to define some yourself with a couple of Notation declarations, or you can use a more featureful library like Gregory Malecha's ExtLib.

Related

How to solve the very simple Syntax error: 'end' expected after [branches] (in [term_match]). in Coq? (in Gallina and not ltac)

I was trying to write a very simple program to sum nats in a list (copy pasted from here):
Fixpoint sum (l : list nat) : nat :=
match l with
| [] => 0
| x :: xs => x + sum xs
end.
but my local Coq and jsCoq complain:
Syntax error: 'end' expected after [branches] (in [term_match]).
Why is this? (note I didn't even implement this but my implementation looks the same pretty much)
I've implemented recursive functions before:
Inductive my_nat : Type :=
| O : my_nat
| S : my_nat -> my_nat.
Fixpoint add_left (n m : my_nat) : my_nat :=
match n with
| O => m
| S n' => S (add_left n' m)
end.
which doesn't complain...
I did see this question How to match a "match" expression? but it seems to address some special issue in ltac and I am not using ltac.
The location of the error is on the [], which suggests that Coq does not understand that notation. Upon finding undefined notation, the parser has no idea what to do and produces an essentially meaningless error message.
To have standard list notation be defined, you need to import it from the standard library via:
Require Import List.
Import ListNotations.
The stdlib module List contains the module ListNotations, which defines [] (and more generally [ x ; y ; .. ; z ]). List also defines the notation x :: xs.
when picking up excerpts from a development, you also have to find what are the syntax changing commands that have an effect on this exceprts: Module importation, scope opening, argument declarations (for implicits), Notations, and coercions". In the current case, the file is actually provided by the author of the exercises through this pointer.

How to raise exception in Coq?(in match ... end)

I need to define recursive definitions, but I don't no yet how to do it correctly().
So I want to have partially defined function which will say when it need additional level of recursion to be written.
Context (qsigT: forall (A : Type) (P : forall a : A, Type), Type).
Context (qpr1: forall (A : Type) (P : forall a : A, Type), (#qsigT A P) -> A ).
Record Category :={
ty:>Type
}.
Context (uc:Category).
Context (mO mS: uc -> Type).
Definition ur0:= (#qsigT uc (fun x => mO (x) ) ).
Definition ur1:= (#qsigT ur0 (fun x => mS (qpr1 _ _ x) ) ).
Definition ur2:= (#qsigT ur1 (fun x => mS (qpr1 _ _ (qpr1 _ _ x)) ) ).
Definition ur3:= (#qsigT ur2 (fun x => mS (qpr1 _ _ (qpr1 _ _ (qpr1 _ _ x))) ) ).
(*and so on ...*)
Definition ur (n: nat) := (match n with
|0 => ur0
|1 => ur1
|2 => ur2
|_ => ur3
(*|_ => error*)
end).
1)Is it possibly to create exception on all natural numbers greater than 3? (during the pattern matching)
2)Is there a low level instrument which will not coerce me to use monades?
3)Is it possibly to define my function 'ur' on all natural numbers in Coq?
4)Is there some kind of combinator that will apply function 'pr1' n times?
5)Shall I create 5 different question (with one on the meta :-) ) or it is right way to ask?
1) Is it possibly to create exception on all natural numbers greater
than 3? (during the pattern matching)
No. Coq is a total language. The standard pattern for this is to make your function to return option T for type T, so you work in a partiality monad. Example:
Definition ur (n: nat) := (match n with
| 0 => Some ur0
| 1 => Some ur1
| 2 => Some ur2
| 3 => Some ur3
| _ => None
end).
2) Is there a low level instrument which will not coerce me to use monads?
See above. Whether you want to call it "monad" or not is up to you.
Another approach is to have a "default" value urF that you return when you "fail" the pattern matching. This approach is more convenient than the option type in a wide variety of situations.
3) Is it possibly to define my function 'ur' on all natural numbers in Coq?
I think so. Please provide the missing definitions and we may try.
4) Is there some kind of combinator that will apply function 'pr1' n times?
In principle yes, but it'd depend on the exact type you want for it.
5) Shall I create 5 different question (with one on the meta :-) ) or it is right way to ask?
Maybe. The biggest problem of this question is that the code is not
self-contained.

How to Create Ensemble in Coq

How do I create a set of elements in Coq?
I have looked at the documentation for Ensembles but I don't see any way to construct one. For example, in Haskell I'd use the "Data.Set.fromList [1..10]" to create a set with 10 elements. What's the equivalent in Coq?
Thanks.
As explained here, you can for example do something like
Require Import List Ensembles.
Fixpoint list_to_set {A:Type} (l : list A) {struct l}: Ensemble A :=
match l with
| nil => Empty_set A
| hd :: tl => Add A (list_to_set tl) hd
end.

How to concisely express function iteration?

Is there a concise, idiomatic way how to express function iteration? That is, given a number n and a function f :: a -> a, I'd like to express \x -> f(...(f(x))...) where f is applied n-times.
Of course, I could make my own, recursive function for that, but I'd be interested if there is a way to express it shortly using existing tools or libraries.
So far, I have these ideas:
\n f x -> foldr (const f) x [1..n]
\n -> appEndo . mconcat . replicate n . Endo
but they all use intermediate lists, and aren't very concise.
The shortest one I found so far uses semigroups:
\n f -> appEndo . times1p (n - 1) . Endo,
but it works only for positive numbers (not for 0).
Primarily I'm focused on solutions in Haskell, but I'd be also interested in Scala solutions or even other functional languages.
Because Haskell is influenced by mathematics so much, the definition from the Wikipedia page you've linked to almost directly translates to the language.
Just check this out:
Now in Haskell:
iterateF 0 _ = id
iterateF n f = f . iterateF (n - 1) f
Pretty neat, huh?
So what is this? It's a typical recursion pattern. And how do Haskellers usually treat that? We treat that with folds! So after refactoring we end up with the following translation:
iterateF :: Int -> (a -> a) -> (a -> a)
iterateF n f = foldr (.) id (replicate n f)
or point-free, if you prefer:
iterateF :: Int -> (a -> a) -> (a -> a)
iterateF n = foldr (.) id . replicate n
As you see, there is no notion of the subject function's arguments both in the Wikipedia definition and in the solutions presented here. It is a function on another function, i.e. the subject function is being treated as a value. This is a higher level approach to a problem than implementation involving arguments of the subject function.
Now, concerning your worries about the intermediate lists. From the source code perspective this solution turns out to be very similar to a Scala solution posted by #jmcejuela, but there's a key difference that GHC optimizer throws away the intermediate list entirely, turning the function into a simple recursive loop over the subject function. I don't think it could be optimized any better.
To comfortably inspect the intermediate compiler results for yourself, I recommend to use ghc-core.
In Scala:
Function chain Seq.fill(n)(f)
See scaladoc for Function. Lazy version: Function chain Stream.fill(n)(f)
Although this is not as concise as jmcejuela's answer (which I prefer), there is another way in scala to express such a function without the Function module. It also works when n = 0.
def iterate[T](f: T=>T, n: Int) = (x: T) => (1 to n).foldLeft(x)((res, n) => f(res))
To overcome the creation of a list, one can use explicit recursion, which in reverse requires more static typing.
def iterate[T](f: T=>T, n: Int): T=>T = (x: T) => (if(n == 0) x else iterate(f, n-1)(f(x)))
There is an equivalent solution using pattern matching like the solution in Haskell:
def iterate[T](f: T=>T, n: Int): T=>T = (x: T) => n match {
case 0 => x
case _ => iterate(f, n-1)(f(x))
}
Finally, I prefer the short way of writing it in Caml, where there is no need to define the types of the variables at all.
let iterate f n x = match n with 0->x | n->iterate f (n-1) x;;
let f5 = iterate f 5 in ...
I like pigworker's/tauli's ideas the best, but since they only gave it as a comments, I'm making a CW answer out of it.
\n f x -> iterate f x !! n
or
\n f -> (!! n) . iterate f
perhaps even:
\n -> ((!! n) .) . iterate

Limitations of Fixpoint in Coq?

I am fooling around with Coq. Specifically, I am trying to implement mergesort and then prove that it works.
My attempt at an implementation was:
Fixpoint sort ls :=
match ls with
| nil => nil
| cons x nil => cons x nil
| xs =>
let (left, right) := split xs nil nil
in merge (sort left) (sort right)
end.
The errors that I get as a result of this are:
Error:
Recursive definition of sort is ill-formed.
In environment
sort : list nat -> list nat
ls : list nat
x : nat
l : list nat
y : nat
l0 : list nat
left : list nat
right : list nat
Recursive call to sort has principal argument equal to "left" instead of
one of the following variables: "l" "l0".
Recursive definition is:
"fun ls : list nat =>
match ls with
| nil => nil
| x :: nil => x :: nil
| x :: _ :: _ =>
let (left, right) := split ls nil nil in merge (sort left) (sort right)
end".
My interpretation of these errors is that l and l0 are ls without its head, x, and ls without x and the element after x (which I guess it decided to call y?). It is mad that I did not recurse on one of these lists and instead recursed on a locally defined list.
Am I only allowed to recurse on things that come directly from the pattern match? If yes, this seems like a severe limitation. Are there ways around it? I am guessing that Coq can't tell that the function will terminate. Is there some way to prove to it that left and right are smaller than xs?
It turns out that the chapter of CPDT on General Recursion addresses just that particular issue:
http://adam.chlipala.net/cpdt/html/GeneralRec.html
Read the section called Well-founded recursion, it implements the merge sort using well-founded recursion to help Coq's termination checker be happy.
There may be other ways to solve that problem using either Function or Program Fixpoint, but I think reading about well-founded recursion will not hurt.