How can i cast nat to int in Isabelle - isabelle

While doing my homework I got stuck in the following question:
Create the function add. It returns the sum of two natural numbers.
Prove that it works.
I'm stuck because to write the code to prove it, I need to cast a natural number (nat in Isabelle) to int.
Here's the add function that I wrote:
primrec add :: "nat ⇒ nat ⇒ nat"
where
add01: "add x 0 = x" |
add02: "add x (Suc y) = Suc (add x y) "
To know the result I did this:
value "somaNat (Suc(Suc(0))) (Suc(0))"
It returns 3, as it should.
Suc(Suc(0) = 2
Suc(0) = 1
Also tried to create a function that cast it to int, like this:
primrec nat_to_int :: "nat ⇒ int"
where
nat_to_int02: "nat_to_int x = value x"
It does not work because (value x) can't be on the right side.
I searched for it in the tutorial that Isabelle provides, and in another one, that I found online.
The closest question I found on SO was this one:
Casting int to nat in Isabelle
So, how can I cast nat to int in Isabelle?

Related

Locale: Codegen fails when instantiating with unit (code_pred: "Tactic failed")

I am trying to use code_pred for an inductive predicate defined inside a locale. I came across this email which shows how this can be done:
locale l = fixes x :: 'a assumes "x = x"
inductive (in l) is_x where "is_x x"
global_interpretation i: l "0 :: nat" defines i_is_x = "i.is_x" by unfold_locales simp
declare i.is_x.intros[code_pred_intro]
code_pred i_is_x by(rule i.is_x.cases)
However, when I change the global_interpretation to use () :: unit instead of 0 :: nat, then code_pred fails with the following message:
Tactic failed
The error(s) above occurred for the goal statement⌂:
i_is_x_i x = Predicate.bind (Predicate.single x) (λx. case x of () ⇒ Predicate.single ())
I tried to do the prove manually, but at some point I got the same error.
Does anyone know how to solve this?
I don't exactly understand what is happening here, but the code generator already uses unit internally and the tactic (corresponding to before single intro rule) fails on your example.
The error does not come from the proof, but comes from proof done internally in the done part. So changing the proof does not change the issue (and you even see with sorry).
A possible work-around: use a type isomorphic to unit:
datatype myunit = MyUnit
locale l = fixes x :: 'a assumes "x = x"
inductive (in l) is_x where "is_x x"
definition X where ‹X = ()›
global_interpretation i: l "MyUnit :: myunit" defines i_is_x = "i.is_x" by unfold_locales simp
declare i.is_x.intros[code_pred_intro]
code_pred i_is_x
by (rule i.is_x.cases)

Defining functions between constants in Isabelle

I'm a mathematician just starting to get used to Isabelle, and something that should be incredibly simple turned out to be frustrating. How do I define a function between two constants? Say, the function f: {1,2,3} \to {1,2,4} mapping 1 to 1, 2 to 4 and 3 to 2?
I suppose I managed to define the sets as constants t1 and t2 without incident, but (I guess since they're not datatypes) I can't try something like
definition f ::"t1 => t2" where
"f 1 = 1" |
"f 2 = 4" |
"f 3 = 2"
I believe there must be a fundamental misconception behind this difficulty, so I appreciate any guidance.
There's a number of aspects to your question.
First, to get something working quickly, use the fun keyword instead of definition, like so:
fun test :: "nat ⇒ nat" where
"test (Suc 0) = 1" |
"test (Suc (Suc 0)) = 4" |
"test (Suc (Suc (Suc 0))) = 2" |
"test _ = undefined"
You cannot pattern match on any arguments directly in the head of the definition using the definition keyword, whereas you can with fun. Note also that I have replaced the overloaded numeric literals (1, 2, 3, etc.) with the constructors for the nat datatype (0 and Suc) in the pattern match.
An alternative would be to stick with definition, but push the case analysis of the function's argument inside the body of the definition using a case statement, like so:
definition test2 :: "nat ⇒ nat" where
"test2 x ≡
case x of
(Suc 0) ⇒ 1
| (Suc (Suc 0)) ⇒ 4
| (Suc (Suc (Suc 0))) ⇒ 2
| _ ⇒ undefined"
Note that definitions like test2 are not unfolded by the simplifier by default, and you will need to manually add the theorem test2_def to the simplifier's simpset if you want to expand occurrences of test2 in a proof.
You can also define new types (you cannot use sets as types, directly, as you are trying to do) corresponding to your two three-element sets with typedef, but personally I would stick with nat.
EDIT: to use typedef, do something like:
typedef t1 = "{x::nat. x = 1 ∨ x = 2 ∨ x = 3}"
by auto
definition test :: "t1 ⇒ t1" where
"test x ≡
case (Rep_t1 x) of
| Suc 0 ⇒ Abs_t1 1
| Suc (Suc 0) ⇒ Abs_t1 4
| Suc (Suc (Suc 0)) ⇒ Abs_t1 2"
Though, I don't really ever use typedef myself, and so this may not be the best way of using this and others may possibly suggest some other way. What typedef does is carve out a new type from an existing one, by identifying a non-empty set of inhabitants for the new type. The proof obligation, here closed by auto, is merely to demonstrate that the defining set for the new type is indeed non-empty, and in this case I am carving out a three-element set of naturals into a new type, called t1, so the proof is fairly trivial. Two new constants are created, Abs_t1 and Rep_t1 which allow you to move back-and-forth between the naturals and the new type. If you put a print_theorems after the typedef command you will see several new theorems about t1 that Isabelle has automatically generated for you.

Isabelle unification error

I am new to Isabelle and this is a simplification of my first program
theory Scratch
imports Main
begin
record flow =
Src :: "nat"
Dest :: "nat"
record diagram =
DataFlows :: "flow set"
Transitions :: "nat set"
Markings :: "flow set"
fun consume :: "diagram × (nat set) ⇒ (flow set)"
where
"(consume dia trans) = {n . n ∈ (Markings dia) ∧ (∃ t ∈ trans . (Dest n) = t)}"
end
The function give the error:
Type unification failed: Clash of types "_ ⇒ " and " set"
Type error in application: operator not of function type
Operator: consume dia :: flow set
Operand: trans :: (??'a × ??'a) set ⇒ bool
What should I do for the the code to compile?
First of all, you give two parameters to your consume function, but the way you defined its type, it takes a single tuple. This is unusual and often inconvenient – defined curried functions instead, like this:
fun consume :: "diagram ⇒ (nat set) ⇒ (flow set)"
Also, trans is a constant; it is the property that a relation is transitive. You can see that by observing that trans is black to indicate that it is a constant and the other variable is blue, indicating that it is a free variable.
I therefore recommend using another name, like ts:
where
"consume dia ts = {n . n ∈ (Markings dia) ∧ (∃ t ∈ ts . (Dest n) = t)}"

How to generate code for reverse sorting

What is the easiest way to generate code for a sorting algorithm that sorts its argument in reverse order, while building on top of the existing List.sort?
I came up with two solutions that are shown below in my answer. But both of them are not really satisfactory.
Any other ideas how this could be done?
I came up with two possible solutions. But both have (severe) drawbacks. (I would have liked to obtain the result almost automatically.)
Introduce a Haskell-style newtype. E.g., if we wanted to sort lists of nats, something like
datatype 'a new = New (old : 'a)
instantiation new :: (linorder) linorder
begin
definition "less_eq_new x y ⟷ old x ≥ old y"
definition "less_new x y ⟷ old x > old y"
instance by (default, case_tac [!] x) (auto simp: less_eq_new_def less_new_def)
end
At this point
value [code] "sort_key New [0::nat, 1, 0, 0, 1, 2]"
yields the desired reverse sorting. While this is comparatively easy, it is not as automatic as I would like the solution to be and in addition has a small runtime overhead (since Isabelle doesn't have Haskell's newtype).
Via a locale for the dual of a linear order. First we more or less copy the existing code for insertion sort (but instead of relying on a type class, we make the parameter that represents the comparison explicit).
fun insort_by_key :: "('b ⇒ 'b ⇒ bool) ⇒ ('a ⇒ 'b) ⇒ 'a ⇒ 'a list ⇒ 'a list"
where
"insort_by_key P f x [] = [x]"
| "insort_by_key P f x (y # ys) =
(if P (f x) (f y) then x # y # ys else y # insort_by_key P f x ys)"
definition "revsort_key f xs = foldr (insort_by_key (op ≥) f) xs []"
at this point we have code for revsort_key.
value [code] "revsort_key id [0::nat, 1, 0, 0, 1, 2]"
but we also want all the nice results that have already been proved in the linorder locale (that derives from the linorder class). To this end, we introduce the dual of a linear order and use a "mixin" (not sure if I'm using the correct naming here) to replace all occurrences of linorder.sort_key (which does not allow for code generation) by our new "code constant" revsort_key.
interpretation dual_linorder!: linorder "op ≥ :: 'a::linorder ⇒ 'a ⇒ bool" "op >"
where
"linorder.sort_key (op ≥ :: 'a ⇒ 'a ⇒ bool) f xs = revsort_key f xs"
proof -
show "class.linorder (op ≥ :: 'a ⇒ 'a ⇒ bool) (op >)" by (rule dual_linorder)
then interpret rev_order: linorder "op ≥ :: 'a ⇒ 'a ⇒ bool" "op >" .
have "rev_order.insort_key f = insort_by_key (op ≥) f"
by (intro ext) (induct_tac xa; simp)
then show "rev_order.sort_key f xs = revsort_key f xs"
by (simp add: rev_order.sort_key_def revsort_key_def)
qed
While with this solution we do not have any runtime penalty, it is far too verbose for my taste and is not easily adaptable to changes in the standard code setup (e.g., if we wanted to use the mergesort implementation from the Archive of Formal Proofs for all of our sorting operations).

"String of nat" in Isabelle?

I'm struggling to find a function of type nat => string that converts terms like
42
into terms like
''42''
Does it exist? I've found char_of_nat (in the String library) but that's a bit too low-level, being concerned with ASCII codes and the like.
In the archive of formal proofs, under Real_Impl/Show you find a class show with a function essentially of type 'a => string. In Real_Impl/Show_Instances several common types are instantiated, including nat, rat, and int.
In the meantime, I've gone ahead and written my own string_of_nat and string_of_int functions. In the absence of other pre-existing functions, these will suit me fine.
fun string_of_nat :: "nat ⇒ string"
where
"string_of_nat n = (if n < 10 then [char_of_nat (48 + n)] else
string_of_nat (n div 10) # [char_of_nat (48 + (n mod 10))])"
definition string_of_int :: "int ⇒ string"
where
"string_of_int i = (if i < 0 then ''-'' # string_of_nat (nat (- i)) else
string_of_nat (nat i))"
There's a Haskell-like show class in the AFP entry Show.
The instance for the nat type is in Show.Show_Instances.
Example:
theory Show_Test
imports "Show.Show_Instances"
begin
lemma "show (123 :: nat) = ''123''"
by (simp add: Show_Instances.shows_prec_nat_def showsp_nat.simps shows_string_def)
end

Resources