Datasets:
AI4M
/

text
stringlengths
0
3.34M
[STATEMENT] lemma supp_set_elem_finite: assumes "finite S" and "(m::'a::fs) \<in> S" and "y \<in> supp m" shows "y \<in> supp S" [PROOF STATE] proof (prove) goal (1 subgoal): 1. y \<in> supp S [PROOF STEP] using assms supp_of_finite_sets [PROOF STATE] proof (prove) using this: finite S m \<in> S y \<in> supp m finite ?S \<Longrightarrow> supp ?S = \<Union> (supp ` ?S) goal (1 subgoal): 1. y \<in> supp S [PROOF STEP] by auto
theory Chap3_3 imports Main Chap3_1 Chap3_2 begin datatype instr = LOADI val | LOAD vname | ADD type_synonym stack = "val list" fun exec1 :: "instr \<Rightarrow> state \<Rightarrow> stack \<Rightarrow> stack" where "exec1 (LOADI n) _ stk = n#stk" | "exec1 (LOAD x) s stk = (s x)#stk" | "exec1 ADD s (x#y#stk) = (y+x)#stk" fun exec :: "instr list \<Rightarrow> state \<Rightarrow> stack \<Rightarrow> stack" where "exec [] _ stk = stk" | "exec (i#is) s stk = exec is s (exec1 i s stk)" definition exec' :: "instr list \<Rightarrow> state \<Rightarrow> stack \<Rightarrow> stack" where "exec' is s stk = fold (\<lambda>i stk'. exec1 i s stk') is stk" definition exec'' :: "instr list \<Rightarrow> state \<Rightarrow> stack \<Rightarrow> stack" where "exec'' is s stk = foldr (\<lambda>i stk'. exec1 i s stk') is stk" lemma "exec is s stk = exec' is s stk" apply (induction "is" arbitrary: stk) unfolding exec'_def by simp+ lemma "exec is s stk = exec'' is s stk" oops fun comp :: "aexp \<Rightarrow> instr list" where "comp (N n) = [LOADI n]" | "comp (V x) = [LOAD x]" | "comp (Plus e1 e2) = comp e1 @ comp e2 @ [ADD]" lemma exec_concat: "exec (is1 @ is2) s stk = exec is2 s (exec is1 s stk)" apply (induction is1 arbitrary: stk) by simp+ lemma "exec (comp a) s stk = aval a s # stk" apply (induction a arbitrary: stk) apply simp+ using exec_concat by simp end
From Hammer Require Import Hammer. Require Import Decidable PeanoNat. Require Eqdep_dec. Local Open Scope nat_scope. Implicit Types m n x y : nat. Theorem O_or_S n : {m : nat | S m = n} + {0 = n}. Proof. hammer_hook "Peano_dec" "Peano_dec.O_or_S". induction n. - now right. - left; exists n; auto. Defined. Notation eq_nat_dec := Nat.eq_dec (compat "8.4"). Hint Resolve O_or_S eq_nat_dec: arith. Theorem dec_eq_nat n m : decidable (n = m). Proof. hammer_hook "Peano_dec" "Peano_dec.dec_eq_nat". elim (Nat.eq_dec n m); [left|right]; trivial. Defined. Definition UIP_nat:= Eqdep_dec.UIP_dec Nat.eq_dec. Import EqNotations. Lemma le_unique: forall m n (le_mn1 le_mn2 : m <= n), le_mn1 = le_mn2. Proof. hammer_hook "Peano_dec" "Peano_dec.le_unique". intros m n. generalize (eq_refl (S n)). generalize n at -1. induction (S n) as [|n0 IHn0]; try discriminate. clear n; intros n [= <-] le_mn1 le_mn2. pose (def_n2 := eq_refl n0); transitivity (eq_ind _ _ le_mn2 _ def_n2). 2: reflexivity. generalize def_n2; revert le_mn1 le_mn2. generalize n0 at 1 4 5 7; intros n1 le_mn1. destruct le_mn1; intros le_mn2; destruct le_mn2. + now intros def_n0; rewrite (UIP_nat _ _ def_n0 eq_refl). + intros def_n0; generalize le_mn2; rewrite <-def_n0; intros le_mn0. now destruct (Nat.nle_succ_diag_l _ le_mn0). + intros def_n0; generalize le_mn1; rewrite def_n0; intros le_mn0. now destruct (Nat.nle_succ_diag_l _ le_mn0). + intros def_n0. injection def_n0 as ->. rewrite (UIP_nat _ _ def_n0 eq_refl); simpl. assert (H : le_mn1 = le_mn2). now apply IHn0. now rewrite H. Qed. Require Import Le Lt.
[STATEMENT] lemma n_zero_L_zero: "n(bot) * L = bot" [PROOF STATE] proof (prove) goal (1 subgoal): 1. n bot * L = bot [PROOF STEP] by (simp add: le_bot n_L_decreasing)
[STATEMENT] lemma zle:"((z::int) \<le> w) = (\<not> (w < z))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (z \<le> w) = (\<not> w < z) [PROOF STEP] by auto
theory T84 imports Main begin lemma "( (\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) & (\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(meet(x, y), z) = meet(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(join(x, y), z) = join(over(x, z), over(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(meet(x, y), z) = join(undr(x, z), undr(y, z))) & (\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) & (\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) & (\<forall> x::nat. invo(invo(x)) = x) ) \<longrightarrow> (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(x, join(y, z)) = join(undr(x, y), undr(x, z))) " nitpick[card nat=4,timeout=86400] oops end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % QPSK demonstration packet-based transceiver for Chilipepper % Toyon Research Corp. % http://www.toyon.com/chilipepper.php % Created 10/17/2012 % [email protected] %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % This file is the top level entry function for the receiver portion of the % example. The entire receiver is designed to run at Rate=1 (one clock % cycle per iteration of the core. % We follow standard receive practice with frequency offset estimation, % pulse-shape filtering, time estimateion, and correlation to determine % tart of packet. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %#codegen function [r_out, s_f_out, s_c_out, s_t_out, t_est_out, f_est_out] = ... qpsk_rx(i_in, q_in, mu_foc_in, mu_toc_in) % scale input data coming from the Chilipepper ADC to be purely % fractional to avoid scaling issues r_in = complex(i_in, q_in); % frequency offset estimation. Note that time constant is input as % integer [s_f_i, s_f_q, fe] = qpsk_rx_foc(i_in, q_in, mu_foc_in); % Square-root raised-cosine band-limited filtering [s_c_i, s_c_q] = qpsk_rx_srrc(s_f_i, s_f_q); % Time offset estimation. Output data changes at the symbol rate. [s_t_i, s_t_q, tauh] = qpsk_rx_toc(s_c_i, s_c_q, mu_toc_in); % estimation and correlation values t_est_out = tauh; f_est_out = fe; % original signal out (real version) r_out = real(r_in); % incremental signal outputs after frequency estimation, filtering, and % timining estimation s_f_out = complex(s_f_i,s_f_q); s_c_out = complex(s_c_i,s_c_q); s_t_out = complex(s_t_i,s_t_q); end
{-# OPTIONS --without-K #-} module Ch2-3 where open import Level hiding (lift) open import Ch2-1 open import Ch2-2 -- p -- x ~~~~~~~~~ y -- -- -- P x --------> P y -- -- Lemma 2.3.1 (transport) transport : ∀ {a b} {A : Set a} {x y : A} → (P : A → Set b) → (p : x ≡ y) → P x → P y transport {a} {b} {A} {x} {y} P p = J A D d x y p P -- J A D d x y p P where -- the predicate D : (x y : A) (p : x ≡ y) → Set (a ⊔ suc b) D x y p = (P : A → Set b) → P x → P y -- base case d : (x : A) → D x x refl d x P y = y open import Data.Product -- proof -- +-----+ p +-----+ -- | x ~~~~~~~~~~~~~~~~ y | -- | | | | -- | P x |~~~~~~~~~~~~| P y | -- +-----+ * +-----+ -- -- Lemma 2.3.2 (path lifting property) lift : ∀ {a b} {A : Set a} → (P : A → Set b) → (proof : Σ[ x ∈ A ] P x) → (y : A) → (p : proj₁ proof ≡ y) → proof ≡ (y , transport P p (proj₂ proof)) lift {a} {b} {A} P proof y p = J A D d (proj₁ proof) y p (proj₂ proof) where -- the predicate D : (x y : A) (p : x ≡ y) → Set (a ⊔ b) D x y p = (u : P x) → (x , u) ≡ (y , transport P p u) -- base case d : (x : A) → D x x refl d x u = refl -- A -- +----------------------------------------------+ -- | p | -- | x ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ y | -- | + + | -- +----------------------------------------------+ -- | | -- P x | P y | -- +-------+ +----------------------------------+ -- | v | | * v | -- | f x +-------> transport P p (f x) ~~~~~ f y | -- | | | | -- +-------+ +----------------------------------+ -- -- Lemma 2.3.4 (dependent map) apd : ∀ {a b} {A : Set a} {x y : A} → {P : A → Set b} → (f : (z : A) → P z) → (p : x ≡ y) → transport P p (f x) ≡ f y apd {a} {b} {A} {x} {y} {P} f p = J A D d x y p P f where -- the predicate D : (x y : A) (p : x ≡ y) → _ D x y p = (P : A → Set b) (f : (z : A) → P z) → transport P p (f x) ≡ f y -- base case d : (x : A) → D x x refl d x P f = refl open import Function using (const; _∘_) -- Lemma 2.3.5 transportconst : ∀ {a ℓ} {A : Set a} {x y : A} → {B : Set ℓ} → (p : x ≡ y) → (b : B) → transport (const B) p b ≡ b transportconst {a} {ℓ} {A} {x} {y} {B} p b = J A D d x y p B b where -- the predicate D : (x y : A) (p : x ≡ y) → _ D x y p = (B : Set ℓ) (b : B) → transport (const B) p b ≡ b -- base case d : (x : A) → D x x refl d x B b = refl open import Ch2-2 -- Lemma 2.3.8 lemma-2-3-8 : ∀ {a ℓ} {A : Set a} {B : Set ℓ} {x y : A} → (f : A → B) → (p : x ≡ y) → apd f p ≡ transportconst p (f x) ∙ ap f p lemma-2-3-8 {a} {ℓ} {A} {B} {x} {y} f p = J {a} {a ⊔ ℓ} A D d x y p f where -- the predicate D : (x y : A) (p : x ≡ y) → _ D x y p = (f : A → B) → apd f p ≡ transportconst p (f x) ∙ ap f p -- base case d : (x : A) → D x x refl d x f = refl -- Lemma 2.3.9 lemma-2-3-9 : ∀ {a b} {A : Set a} {x y z : A} → (P : A → Set b) → (p : x ≡ y) → (q : y ≡ z) → (u : P x) → transport P q (transport P p u) ≡ transport P (p ∙ q) u lemma-2-3-9 {a} {b} {A} {x} {y} {z} P p q u = J A D d x y p P z q u where -- the predicate D : (x y : A) (p : x ≡ y) → Set _ D x y p = (P : A → Set b) (z : A) (q : y ≡ z) (u : P x) → transport P q (transport P p u) ≡ transport P (p ∙ q) u -- base case d : (x : A) → D x x refl d x P z q u = J A E e x z q P u where -- the predicate E : (x z : A) (q : x ≡ z) → Set _ E x z q = (P : A → Set b) (u : P x) → transport P q (transport P refl u) ≡ transport P (refl ∙ q) u -- base case e : (x : A) → E x x refl e x P u = refl -- Lemma 2.3.10 lemma-2-3-10 : ∀ {a b c} {A : Set a} {B : Set b} {x y : A} → (P : B → Set c) → (f : A → B) → (p : x ≡ y) → (u : P (f x)) → transport (P ∘ f) p u ≡ transport P (ap f p) u lemma-2-3-10 {a} {b} {c} {A} {B} {x} {y} P f p u = J A D d x y p P f u where -- the predicate D : (x y : A) (p : x ≡ y) → Set _ D x y p = (P : B → Set c) (f : A → B) (u : P (f x)) → transport (P ∘ f) p u ≡ transport P (ap f p) u -- base case d : (x : A) → D x x refl d x P f u = refl -- Lemma 2.3.11 lemma-2-3-11 : {a b c : Level} {A : Set a} {x y : A} → (P : A → Set b) (Q : A → Set c) → (f : (z : A) → P z → Q z) → (p : x ≡ y) → (u : P x) → transport Q p (f x u) ≡ f y (transport P p u) lemma-2-3-11 {a} {b} {c} {A} {x} {y} P Q f p u = J A D d x y p P Q f u -- J A D d x y p {! !} {! !} {! !} {! !} where -- the predicate D : (x y : A) (p : x ≡ y) → Set _ D x y p = (P : A → Set b) (Q : A → Set c) (f : (z : A) → P z → Q z) (u : P x) → transport Q p (f x u) ≡ f y (transport P p u) -- base case d : (x : A) → D x x refl d x P Q f u = refl
-- @@stderr -- dtrace: invalid probe specifier 4.56: probe identifier 4 not permitted when specifying functions
[STATEMENT] lemma poly_sum_list: "poly (sum_list ps) x = sum_list (map (\<lambda> p. poly p x) ps)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. poly (sum_list ps) x = (\<Sum>p\<leftarrow>ps. poly p x) [PROOF STEP] by (induct ps, auto)
module Coproduct import Basic import Unit import Void %default total infixl 5 + namespace Coproduct public export data (+) : Type -> Type -> Type where Inl : a -> a + b Inr : b -> a + b public export SumInduction : (p : a + b -> Type) -> ((x : a) -> p (Inl x)) -> ((y : b) -> p (Inr y)) -> (z : a + b) -> p z SumInduction p f g (Inl x) = f x SumInduction p f g (Inr y) = g y public export SumRecursion : (p : Type) -> ((x : a) -> p) -> ((y : b) -> p) -> (z : a + b) -> p SumRecursion p = SumInduction (const p) public export Two : Type Two = Unit + Unit public export TwoInduction : (p : Two -> Type) -> p (Inl ()) -> p (Inr ()) -> (two : Two) -> p two TwoInduction p pl pr = SumInduction p (UnitInduction (p `compose` Inl) pl) (UnitInduction (p `compose` Inr) pr)
Formal statement is: lemma islimpt_Un_finite: fixes x :: "'a::t1_space" shows "finite s \<Longrightarrow> x islimpt (s \<union> t) \<longleftrightarrow> x islimpt t" Informal statement is: If $x$ is a limit point of $s \cup t$ and $s$ is finite, then $x$ is a limit point of $t$.
The complex conjugate function is continuous.
theory T151 imports Main begin lemma "( (\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) & (\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, meet(y, z)) = meet(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(meet(x, y), z) = meet(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(join(x, y), z) = join(over(x, z), over(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(meet(x, y), z) = join(undr(x, z), undr(y, z))) & (\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) & (\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) & (\<forall> x::nat. invo(invo(x)) = x) ) \<longrightarrow> (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(x, meet(y, z)) = join(over(x, y), over(x, z))) " nitpick[card nat=7,timeout=86400] oops end
(* Copyright (C) 2020 Susi Lehtola This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. *) (* type: gga_exc *) (* prefix: gga_k_pg_params *params; assert(p->params != NULL); params = (gga_k_pg_params * )(p->params); *) pg_f0 := s -> 5/3*s^2 + exp(-params_a_pg_mu * s^2): pg_f := x -> pg_f0(X2S*x): f := (rs, z, xt, xs0, xs1) -> gga_kinetic(pg_f, rs, z, xs0, xs1):
module Control.Effect.Labelled import Control.EffectAlgebra ||| Wrap an effect in a label. ||| This can help disambiguate between multiple identical effects and ||| lessen the number of type annotations. public export data Labelled : (label : k) -> (sub : (Type -> Type) -> (Type -> Type)) -> (m : Type -> Type) -> (Type -> Type) where MkLabelled : (eff : sub m a) -> Labelled label sub m a public export runLabelled : Labelled label sub m a -> sub m a runLabelled (MkLabelled eff) = eff public export Functor (sub m) => Functor (Labelled label sub m) where map f (MkLabelled x) = MkLabelled (map f x) public export Applicative (sub m) => Applicative (Labelled label sub m) where pure x = MkLabelled (pure x) (MkLabelled f) <*> (MkLabelled x) = MkLabelled (f <*> x) public export Monad (sub m) => Monad (Labelled label sub m) where (MkLabelled x) >>= f = MkLabelled (x >>= runLabelled . f) public export Algebra (eff :+: sig) (sub m) => Algebra (Labelled label eff :+: sig) (Labelled label sub m) where alg ctxx hdl (Inl (MkLabelled x)) = MkLabelled $ alg {sig = eff :+: sig, m = sub m} ctxx (runLabelled . hdl) (Inl x) alg ctxx hdl (Inr x) = MkLabelled $ alg {sig = eff :+: sig, m = sub m} ctxx (runLabelled . hdl) (Inr x) ||| Higher-order injections where signatures are inferred from the label. public export interface InjL (0 label : k) (0 sub : (Type -> Type) -> (Type -> Type)) (0 sup : (Type -> Type) -> (Type -> Type)) | label where constructor MkSubL injLabelled : Labelled label sub m a -> sup m a public export [LabelAuto] Inj sub sup => InjL label sub sup where injLabelled (MkLabelled x) = inj x public export Label : Inj sub sup -> InjL label sub sup Label x = LabelAuto @{x} public export labelled : (label : k) -> InjL label sub sig => Algebra sig m => sub m a -> m a labelled label @{sub} x = let y = injLabelled (MkLabelled {label} x) in alg {ctx = id} () id y
#' Find the distance between locations specified by latitude/longitude in degrees. #' #' @param locs a matrix of locations, each row specifying two locations to find the distance between. The first two columns are the "from" longitude and latitude, respectively; the third and fourth columns are the "from" longitude and latitude, respectively. #' @param dist logical: return the distances as a \code{\link{dist}} object (distance matrix)? #' #' @return either a matrix or a distance matrix containing the distances between all the points. earth.dist = function (locs, dist=TRUE) { if (class(locs) == "SpatialPoints") locs <- coordinates(locs) name <- list(rownames(locs), rownames(locs)) n <- nrow(locs) z <- matrix(0, n, n, dimnames = name) z <- outer(1:n, 1:n, function(i, j) deg.dist(long1=locs[i,1], lat1=locs[i, 2], long2=locs[j, 1], lat2=locs[j,2])) if (dist == TRUE) z <- as.dist(z) return(z) }
/- Copyright (c) 2023 Tian Chen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tian Chen -/ import data.matrix.pequiv noncomputable theory open_locale big_operators matrix namespace matrix variables {n m α : Type*} [fintype n] [fintype m] section variables [has_zero α] /-- A matrix as a finitely supported function -/ def finsupp (M : matrix n m α) : (n × m) →₀ α := finsupp.of_support_finite (function.uncurry M) (set.to_finite _) lemma finsupp_apply {M : matrix n m α} (i j) : M.finsupp (i, j) = M i j := rfl end lemma curry_finsupp_apply [add_comm_monoid α] (M : matrix n m α) (i j) : M.finsupp.curry i j = M i j := by rw [finsupp.curry_apply, finsupp_apply] lemma mem_support_curry_finsupp [add_comm_monoid α] (M : matrix n m α) (i j) : j ∈ (M.finsupp.curry i).support ↔ M i j ≠ 0 := by rw [finsupp.mem_support_iff, curry_finsupp_apply] lemma finsupp_smul [add_monoid α] {R : Type*} [smul_zero_class R α] (M : matrix n m α) (x : R) : (x • M).finsupp = x • M.finsupp := by ext ⟨i, j⟩; refl namespace finsupp variables [add_comm_monoid α] {M : matrix n m α} lemma transpose : M.finsupp.map_domain prod.swap = Mᵀ.finsupp := begin ext ⟨j, i⟩, exact finsupp.map_domain_apply prod.swap_injective _ (i, j) end lemma transpose' : M.finsupp.equiv_map_domain (equiv.prod_comm n m) = Mᵀ.finsupp := begin ext ⟨j, i⟩, exact finsupp.equiv_map_domain_apply _ _ (j, i) end end finsupp /-- The non-zero entries of `M` defined as the support of `M.finsupp`. -/ def support [has_zero α] (M : matrix n m α) : finset (n × m) := M.finsupp.support section support variable {M : matrix n m α} section variables [has_zero α] lemma mem_support_iff' (a : n × m) : a ∈ M.support ↔ M a.1 a.2 ≠ 0 := finsupp.mem_support_iff lemma mem_support_iff (i j) : (i, j) ∈ M.support ↔ M i j ≠ 0 := finsupp.mem_support_iff lemma not_mem_support_iff (i j) : (i, j) ∉ M.support ↔ M i j = 0 := finsupp.not_mem_support_iff lemma mem_support_transpose (i j) : (i, j) ∈ Mᵀ.support ↔ M j i ≠ 0 := mem_support_iff _ _ lemma support_transpose' : M.support.map (equiv.prod_comm n m).to_embedding = Mᵀ.support := begin ext ⟨i, j⟩, rw [finset.mem_map_equiv, equiv.prod_comm_symm, equiv.prod_comm_apply, prod.swap_prod_mk, mem_support_iff, mem_support_iff], refl end lemma card_support_transpose : Mᵀ.support.card = M.support.card := by rw [← support_transpose', finset.card_map] lemma support_transpose [decidable_eq n] [decidable_eq m] : M.support.image prod.swap = Mᵀ.support := begin rw [← support_transpose', finset.map_eq_image], refl end end variables [add_comm_monoid α] lemma support_smul_eq {R : Type*} [semiring R] [module R α] [no_zero_smul_divisors R α] {x : R} (hx : x ≠ 0) : (x • M).support = M.support := by rw [support, finsupp_smul]; exact finsupp.support_smul_eq hx lemma finsupp_eq_sum_row : M.finsupp = ∑ i, (M.finsupp.curry i).map_domain (prod.mk i) := begin classical, ext ⟨i, j⟩, have : ∑ i' in {i}ᶜ, (M.finsupp.curry i').map_domain (prod.mk i') (i, j) = 0, { apply finset.sum_eq_zero, intros _ hi', apply finsupp.map_domain_notin_range, rintro ⟨_, h⟩, rw [finset.mem_compl, finset.not_mem_singleton] at hi', exact hi' (prod.mk.inj h).1 }, rw [finsupp.coe_finset_sum, finset.sum_apply, fintype.sum_eq_add_sum_compl i, finsupp.map_domain_apply (prod.mk.inj_left i), finsupp.curry_apply, this, add_zero] end lemma support_card_eq_sum_row : M.support.card = ∑ i, (M.finsupp.curry i).support.card := begin classical, conv_lhs { rw [support, finsupp_eq_sum_row] }, have : ∀ i₁ i₂, i₁ ≠ i₂ → disjoint ((M.finsupp.curry i₁).map_domain (prod.mk i₁)).support ((M.finsupp.curry i₂).map_domain (prod.mk i₂)).support, { intros x y h, rw finset.disjoint_iff_ne, rintros ⟨i₁, j₁⟩ h₁ ⟨i₂, j₂⟩ h₂ h', rw [finsupp.map_domain_support_of_injective (prod.mk.inj_left _)] at h₁ h₂, all_goals { try { apply_instance } }, rw [finset.mem_image] at h₁ h₂, rcases h₁ with ⟨a, _, ha⟩, rcases h₂ with ⟨b, _, hb⟩, rw [← ha, ← hb] at h', exact h (prod.mk.inj h').1 }, rw [finsupp.support_sum_eq_bUnion _ this, finset.card_bUnion], apply finset.sum_congr rfl, intros i _, have h := prod.mk.inj_left i, rw [finsupp.map_domain_support_of_injective h, finset.card_image_of_injective _ h], { intros, apply this, assumption } end variables [has_one α] [ne_zero (1 : α)] [decidable_eq m] [decidable_eq n] lemma _root_.equiv.card_support_to_matrix (σ : m ≃ n) : (σ.to_pequiv.to_matrix : matrix m n α).support.card = fintype.card m := begin suffices h : σ.to_pequiv.to_matrix.support = finset.univ.image (λ i, (i, σ i)), { rw [h, finset.card_image_of_injective, fintype.card], intros _ _ hp, exact (prod.mk.inj hp).1 }, ext ⟨i, j⟩, rw [mem_support_iff, pequiv.to_matrix, equiv.to_pequiv_apply, finset.mem_image], simp_rw [option.mem_some_iff], rw [ne.ite_ne_right_iff (one_ne_zero' α)], simp_rw [prod.mk.inj_iff, finset.mem_univ, exists_true_left, exists_eq_left] end lemma _root_.equiv.card_support_to_matrix' [has_one α] [ne_zero (1 : α)] [decidable_eq n] (σ : m ≃ n) : (σ.to_pequiv.to_matrix : matrix m n α).support.card = fintype.card n := fintype.card_congr σ ▸ equiv.card_support_to_matrix σ end support end matrix
[STATEMENT] lemma noFault_startn: assumes execn: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" and t: "t\<noteq>Fault f" shows "s\<noteq>Fault f" [PROOF STATE] proof (prove) goal (1 subgoal): 1. s \<noteq> Fault f [PROOF STEP] using execn t [PROOF STATE] proof (prove) using this: \<Gamma>\<turnstile> \<langle>c,s\<rangle> =n\<Rightarrow> t t \<noteq> Fault f goal (1 subgoal): 1. s \<noteq> Fault f [PROOF STEP] by (induct) auto
Formal statement is: lemma translation_assoc: fixes a b :: "'a::ab_group_add" shows "(\<lambda>x. b + x) ` ((\<lambda>x. a + x) ` S) = (\<lambda>x. (a + b) + x) ` S" Informal statement is: For any set $S$ and any elements $a$ and $b$ of an abelian group, the set of all elements of the form $b + (a + x)$ for $x \in S$ is equal to the set of all elements of the form $(a + b) + x$ for $x \in S$.
module Replica.Other.Validation %default total public export data Validation : (err, a : Type) -> Type where Valid : (x : a) -> Validation err a Error : (e : err) -> Validation err a export Functor (Validation err) where map f (Valid x) = Valid $ f x map f (Error x) = Error x export (Semigroup err) => Applicative (Validation err) where pure = Valid (Valid f) <*> (Valid x) = Valid $ f x (Valid _) <*> (Error e) = Error e (Error e) <*> (Valid x) = Error e (Error e1) <*> (Error e2) = Error $ e1 <+> e2 export (Monoid err) => Alternative (Validation err) where empty = Error neutral (<|>) (Valid x) y = Valid x (<|>) (Error e) (Valid y) = Valid y (<|>) (Error e) (Error r) = Error $ e <+> r export fromEither : Applicative f => Either err a -> Validation (f err) a fromEither = either (Error . pure) Valid
State Before: α : Type u_1 inst✝ : HeytingAlgebra α a b : α hb : IsRegular b ⊢ Disjoint a (bᶜ) ↔ a ≤ b State After: no goals Tactic: rw [← le_compl_iff_disjoint_right, hb.eq]
-- Andreas, 2015-12-05 issue reported by Conor -- {-# OPTIONS -v tc.cover.splittree:10 -v tc.cc:20 #-} module Issue1734 where infix 4 _≡_ data _≡_ {A : Set} (x : A) : A → Set where refl : x ≡ x record One : Set where constructor <> data Two : Set where tt ff : Two -- two : ∀{α}{A : Set α} → A → A → Two → A two : (S T : Set) → Two → Set two a b tt = a two a b ff = b record Sg (S : Set)(T : S -> Set) : Set where constructor _,_ field fst : S snd : T fst open Sg public _+_ : Set -> Set -> Set S + T = Sg Two (two S T) data Twoey : Two -> Set where ffey : Twoey ff ttey : Twoey tt postulate Thingy : Set ThingyIf : Two -> Set ThingyIf tt = Thingy ThingyIf ff = One thingy? : (b : Two) -> ThingyIf b -> Twoey b + One -> Thingy + One thingy? .ff <> (tt , ffey) = ff , <> thingy? .tt x (tt , ttey) = tt , x thingy? _ _ _ = ff , <> -- WORKS: thingy? _ _ (ff , _ ) = ff , <> {- Correct split tree split at 2 | `- Issue1734.Sg._,_ -> split at 2 | +- Issue1734.Two.tt -> split at 2 | | | +- Issue1734.Twoey.ffey -> split at 1 | | | | | `- Issue1734.One.<> -> done, 0 bindings | | | `- Issue1734.Twoey.ttey -> done, 1 bindings | `- Issue1734.Two.ff -> done, 3 bindings but clause compiler deviated from it: thingy? b x p = case p of (y , z) -> case y of tt -> case x of <> -> case z of ffey -> ff , <> ttey -> tt , <> _ -> case z of ttey -> tt , x _ -> ff , <> compiled clauses (still containing record splits) case 2 of Issue1734.Sg._,_ -> case 2 of Issue1734.Two.tt -> case 1 of Issue1734.One.<> -> case 1 of Issue1734.Twoey.ffey -> ff , <> Issue1734.Twoey.ttey -> tt , <> _ -> case 2 of Issue1734.Twoey.ttey -> tt , x _ -> ff , <> -} test1 : ∀ x → thingy? tt x (tt , ttey) ≡ tt , x test1 = λ x → refl -- should pass! first-eq-works : ∀ x → thingy? ff x (tt , ffey) ≡ ff , x first-eq-works = λ x → refl -- It's weird. I couldn't make it happen with Twoey b alone: I needed Twoey b + One. -- I also checked that reordering the arguments made it go away. This... thygni? : (b : Two) -> Twoey b + One -> ThingyIf b -> Thingy + One thygni? .ff (tt , ffey) <> = ff , <> thygni? .tt (tt , ttey) x = tt , x thygni? _ _ _ = ff , <> works : ∀ x → thygni? tt (tt , ttey) x ≡ tt , x works = λ x → refl -- Moreover, replacing the gratuitous <> pattern by a variable... hingy? : (b : Two) -> ThingyIf b -> Twoey b + One -> Thingy + One hingy? .ff x (tt , ffey) = ff , <> hingy? .tt x (tt , ttey) = tt , x hingy? _ _ _ = ff , <> -- ...gives... works2 : ∀ x → hingy? tt x (tt , ttey) ≡ tt , x works2 = λ x -> refl -- ...and it has to be a variable: an _ gives the same outcome as <>.
In the nights following the earthquake , many people in Haiti slept in the streets , on pavements , in their cars , or in makeshift shanty towns either because their houses had been destroyed , or they feared standing structures would not withstand aftershocks . Construction standards are low in Haiti ; the country has no building codes . Engineers have stated that it is unlikely many buildings would have stood through any kind of disaster . Structures are often raised wherever they can fit ; some buildings were built on slopes with insufficient foundations or steel supports . A representative of Catholic Relief Services has estimated that about two million Haitians lived as squatters on land they did not own . The country also suffered from shortages of fuel and potable water even before the disaster .
[STATEMENT] lemma plus_fun_conv: "a + b = a ++ b" [PROOF STATE] proof (prove) goal (1 subgoal): 1. a + b = a ++ b [PROOF STEP] by (auto simp: plus_fun_def map_add_def split: option.splits)
theory T59 imports Main begin lemma "( (\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) & (\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, meet(y, z)) = meet(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(join(x, y), z) = join(over(x, z), over(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(x, meet(y, z)) = join(over(x, y), over(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(meet(x, y), z) = join(undr(x, z), undr(y, z))) & (\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) & (\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) & (\<forall> x::nat. invo(invo(x)) = x) ) \<longrightarrow> (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(meet(x, y), z) = meet(mult(x, z), mult(y, z))) " nitpick[card nat=10,timeout=86400] oops end
------------------------------------------------------------------------ -- The Agda standard library -- -- Example of a Quotient: ℤ as (ℕ × ℕ / ∼) ------------------------------------------------------------------------ {-# OPTIONS --with-K --safe #-} module Relation.Binary.HeterogeneousEquality.Quotients.Examples where open import Relation.Binary.HeterogeneousEquality.Quotients open import Level using (0ℓ) open import Relation.Binary open import Relation.Binary.HeterogeneousEquality hiding (isEquivalence) import Relation.Binary.PropositionalEquality as ≡ open import Data.Nat open import Data.Nat.Properties open import Data.Product open import Function open ≅-Reasoning ℕ² = ℕ × ℕ _∼_ : ℕ² → ℕ² → Set (x , y) ∼ (x' , y') = x + y' ≅ x' + y infix 10 _∼_ ∼-trans : ∀ {i j k} → i ∼ j → j ∼ k → i ∼ k ∼-trans {x₁ , y₁} {x₂ , y₂} {x₃ , y₃} p q = ≡-to-≅ $ +-cancelˡ-≡ y₂ $ ≅-to-≡ $ begin y₂ + (x₁ + y₃) ≡⟨ ≡.sym (+-assoc y₂ x₁ y₃) ⟩ y₂ + x₁ + y₃ ≡⟨ ≡.cong (_+ y₃) (+-comm y₂ x₁) ⟩ x₁ + y₂ + y₃ ≅⟨ cong (_+ y₃) p ⟩ x₂ + y₁ + y₃ ≡⟨ ≡.cong (_+ y₃) (+-comm x₂ y₁) ⟩ y₁ + x₂ + y₃ ≡⟨ +-assoc y₁ x₂ y₃ ⟩ y₁ + (x₂ + y₃) ≅⟨ cong (y₁ +_) q ⟩ y₁ + (x₃ + y₂) ≡⟨ +-comm y₁ (x₃ + y₂) ⟩ x₃ + y₂ + y₁ ≡⟨ ≡.cong (_+ y₁) (+-comm x₃ y₂) ⟩ y₂ + x₃ + y₁ ≡⟨ +-assoc y₂ x₃ y₁ ⟩ y₂ + (x₃ + y₁) ∎ ∼-isEquivalence : IsEquivalence _∼_ ∼-isEquivalence = record { refl = refl ; sym = sym ; trans = λ {i} {j} {k} → ∼-trans {i} {j} {k} } ℕ²-∼-setoid : Setoid 0ℓ 0ℓ ℕ²-∼-setoid = record { isEquivalence = ∼-isEquivalence } module Integers (quot : Quotients 0ℓ 0ℓ) where Int : Quotient ℕ²-∼-setoid Int = quot _ open Quotient Int renaming (Q to ℤ) _+²_ : ℕ² → ℕ² → ℕ² (x₁ , y₁) +² (x₂ , y₂) = x₁ + x₂ , y₁ + y₂ +²-cong : ∀{a b a' b'} → a ∼ a' → b ∼ b' → a +² b ∼ a' +² b' +²-cong {a₁ , b₁} {c₁ , d₁} {a₂ , b₂} {c₂ , d₂} ab∼cd₁ ab∼cd₂ = begin (a₁ + c₁) + (b₂ + d₂) ≡⟨ ≡.cong (_+ (b₂ + d₂)) (+-comm a₁ c₁) ⟩ (c₁ + a₁) + (b₂ + d₂) ≡⟨ +-assoc c₁ a₁ (b₂ + d₂) ⟩ c₁ + (a₁ + (b₂ + d₂)) ≡⟨ ≡.cong (c₁ +_) (≡.sym (+-assoc a₁ b₂ d₂)) ⟩ c₁ + (a₁ + b₂ + d₂) ≅⟨ cong (λ n → c₁ + (n + d₂)) ab∼cd₁ ⟩ c₁ + (a₂ + b₁ + d₂) ≡⟨ ≡.cong (c₁ +_) (+-assoc a₂ b₁ d₂) ⟩ c₁ + (a₂ + (b₁ + d₂)) ≡⟨ ≡.cong (λ n → c₁ + (a₂ + n)) (+-comm b₁ d₂) ⟩ c₁ + (a₂ + (d₂ + b₁)) ≡⟨ ≡.sym (+-assoc c₁ a₂ (d₂ + b₁)) ⟩ (c₁ + a₂) + (d₂ + b₁) ≡⟨ ≡.cong (_+ (d₂ + b₁)) (+-comm c₁ a₂) ⟩ (a₂ + c₁) + (d₂ + b₁) ≡⟨ +-assoc a₂ c₁ (d₂ + b₁) ⟩ a₂ + (c₁ + (d₂ + b₁)) ≡⟨ ≡.cong (a₂ +_) (≡.sym (+-assoc c₁ d₂ b₁)) ⟩ a₂ + (c₁ + d₂ + b₁) ≅⟨ cong (λ n → a₂ + (n + b₁)) ab∼cd₂ ⟩ a₂ + (c₂ + d₁ + b₁) ≡⟨ ≡.cong (a₂ +_) (+-assoc c₂ d₁ b₁) ⟩ a₂ + (c₂ + (d₁ + b₁)) ≡⟨ ≡.cong (λ n → a₂ + (c₂ + n)) (+-comm d₁ b₁) ⟩ a₂ + (c₂ + (b₁ + d₁)) ≡⟨ ≡.sym (+-assoc a₂ c₂ (b₁ + d₁)) ⟩ (a₂ + c₂) + (b₁ + d₁) ∎ module _ (ext : ∀ {a b} {A : Set a} {B₁ B₂ : A → Set b} {f₁ : ∀ a → B₁ a} {f₂ : ∀ a → B₂ a} → (∀ a → f₁ a ≅ f₂ a) → f₁ ≅ f₂) where _+ℤ_ : ℤ → ℤ → ℤ _+ℤ_ = Properties₂.lift₂ ext Int Int (λ i j → abs (i +² j)) $ λ {a} {b} {c} p p' → compat-abs (+²-cong {a} {b} {c} p p') zero² : ℕ² zero² = 0 , 0 zeroℤ : ℤ zeroℤ = abs zero² +²-identityʳ : (i : ℕ²) → (i +² zero²) ∼ i +²-identityʳ (x , y) = begin (x + 0) + y ≡⟨ ≡.cong (_+ y) (+-identityʳ x) ⟩ x + y ≡⟨ ≡.cong (x +_) (≡.sym (+-identityʳ y)) ⟩ x + (y + 0) ∎ +ℤ-on-abs≅abs-+₂ : ∀ a b → abs a +ℤ abs b ≅ abs (a +² b) +ℤ-on-abs≅abs-+₂ = Properties₂.lift₂-conv ext Int Int _ $ λ {a} {b} {c} p p′ → compat-abs (+²-cong {a} {b} {c} p p′) +ℤ-identityʳ : ∀ i → i +ℤ zeroℤ ≅ i +ℤ-identityʳ = lift _ eq (≅-heterogeneous-irrelevantʳ _ _ ∘ compat-abs) where eq : ∀ a → abs a +ℤ zeroℤ ≅ abs a eq a = begin abs a +ℤ zeroℤ ≡⟨⟩ abs a +ℤ abs zero² ≅⟨ +ℤ-on-abs≅abs-+₂ a zero² ⟩ abs (a +² zero²) ≅⟨ compat-abs (+²-identityʳ a) ⟩ abs a ∎ +²-identityˡ : (i : ℕ²) → (zero² +² i) ∼ i +²-identityˡ i = refl +ℤ-identityˡ : (i : ℤ) → zeroℤ +ℤ i ≅ i +ℤ-identityˡ = lift _ eq (≅-heterogeneous-irrelevantʳ _ _ ∘ compat-abs) where eq : ∀ a → zeroℤ +ℤ abs a ≅ abs a eq a = begin zeroℤ +ℤ abs a ≡⟨⟩ abs zero² +ℤ abs a ≅⟨ +ℤ-on-abs≅abs-+₂ zero² a ⟩ abs (zero² +² a) ≅⟨ compat-abs (+²-identityˡ a) ⟩ abs a ∎ +²-assoc : (i j k : ℕ²) → (i +² j) +² k ∼ i +² (j +² k) +²-assoc (a , b) (c , d) (e , f) = begin ((a + c) + e) + (b + (d + f)) ≡⟨ ≡.cong (_+ (b + (d + f))) (+-assoc a c e) ⟩ (a + (c + e)) + (b + (d + f)) ≡⟨ ≡.cong ((a + (c + e)) +_) (≡.sym (+-assoc b d f)) ⟩ (a + (c + e)) + ((b + d) + f) ∎ +ℤ-assoc : ∀ i j k → (i +ℤ j) +ℤ k ≅ i +ℤ (j +ℤ k) +ℤ-assoc = Properties₃.lift₃ ext Int Int Int eq compat₃ where eq : ∀ i j k → (abs i +ℤ abs j) +ℤ abs k ≅ abs i +ℤ (abs j +ℤ abs k) eq i j k = begin (abs i +ℤ abs j) +ℤ abs k ≅⟨ cong (_+ℤ abs k) (+ℤ-on-abs≅abs-+₂ i j) ⟩ (abs (i +² j) +ℤ abs k) ≅⟨ +ℤ-on-abs≅abs-+₂ (i +² j) k ⟩ abs ((i +² j) +² k) ≅⟨ compat-abs (+²-assoc i j k) ⟩ abs (i +² (j +² k)) ≅⟨ sym (+ℤ-on-abs≅abs-+₂ i (j +² k)) ⟩ (abs i +ℤ abs (j +² k)) ≅⟨ cong (abs i +ℤ_) (sym (+ℤ-on-abs≅abs-+₂ j k)) ⟩ abs i +ℤ (abs j +ℤ abs k) ∎ compat₃ : ∀ {a a′ b b′ c c′} → a ∼ a′ → b ∼ b′ → c ∼ c′ → eq a b c ≅ eq a′ b′ c′ compat₃ p q r = ≅-heterogeneous-irrelevantˡ _ _ $ cong₂ _+ℤ_ (cong₂ _+ℤ_ (compat-abs p) (compat-abs q)) $ compat-abs r
Formal statement is: lemma prime_power_cancel: assumes "prime p" and eq: "m * (p ^ k) = m' * (p ^ k')" and "\<not> p dvd m" "\<not> p dvd m'" shows "k = k'" Informal statement is: If $p$ is prime, $m$ and $m'$ are not divisible by $p$, and $m p^k = m' p^{k'}$, then $k = k'$.
The event will be held in the historic Naper Settlement at 523 S. Webster St. on Friday, September 18, and Saturday, September 19. If you are coming from downtown, the Metra will get you there quickly, and the stop is closeby. You can purchase tickets in advance for $25 through the website or by calling (847)382-1480. Tickets can also be purchase at the door for $30, and includes a souvenier glass, a Festival program, 10 tastes, and access to food, demos, and music. An additional 10 tastes can be purchased for $5, while designated drivers can enter for $10, with the same benefits, except their 10 tastes are replaced by 2 non alcoholic drinks. Groups of 15 or more receive a 10% discount. A portion of all proceeds benefits the Naperville Area Humane Society and Naper Settlement. If you are not the biggest wine fan, you can still enjoy the fest. Not only will there be lots of food and entertainment, but a Belgian Beer Cafe will be onhand. It is sponsored by Stella Artois, and will also include Leffe and Hoegaarden beers. No matter what you like, I guarantee you will enjoy this trip to Naperville and its gorgeous riverwalk. Treat yourself to a day away from the big city with some wine and Naperville!
% See how well partial Kalman filter updates work seed = 0; rand('state', seed); randn('state', seed); nlandmarks = 6; T = 12; [A,B,C,Q,R,Qbig,Rbig,init_x,init_V,robot_block,landmark_block,... true_landmark_pos, true_robot_pos, true_data_assoc, ... obs_rel_pos, ctrl_signal] = mk_linear_slam(... 'nlandmarks', nlandmarks, 'T', T, 'ctrl', 'leftright', 'data-assoc', 'cycle'); % exact [xe, Ve] = kalman_filter(obs_rel_pos, A, C, Qbig, Rbig, init_x, init_V, ... 'model', true_data_assoc, 'u', ctrl_signal, 'B', B); % approx %k = nlandmarks-1; % exact k = 3; ndx = {}; for t=1:T landmarks = unique(true_data_assoc(t:-1:max(t-k,1))); tmp = [landmark_block(:, landmarks) robot_block']; ndx{t} = tmp(:); end [xa, Va] = kalman_filter(obs_rel_pos, A, C, Qbig, Rbig, init_x, init_V, ... 'model', true_data_assoc, 'u', ctrl_signal, 'B', B, ... 'ndx', ndx); nrows = 10; stepsize = T/(2*nrows); ts = 1:stepsize:T; if 1 % plot clim = [0 max(max(Va(:,:,end)))]; figure(2) if 0 imagesc(Ve(1:2:end,1:2:end, T)) clim = get(gca,'clim'); else i = 1; for t=ts(:)' subplot(nrows,2,i) i = i + 1; imagesc(Ve(1:2:end,1:2:end, t)) set(gca, 'clim', clim) colorbar end end suptitle('exact') figure(3) if 0 imagesc(Va(1:2:end,1:2:end, T)) set(gca,'clim', clim) else i = 1; for t=ts(:)' subplot(nrows,2,i) i = i+1; imagesc(Va(1:2:end,1:2:end, t)) set(gca, 'clim', clim) colorbar end end suptitle('approx') figure(4) i = 1; for t=ts(:)' subplot(nrows,2,i) i = i+1; Vd = Va(1:2:end,1:2:end, t) - Ve(1:2:end,1:2:end,t); imagesc(Vd) set(gca, 'clim', clim) colorbar end suptitle('diff') end % all plot for t=1:T %err(t)=rms(xa(:,t), xe(:,t)); err(t)=rms(xa(1:end-2,t), xe(1:end-2,t)); % exclude robot end figure(5);plot(err) title('rms mean pos') for t=1:T i = 1:2*nlandmarks; denom = Ve(i,i,t) + (Ve(i,i,t)==0); Vd =(Va(i,i,t)-Ve(i,i,t)) ./ denom; Verr(t) = max(Vd(:)); end figure(6); plot(Verr) title('max relative Verr')
Formal statement is: lemma finite_ball_include: fixes a :: "'a::metric_space" assumes "finite S" shows "\<exists>e>0. S \<subseteq> ball a e" Informal statement is: If $S$ is a finite set, then there exists a positive real number $e$ such that $S \subseteq B(a, e)$.
------------------------------------------------------------------------------ -- Agda-Prop Library. -- Syntax definitions. ------------------------------------------------------------------------------ open import Data.Nat using ( ℕ ) module Data.PropFormula.Syntax ( n : ℕ ) where ------------------------------------------------------------------------------ open import Data.Bool renaming ( _∧_ to _&&_; _∨_ to _||_ ) using ( Bool; true; false; not ) open import Data.Fin using ( Fin; #_ ) open import Data.List using ( List ; [] ; _∷_ ; _++_ ; [_] ) open import Relation.Binary.PropositionalEquality using ( _≡_; refl; cong; trans; sym; subst) ------------------------------------------------------------------------------ -- Proposition data type. data PropFormula : Set where Var : Fin n → PropFormula ⊤ : PropFormula ⊥ : PropFormula _∧_ _∨_ _⊃_ _⇔_ : (φ ψ : PropFormula) → PropFormula ¬_ : (φ : PropFormula) → PropFormula infix 11 ¬_ infixl 8 _∧_ _∨_ infixr 7 _⊃_ _⇔_ -- Context is a list (set) of hypotesis and axioms. Ctxt : Set Ctxt = List PropFormula infixl 5 _,_ _,_ : Ctxt → PropFormula → Ctxt Γ , φ = Γ ++ [ φ ] ∅ : Ctxt ∅ = [] infix 30 _⨆_ _⨆_ : Ctxt → Ctxt → Ctxt Γ ⨆ Δ = Γ ++ Δ infix 4 _∈_ data _∈_ (φ : PropFormula) : Ctxt → Set where here : ∀ {Γ} → φ ∈ Γ , φ there : ∀ {Γ} → (ψ : PropFormula) → φ ∈ Γ → φ ∈ Γ , ψ ⨆-ext : ∀ {Γ} → (Δ : Ctxt) → φ ∈ Γ → φ ∈ Γ ⨆ Δ _⊆_ : Ctxt → Ctxt → Set Γ ⊆ Η = ∀ {φ} → φ ∈ Γ → φ ∈ Η ------------------------------------------------------------------------ -- Theorem data type. infix 3 _⊢_ data _⊢_ : Ctxt → PropFormula → Set where -- Hyp. assume : ∀ {Γ} → (φ : PropFormula) → Γ , φ ⊢ φ axiom : ∀ {Γ} → (φ : PropFormula) → φ ∈ Γ → Γ ⊢ φ weaken : ∀ {Γ} {φ} → (ψ : PropFormula) → Γ ⊢ φ → Γ , ψ ⊢ φ weaken₂ : ∀ {Γ} {φ} → (ψ : PropFormula) → Γ ⊢ φ → ψ ∷ Γ ⊢ φ -- Top and Bottom. ⊤-intro : ∀ {Γ} → Γ ⊢ ⊤ ⊥-elim : ∀ {Γ} → (φ : PropFormula) → Γ ⊢ ⊥ → Γ ⊢ φ -- Negation. ¬-intro : ∀ {Γ} {φ} → Γ , φ ⊢ ⊥ → Γ ⊢ ¬ φ ¬-elim : ∀ {Γ} {φ} → Γ ⊢ ¬ φ → Γ ⊢ φ → Γ ⊢ ⊥ -- Conjunction. ∧-intro : ∀ {Γ} {φ ψ} → Γ ⊢ φ → Γ ⊢ ψ → Γ ⊢ φ ∧ ψ ∧-proj₁ : ∀ {Γ} {φ ψ} → Γ ⊢ φ ∧ ψ → Γ ⊢ φ ∧-proj₂ : ∀ {Γ} {φ ψ} → Γ ⊢ φ ∧ ψ → Γ ⊢ ψ -- Disjunction. ∨-intro₁ : ∀ {Γ} {φ} → (ψ : PropFormula) → Γ ⊢ φ → Γ ⊢ φ ∨ ψ ∨-intro₂ : ∀ {Γ} {ψ} → (φ : PropFormula) → Γ ⊢ ψ → Γ ⊢ φ ∨ ψ ∨-elim : ∀ {Γ} {φ ψ χ} → Γ , φ ⊢ χ → Γ , ψ ⊢ χ → Γ , φ ∨ ψ ⊢ χ -- Implication. ⊃-intro : ∀ {Γ} {φ ψ} → Γ , φ ⊢ ψ → Γ ⊢ φ ⊃ ψ ⊃-elim : ∀ {Γ} {φ ψ} → Γ ⊢ φ ⊃ ψ → Γ ⊢ φ → Γ ⊢ ψ -- Biconditional. ⇔-intro : ∀ {Γ} {φ ψ} → Γ , φ ⊢ ψ → Γ , ψ ⊢ φ → Γ ⊢ φ ⇔ ψ ⇔-elim₁ : ∀ {Γ} {φ ψ} → Γ ⊢ φ → Γ ⊢ φ ⇔ ψ → Γ ⊢ ψ ⇔-elim₂ : ∀ {Γ} {φ ψ} → Γ ⊢ ψ → Γ ⊢ φ ⇔ ψ → Γ ⊢ φ ------------------------------------------------------------------------
-- @@stderr -- dtrace: failed to compile script test/unittest/arithmetic/err.D_DIV_ZERO.modby0.d: [D_DIV_ZERO] line 20: expression contains division by zero
#redirect Davis Players Society
module 100-natural where open import 010-false-true open import 020-equivalence record Natural {N : Set} (zero : N) (suc : N -> N) (_==_ : N -> N -> Set) : Set1 where -- axioms field equiv : Equivalence _==_ sucn!=zero : ∀ {r} -> suc r == zero -> False sucinjective : ∀ {r s} -> suc r == suc s -> r == s cong : ∀ {r s} -> r == s -> suc r == suc s induction : (p : N -> Set) -> p zero -> (∀ n -> p n -> p (suc n)) -> (∀ n -> p n) open Equivalence equiv public
module Main import System countdown : (secs : Nat) -> IO () countdown Z = putStrLn "Lift off!" countdown (S secs) = do putStrLn (show (S secs)) usleep 1000000 countdown secs
Editor’s Note: A few weeks ago, we ran a provocative piece by Stephen Watts and Sean Mann in which they argued that in both its politics and in its development, Afghanistan is doing better than is commonly believed. Gary Owen, a civilian development worker who has spent the last several years working on the ground in Afghanistan, begs to differ. He paints a far gloomier picture of Afghanistan, arguing that the country and U.S. policy have a long way to go. Many Americans are surprisingly bullish on Afghanistan, and this perspective showed up in a July Lawfare post on “Afghanistan After the Drawdown” by RAND analysts Stephen Watts and Sean Mann. Although the two authors offer some valid points, they miss many of the country’s problems and, in so doing, are wrongly optimistic about where Afghanistan is going. After a decade and more of U.S. intervention, it can be difficult to pin down how things are going in Afghanistan. By some measures, things in Afghanistan are better: There are more children in school than there were under the Taliban, more Afghans have access to basic healthcare than before the 2001 invasion, and Internet access means more connections to the outside world than was ever possible during the time of the black turbans. Watts and Mann cite those cases as reasons to be optimistic about the country, and rightly so. Where they go wrong is in three key areas: relations with Pakistan, the current government as a symbol of Afghan unity, and the abilities of Afghan security forces. Pakistan’s got plenty to worry about when it comes to sanctuaries within its own borders, a grim point made by last year’s school shooting in Peshawar. And recent revelations that Mullah Omar died in Pakistan, and his whereabouts were known to the ISI for years, don’t paint a picture of Afghanistan being used as a base to launch operations against Pakistan. Instead it speaks to Pakistan’s harboring of the Taliban with the government’s knowledge, something Islamabad is scrambling to correct as they look ahead to peace talks with the Taliban. Or it’s just a case of Afghanistan following the American lead. In the fall of 2014, after another runoff election threatened to bring the country’s democratic future to a grinding halt, Secretary of State John Kerry addressed a group made up of Abdullah’s leadership team. According to an administration official, Kerry told the group, “I have to emphasize to you that if you do not have an agreement, if you do not move to a unity government, the United States will not be able to support Afghanistan.” Aimed squarely at those who supported Abdullah to the point that they might take up arms in his name, Kerry’s statement was an offer neither Ghani nor Abdullah could possibly refuse. The current government isn’t a triumph of consensus so much as it is a case study in diplomatic extortion, and its survival is doubtful if the Americans stick with the current timeline for complete withdrawal by the end of 2016. The current government isn’t a triumph of consensus so much as it is a case study in diplomatic extortion, and its survival is doubtful if the Americans stick with the current timeline for complete withdrawal by the end of 2016. Thanks to advances by the Taliban in Faryab and Kunduz, influential politicians like Rashid Dostum (currently Ghani’s vice president) and Atta Noor (the powerful governor of Balkh province) have been pretty vocal in their thinking that Afghan forces alone can’t get the job done; that to tip the balance means more troops from somewhere—either the Americans (not out of the question completely, but unlikely), or some kind of militia. Since today’s anti-Taliban militia could be tomorrow’s coup attempt, it lays some troubling groundwork for widening existing divides in the country that the United States had hoped the Ghani/Abdullah deal would help bridge. Unless they can manage to bring the security situation that’s deteriorating faster than Iggy Azalea’s career back under control, Afghan troops could have some new bosses very soon. Their current performance doesn’t inspire much hope. Actually, it’s pretty clear how those forces will perform. In a word? Badly. Since the Afghans assumed control of the country’s security in 2014, more civilians have been killed, more soldiers have died, more Afghan troops have deserted than ever before, and security forces are still torturing one-third of their detainees. This is the force Watts and Mann describe as “passably capable” and “resilient.” If by “passably capable” they mean “doesn’t torture too many people,” then sure, I suppose they are “passably capable,” but I think we might want to aim just a bit higher. According to the Americans, civilian casualties as a result of ground engagements between the Afghans and insurgents were up eight percent for the first three months of 2015 when compared to the same period in 2014. In June, Afghan Chief of Army Staff Gen. Qadam Shah Shaheem told his troops that using artillery and conducting night raids against the insurgents was just fine, and no one would be prosecuted as a result. Since most engagements occur among the population when one is countering an insurgency, this change in the rules of engagement means more innocent civilians are going to die as the result of actions by Afghan security forces. That’s borne out by the latest report on civilian casualties from UNAMA, which found that throughout the first half of 2015, Afghan forces caused more civilian casualties than the Taliban did. And when they’re not busy leveling villages, Afghan forces are dying in record numbers. Throughout the first five months of 2015, security forces casualties were up 70 percent from the same period in 2014. Some of that’s attributable to increasing activity by the insurgents, but a “capable” force doesn’t see that kind of casualty increase unless its capabilities are less than optimal. Even so, the biggest cause of attrition for Afghan troops isn’t being killed in action (KIA). According to a June report by the Americans to Congress, the largest source for attrition is “dropped from rolls” (wherein a soldier stops showing up for work for more than a month so he’s no longer counted), and KIA is the smallest source for Afghan force attrition. But when they do manage to not die and to show up for work, Afghan forces like to spend some quality time with their detainees. A February report by the United Nations Assistance Mission in Afghanistan (UNAMA) found that while torture is on the decrease, around 35 percent of all detainees surveyed reported being tortured in detention. Much of that alleged torture was at the hands of the National Directorate of Security (NDS), which is similar to the FBI, except that the FBI has better windbreakers and isn’t prone to hooking people up to car batteries unnecessarily. That probably explains why the Americans made it clear in June that no U.S. funds were going to the NDS, even though nearly every other aspect of Afghan defense operations comes directly from American coffers and internal defense is vital for the success of the counterinsurgency. In an alternate-reality Afghanistan, civilians aren’t dying in greater numbers, the government isn’t on the verge of collapse, and the return on foreign investment is staggering. The Afghans would love it—because that’s the country the Americans promised them. An American solution to Afghanistan’s problems faces the struggles of a dwindling security force to keep the Taliban at bay as they strike from sanctuaries in Pakistan, a government on the verge of collapse, and large numbers of civilians being victimized by their own government. And that’s without the growing threat of the Islamic State. In an alternate-reality Afghanistan, civilians aren’t dying in greater numbers, the government isn’t on the verge of collapse, and the return on foreign investment is staggering. The Afghans would love it—because that’s the country the Americans promised them. The reality is that that Afghanistan’s future, while grim, is still better than it was. There is cause for cautious optimism. That does not mean that we shouldn’t be painfully honest about what’s happening in Afghanistan. Given the sacrifices made since 9/11, it’s tempting to do otherwise. But doing so means ignoring challenges the country faces, and the decisions about its future the Americans still need to make.
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import order.bounds /-! # Intervals in Lattices In this file, we provide instances of lattice structures on intervals within lattices. Some of them depend on the order of the endpoints of the interval, and thus are not made global instances. These are probably not all of the lattice instances that could be placed on these intervals, but more can be added easily along the same lines when needed. ## Main definitions In the following, `*` can represent either `c`, `o`, or `i`. * `set.Ic*.order_bot` * `set.Ii*.semillatice_inf` * `set.I*c.order_top` * `set.I*c.semillatice_inf` * `set.I**.lattice` * `set.Iic.bounded_order`, within an `order_bot` * `set.Ici.bounded_order`, within an `order_top` -/ variable {α : Type*} namespace set namespace Ico variables {a b : α} instance [semilattice_inf α] : semilattice_inf (Ico a b) := subtype.semilattice_inf (λ x y hx hy, ⟨le_inf hx.1 hy.1, lt_of_le_of_lt inf_le_left hx.2⟩) /-- `Ico a b` has a bottom element whenever `a < b`. -/ @[reducible] protected def order_bot [partial_order α] (h : a < b) : order_bot (Ico a b) := (is_least_Ico h).order_bot end Ico namespace Iio instance [semilattice_inf α] {a : α} : semilattice_inf (Iio a) := subtype.semilattice_inf (λ x y hx hy, lt_of_le_of_lt inf_le_left hx) end Iio namespace Ioc variables {a b : α} instance [semilattice_sup α] : semilattice_sup (Ioc a b) := subtype.semilattice_sup (λ x y hx hy, ⟨lt_of_lt_of_le hx.1 le_sup_left, sup_le hx.2 hy.2⟩) /-- `Ioc a b` has a top element whenever `a < b`. -/ @[reducible] protected def order_top [partial_order α] (h : a < b) : order_top (Ioc a b) := (is_greatest_Ioc h).order_top end Ioc namespace Iio instance [semilattice_sup α] {a : α} : semilattice_sup (Ioi a) := subtype.semilattice_sup (λ x y hx hy, lt_of_lt_of_le hx le_sup_left) end Iio namespace Iic variables {a : α} instance [semilattice_inf α] : semilattice_inf (Iic a) := subtype.semilattice_inf (λ x y hx hy, le_trans inf_le_left hx) instance [semilattice_sup α] : semilattice_sup (Iic a) := subtype.semilattice_sup (λ x y hx hy, sup_le hx hy) instance [lattice α] : lattice (Iic a) := { .. Iic.semilattice_inf, .. Iic.semilattice_sup } instance [preorder α] : order_top (Iic a) := { top := ⟨a, le_refl a⟩, le_top := λ x, x.prop } @[simp] lemma coe_top [partial_order α] {a : α} : ↑(⊤ : Iic a) = a := rfl instance [preorder α] [order_bot α] : order_bot (Iic a) := { bot := ⟨⊥, bot_le⟩, bot_le := λ ⟨_,_⟩, subtype.mk_le_mk.2 bot_le } @[simp] lemma coe_bot [preorder α] [order_bot α] {a : α} : ↑(⊥ : Iic a) = (⊥ : α) := rfl instance [partial_order α] [no_min_order α] {a : α} : no_min_order (Iic a) := ⟨λ x, let ⟨y, hy⟩ := exists_lt x.1 in ⟨⟨y, le_trans hy.le x.2⟩, hy⟩ ⟩ instance [preorder α] [order_bot α] : bounded_order (Iic a) := { .. Iic.order_top, .. Iic.order_bot } end Iic namespace Ici variables {a : α} instance [semilattice_inf α] : semilattice_inf (Ici a) := subtype.semilattice_inf (λ x y hx hy, le_inf hx hy) instance [semilattice_sup α] : semilattice_sup (Ici a) := subtype.semilattice_sup (λ x y hx hy, le_trans hx le_sup_left) instance [lattice α] : lattice (Ici a) := { .. Ici.semilattice_inf, .. Ici.semilattice_sup } instance [preorder α] : order_bot (Ici a) := { bot := ⟨a, le_refl a⟩, bot_le := λ x, x.prop } @[simp] lemma coe_bot [partial_order α] {a : α} : ↑(⊥ : Ici a) = a := rfl instance [preorder α] [order_top α] : order_top (Ici a) := { top := ⟨⊤, le_top⟩, le_top := λ ⟨_,_⟩, subtype.mk_le_mk.2 le_top } @[simp] lemma coe_top [preorder α] [order_top α] {a : α} : ↑(⊤ : Ici a) = (⊤ : α) := rfl instance [partial_order α] [no_max_order α] {a : α} : no_max_order (Ici a) := ⟨λ x, let ⟨y, hy⟩ := exists_gt x.1 in ⟨⟨y, le_trans x.2 hy.le⟩, hy⟩ ⟩ instance [preorder α] [order_top α] : bounded_order (Ici a) := { .. Ici.order_top, .. Ici.order_bot } end Ici namespace Icc instance [semilattice_inf α] {a b : α} : semilattice_inf (Icc a b) := subtype.semilattice_inf (λ x y hx hy, ⟨le_inf hx.1 hy.1, le_trans inf_le_left hx.2⟩) instance [semilattice_sup α] {a b : α} : semilattice_sup (Icc a b) := subtype.semilattice_sup (λ x y hx hy, ⟨le_trans hx.1 le_sup_left, sup_le hx.2 hy.2⟩) instance [lattice α] {a b : α} : lattice (Icc a b) := { .. Icc.semilattice_inf, .. Icc.semilattice_sup } /-- `Icc a b` has a bottom element whenever `a ≤ b`. -/ @[reducible] protected def order_bot [preorder α] {a b : α} (h : a ≤ b) : order_bot (Icc a b) := (is_least_Icc h).order_bot /-- `Icc a b` has a top element whenever `a ≤ b`. -/ @[reducible] protected def order_top [preorder α] {a b : α} (h : a ≤ b) : order_top (Icc a b) := (is_greatest_Icc h).order_top /-- `Icc a b` is a `bounded_order` whenever `a ≤ b`. -/ @[reducible] protected def bounded_order [preorder α] {a b : α} (h : a ≤ b) : bounded_order (Icc a b) := { .. Icc.order_top h, .. Icc.order_bot h } end Icc end set
module Render import Data.String import VNode import Attributes -- Creates an empty node an returns a pointer to it %foreign "browser:lambda: node => document.createElement(node)" prim__makeNode : String -> PrimIO AnyPtr -- Returns undefined %foreign "browser:lambda: (node, attr, value) => node.setAttribute(attr, value)" prim__setAttr : AnyPtr -> String -> String -> PrimIO AnyPtr %foreign "browser:lambda: (parent, child) => parent.appendChild(child)" prim__addNode : AnyPtr -> AnyPtr -> PrimIO AnyPtr %foreign "browser:lambda: id => document.getElementById(id)" prim__getRoot : String -> PrimIO AnyPtr %foreign "browser:lambda: text => document.createTextNode(text)" prim__madeText : String -> PrimIO AnyPtr %foreign "browser:lambda: value => console.log(value)" prim__consoleLog : AnyPtr -> PrimIO AnyPtr %foreign "browser:lambda: value => console.log(value)" prim__consoleString : String -> PrimIO AnyPtr %foreign "browser:lambda: node => node.innerHTML = ''" prim__clearNode : AnyPtr -> PrimIO AnyPtr export getRoot : String -> IO AnyPtr getRoot id = primIO $ prim__getRoot id export consoleLog : Show a => a -> IO () consoleLog x = do _ <- primIO $ prim__consoleString (show x) pure () export setAttributes : NodeRef -> List Attribute -> IO NodeRef setAttributes node attrs = do _ <- traverse (setAttribute node) attrs pure node where setAttribute : NodeRef -> Attribute -> IO NodeRef setAttribute node (Class xs) = primIO $ prim__setAttr node "class" (unwords xs) setAttribute node (Accept x) = primIO $ prim__setAttr node "accept" x setAttribute node (AcceptCharSet x) = primIO $ prim__setAttr node "accept-charset" x setAttribute node (AcessKey x) = primIO $ prim__setAttr node "accesskey" x setAttribute node (Action x) = primIO $ prim__setAttr node "action" x setAttribute node Async = primIO $ prim__setAttr node "async" "" -- TODO Fix this setAttribute node (Cols x) = primIO $ prim__setAttr node "cols" (show x) setAttribute node (Attr x y) = primIO $ prim__setAttr node x y setAttribute node (Id x) = primIO $ prim__setAttr node "id" x makeNode : (Node V tagType) -> IO NodeRef makeNode (Tag name attrs children) = do node <- primIO $ prim__makeNode name _ <- setAttributes node attrs pure node makeNode (Void name attrs) = do node <- primIO $ prim__makeNode name _ <- setAttributes node attrs pure node makeNode (Text text) = primIO $ prim__madeText text attachNode : (parent : NodeRef) -> (child : NodeRef) -> IO () attachNode parent child = do _ <- primIO $ prim__addNode parent child pure () render' : (root : NodeRef) -> (vdom : DOM V) -> IO (DOM L) render' root (VDOM meta node) = do ref <- makeNode node _ <- attachNode root ref case node of (Tag name attr children) => do children <- traverse (render' ref) children let liveNode = Tag name attr children pure (LiveDOM meta liveNode ref) (Text string) => pure (LiveDOM meta (Text string) ref) (Void name attr) => pure (LiveDOM meta (Void name attr) ref) export render : (root : NodeRef) -> (vdom : DOM V) -> IO (DOM L) render root vdom = do _ <- primIO $ prim__clearNode root render' root vdom
theory T14 imports Main begin lemma "( (\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) & (\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(x, meet(y, z)) = join(over(x, y), over(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(meet(x, y), z) = join(undr(x, z), undr(y, z))) & (\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) & (\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) & (\<forall> x::nat. invo(invo(x)) = x) ) \<longrightarrow> (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, meet(y, z)) = meet(mult(x, y), mult(x, z))) " nitpick[card nat=4,timeout=86400] oops end
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import order.category.BddDistLat import order.heyting.hom /-! # The category of Heyting algebras This file defines `HeytAlg`, the category of Heyting algebras. -/ universes u open category_theory opposite order /-- The category of Heyting algebras. -/ def HeytAlg := bundled heyting_algebra namespace HeytAlg instance : has_coe_to_sort HeytAlg Type* := bundled.has_coe_to_sort instance (X : HeytAlg) : heyting_algebra X := X.str /-- Construct a bundled `HeytAlg` from a `heyting_algebra`. -/ def of (α : Type*) [heyting_algebra α] : HeytAlg := bundled.of α @[simp] lemma coe_of (α : Type*) [heyting_algebra α] : ↥(of α) = α := rfl instance : inhabited HeytAlg := ⟨of punit⟩ instance bundled_hom : bundled_hom heyting_hom := { to_fun := λ α β [heyting_algebra α] [heyting_algebra β], by exactI (coe_fn : heyting_hom α β → α → β), id := heyting_hom.id, comp := @heyting_hom.comp, hom_ext := λ α β [heyting_algebra α] [heyting_algebra β], by exactI fun_like.coe_injective } attribute [derive [large_category, concrete_category]] HeytAlg @[simps] instance has_forget_to_Lat : has_forget₂ HeytAlg BddDistLat := { forget₂ := { obj := λ X, BddDistLat.of X, map := λ X Y f, (f : bounded_lattice_hom X Y) } } /-- Constructs an isomorphism of Heyting algebras from an order isomorphism between them. -/ @[simps] def iso.mk {α β : HeytAlg.{u}} (e : α ≃o β) : α ≅ β := { hom := e, inv := e.symm, hom_inv_id' := by { ext, exact e.symm_apply_apply _ }, inv_hom_id' := by { ext, exact e.apply_symm_apply _ } } end HeytAlg
-- --------------------------------------------------------------- [ Model.idr ] -- Description : The Model -- Copyright : (c) Jan de Muijnck-Hughes -- License : see LICENSE -- --------------------------------------------------------------------- [ EOH ] module Commons.Options.ArgParse.Model %access public export data Arg : Type where Flag : String -> Arg KeyValue : String -> String -> Arg File : String -> Arg Show Arg where show (Flag f) = "[Flag " ++ show f ++ "]" show (KeyValue k v) = "[KeyValue " ++ show k ++ " : " ++ show v ++ "]" show (File fs) = "[File " ++ show fs ++ "]" -- --------------------------------------------------------------------- [ EOF ]
theory T51 imports Main begin lemma "( (\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) & (\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, meet(y, z)) = meet(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(x, meet(y, z)) = join(over(x, y), over(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(meet(x, y), z) = join(undr(x, z), undr(y, z))) & (\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) & (\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) & (\<forall> x::nat. invo(invo(x)) = x) ) \<longrightarrow> (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(meet(x, y), z) = meet(mult(x, z), mult(y, z))) " nitpick[card nat=7,timeout=86400] oops end
From Coq Require Import String Arith. From Vyper Require Import Config Map. From Vyper.L10 Require Import Base. From Vyper.L50 Require Import Types AST Builtins DynError. Local Open Scope list_scope. (** Lookup all the names in the variable map and check types. The names need not be distinct. *) Fixpoint get_vars_by_typenames {C: VyperConfig} (typenames: list typename) (vars: string_map dynamic_value) : dynamic_error + list dynamic_value := match typenames with | nil => inr nil | (type, name) :: rest => match map_lookup vars name as z return (_ = z -> _) with | None => fun _ => inl (DE_CannotResolveLocalVariable name) | Some value => fun found => let t := projT1 value in if yul_type_eq_dec type t then match get_vars_by_typenames rest vars with | inl err => inl err | inr rest_results => inr (value :: rest_results) end else inl (DE_TypeMismatch type t) end eq_refl end. (** Bind several variables. This happens to the function arguments right after a call and also in a variable declaration with initializer. The names must be distinct because shadowing is not allowed. *) Fixpoint bind_vars_to_values {C: VyperConfig} (vars: list typename) (init: list dynamic_value) (loc: string_map dynamic_value) : dynamic_error + string_map dynamic_value := match vars with | nil => match init with | nil => inr loc | _ => inl DE_TooManyValues end | (vtype, vname) :: vtail => match init with | nil => inl DE_TooFewValues | (existT _ itype ivalue as ihead) :: itail => if yul_type_eq_dec vtype itype then match map_lookup loc vname with | Some _ => inl (DE_LocalNameShadowing vname) | None => bind_vars_to_values vtail itail (map_insert loc vname ihead) end else inl (DE_TypeMismatch vtype itype) end end. (** Bind several variables to zeros. This happens to the function outputs right after a call and also in a variable declaration without initializer. The names must be distinct because shadowing is not allowed. *) Fixpoint bind_vars_to_zeros {C: VyperConfig} (vars: list typename) (loc: string_map dynamic_value) : dynamic_error + string_map dynamic_value := match vars with | nil => inr loc | (vtype, vname) :: vtail => match map_lookup loc vname with | Some _ => inl (DE_LocalNameShadowing vname) | None => bind_vars_to_zeros vtail (map_insert loc vname (existT _ vtype (zero_value vtype))) end end. (** Rebind several variables. This happens in assignments. *) Fixpoint rebind_vars_to_values {C: VyperConfig} (vars: list string) (rhs: list dynamic_value) (loc: string_map dynamic_value) : dynamic_error + string_map dynamic_value := match vars with | nil => match rhs with | nil => inr loc | _ => inl DE_TooManyValues end | vname :: vtail => match rhs with | nil => inl DE_TooFewValues | (existT _ rtype rvalue as rhead) :: rtail => match map_lookup loc vname with | Some (existT _ vtype _) => if yul_type_eq_dec vtype rtype then rebind_vars_to_values vtail rtail (map_insert loc vname rhead) else inl (DE_TypeMismatch rtype vtype) | None => inl (DE_CannotResolveLocalVariable vname) end end end. Fixpoint unbind_vars {C: VyperConfig} (vars: list typename) (loc: string_map dynamic_value) : string_map dynamic_value := match vars with | nil => loc | h :: t => unbind_vars t (map_remove loc (snd h)) end. Lemma unbind_vars_app {C: VyperConfig} (a b: list typename) (loc: string_map dynamic_value): unbind_vars b (unbind_vars a loc) = unbind_vars (a ++ b) loc. Proof. revert loc. induction a as [|h]; intros. { easy. } cbn. apply IHa. Qed.
{-# OPTIONS --no-sized-types #-} postulate Size : Set _^ : Size -> Size ∞ : Size {-# BUILTIN SIZE Size #-} {-# BUILTIN SIZESUC _^ #-} {-# BUILTIN SIZEINF ∞ #-} data Nat : {size : Size} -> Set where zero : {size : Size} -> Nat {size ^} suc : {size : Size} -> Nat {size} -> Nat {size ^} weak : {i : Size} -> Nat {i} -> Nat {∞} weak x = x -- Should give error without sized types. -- .i != ∞ of type Size -- when checking that the expression x has type Nat
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import order.omega_complete_partial_order import category_theory.limits.shapes.products import category_theory.limits.shapes.equalizers import category_theory.limits.constructions.limits_of_products_and_equalizers import category_theory.concrete_category.bundled_hom /-! # Category of types with a omega complete partial order In this file, we bundle the class `omega_complete_partial_order` into a concrete category and prove that continuous functions also form a `omega_complete_partial_order`. ## Main definitions * `ωCPO` * an instance of `category` and `concrete_category` -/ open category_theory universes u v /-- The category of types with a omega complete partial order. -/ def ωCPO : Type (u+1) := bundled omega_complete_partial_order namespace ωCPO open omega_complete_partial_order instance : bundled_hom @continuous_hom := { to_fun := @continuous_hom.simps.apply, id := @continuous_hom.id, comp := @continuous_hom.comp, hom_ext := @continuous_hom.coe_inj } attribute [derive [large_category, concrete_category]] ωCPO instance : has_coe_to_sort ωCPO Type* := bundled.has_coe_to_sort /-- Construct a bundled ωCPO from the underlying type and typeclass. -/ def of (α : Type*) [omega_complete_partial_order α] : ωCPO := bundled.of α @[simp] lemma coe_of (α : Type*) [omega_complete_partial_order α] : ↥(of α) = α := rfl instance : inhabited ωCPO := ⟨of punit⟩ instance (α : ωCPO) : omega_complete_partial_order α := α.str section open category_theory.limits namespace has_products /-- The pi-type gives a cone for a product. -/ def product {J : Type v} (f : J → ωCPO.{v}) : fan f := fan.mk (of (Π j, f j)) (λ j, continuous_hom.of_mono (pi.eval_order_hom j) (λ c, rfl)) /-- The pi-type is a limit cone for the product. -/ def is_product (J : Type v) (f : J → ωCPO) : is_limit (product f) := { lift := λ s, ⟨⟨λ t j, s.π.app ⟨j⟩ t, λ x y h j, (s.π.app ⟨j⟩).monotone h⟩, λ x, funext (λ j, (s.π.app ⟨j⟩).continuous x)⟩, uniq' := λ s m w, begin ext t j, change m t j = s.π.app ⟨j⟩ t, rw ← w ⟨j⟩, refl, end, fac' := λ s j, by { cases j, tidy, } }. instance (J : Type v) (f : J → ωCPO.{v}) : has_product f := has_limit.mk ⟨_, is_product _ f⟩ end has_products instance omega_complete_partial_order_equalizer {α β : Type*} [omega_complete_partial_order α] [omega_complete_partial_order β] (f g : α →𝒄 β) : omega_complete_partial_order {a : α // f a = g a} := omega_complete_partial_order.subtype _ $ λ c hc, begin rw [f.continuous, g.continuous], congr' 1, ext, apply hc _ ⟨_, rfl⟩, end namespace has_equalizers /-- The equalizer inclusion function as a `continuous_hom`. -/ def equalizer_ι {α β : Type*} [omega_complete_partial_order α] [omega_complete_partial_order β] (f g : α →𝒄 β) : {a : α // f a = g a} →𝒄 α := continuous_hom.of_mono (order_hom.subtype.val _) (λ c, rfl) /-- A construction of the equalizer fork. -/ def equalizer {X Y : ωCPO.{v}} (f g : X ⟶ Y) : fork f g := @fork.of_ι _ _ _ _ _ _ (ωCPO.of {a // f a = g a}) (equalizer_ι f g) (continuous_hom.ext _ _ (λ x, x.2)) /-- The equalizer fork is a limit. -/ def is_equalizer {X Y : ωCPO.{v}} (f g : X ⟶ Y) : is_limit (equalizer f g) := fork.is_limit.mk' _ $ λ s, ⟨{ to_fun := λ x, ⟨s.ι x, by apply continuous_hom.congr_fun s.condition⟩, monotone' := λ x y h, s.ι.monotone h, cont := λ x, subtype.ext (s.ι.continuous x) }, by { ext, refl }, λ m hm, begin ext, apply continuous_hom.congr_fun hm, end⟩ end has_equalizers instance : has_products.{v} ωCPO.{v} := λ J, { has_limit := λ F, has_limit_of_iso discrete.nat_iso_functor.symm } instance {X Y : ωCPO.{v}} (f g : X ⟶ Y) : has_limit (parallel_pair f g) := has_limit.mk ⟨_, has_equalizers.is_equalizer f g⟩ instance : has_equalizers ωCPO.{v} := has_equalizers_of_has_limit_parallel_pair _ instance : has_limits ωCPO.{v} := has_limits_of_has_equalizers_and_products end end ωCPO
(* Title: HOL/UNITY/UNITY.thy Author: Lawrence C Paulson, Cambridge University Computer Laboratory Copyright 1998 University of Cambridge The basic UNITY theory (revised version, based upon the "co" operator). From Misra, "A Logic for Concurrent Programming", 1994. *) section \<open>The Basic UNITY Theory\<close> theory UNITY imports Main begin definition "Program = {(init:: 'a set, acts :: ('a * 'a)set set, allowed :: ('a * 'a)set set). Id \<in> acts & Id \<in> allowed}" typedef 'a program = "Program :: ('a set * ('a * 'a) set set * ('a * 'a) set set) set" morphisms Rep_Program Abs_Program unfolding Program_def by blast definition Acts :: "'a program => ('a * 'a)set set" where "Acts F == (%(init, acts, allowed). acts) (Rep_Program F)" definition "constrains" :: "['a set, 'a set] => 'a program set" (infixl "co" 60) where "A co B == {F. \<forall>act \<in> Acts F. act``A \<subseteq> B}" definition unless :: "['a set, 'a set] => 'a program set" (infixl "unless" 60) where "A unless B == (A-B) co (A \<union> B)" definition mk_program :: "('a set * ('a * 'a)set set * ('a * 'a)set set) => 'a program" where "mk_program == %(init, acts, allowed). Abs_Program (init, insert Id acts, insert Id allowed)" definition Init :: "'a program => 'a set" where "Init F == (%(init, acts, allowed). init) (Rep_Program F)" definition AllowedActs :: "'a program => ('a * 'a)set set" where "AllowedActs F == (%(init, acts, allowed). allowed) (Rep_Program F)" definition Allowed :: "'a program => 'a program set" where "Allowed F == {G. Acts G \<subseteq> AllowedActs F}" definition stable :: "'a set => 'a program set" where "stable A == A co A" definition strongest_rhs :: "['a program, 'a set] => 'a set" where "strongest_rhs F A == \<Inter>{B. F \<in> A co B}" definition invariant :: "'a set => 'a program set" where "invariant A == {F. Init F \<subseteq> A} \<inter> stable A" definition increasing :: "['a => 'b::{order}] => 'a program set" where \<comment> \<open>Polymorphic in both states and the meaning of \<open>\<le>\<close>\<close> "increasing f == \<Inter>z. stable {s. z \<le> f s}" subsubsection\<open>The abstract type of programs\<close> lemmas program_typedef = Rep_Program Rep_Program_inverse Abs_Program_inverse Program_def Init_def Acts_def AllowedActs_def mk_program_def lemma Id_in_Acts [iff]: "Id \<in> Acts F" apply (cut_tac x = F in Rep_Program) apply (auto simp add: program_typedef) done lemma insert_Id_Acts [iff]: "insert Id (Acts F) = Acts F" by (simp add: insert_absorb) lemma Acts_nonempty [simp]: "Acts F \<noteq> {}" by auto lemma Id_in_AllowedActs [iff]: "Id \<in> AllowedActs F" apply (cut_tac x = F in Rep_Program) apply (auto simp add: program_typedef) done lemma insert_Id_AllowedActs [iff]: "insert Id (AllowedActs F) = AllowedActs F" by (simp add: insert_absorb) subsubsection\<open>Inspectors for type "program"\<close> lemma Init_eq [simp]: "Init (mk_program (init,acts,allowed)) = init" by (simp add: program_typedef) lemma Acts_eq [simp]: "Acts (mk_program (init,acts,allowed)) = insert Id acts" by (simp add: program_typedef) lemma AllowedActs_eq [simp]: "AllowedActs (mk_program (init,acts,allowed)) = insert Id allowed" by (simp add: program_typedef) subsubsection\<open>Equality for UNITY programs\<close> lemma surjective_mk_program [simp]: "mk_program (Init F, Acts F, AllowedActs F) = F" apply (cut_tac x = F in Rep_Program) apply (auto simp add: program_typedef) apply (drule_tac f = Abs_Program in arg_cong)+ apply (simp add: program_typedef insert_absorb) done lemma program_equalityI: "[| Init F = Init G; Acts F = Acts G; AllowedActs F = AllowedActs G |] ==> F = G" apply (rule_tac t = F in surjective_mk_program [THEN subst]) apply (rule_tac t = G in surjective_mk_program [THEN subst], simp) done lemma program_equalityE: "[| F = G; [| Init F = Init G; Acts F = Acts G; AllowedActs F = AllowedActs G |] ==> P |] ==> P" by simp lemma program_equality_iff: "(F=G) = (Init F = Init G & Acts F = Acts G &AllowedActs F = AllowedActs G)" by (blast intro: program_equalityI program_equalityE) subsubsection\<open>co\<close> lemma constrainsI: "(!!act s s'. [| act \<in> Acts F; (s,s') \<in> act; s \<in> A |] ==> s' \<in> A') ==> F \<in> A co A'" by (simp add: constrains_def, blast) lemma constrainsD: "[| F \<in> A co A'; act \<in> Acts F; (s,s') \<in> act; s \<in> A |] ==> s' \<in> A'" by (unfold constrains_def, blast) lemma constrains_empty [iff]: "F \<in> {} co B" by (unfold constrains_def, blast) lemma constrains_empty2 [iff]: "(F \<in> A co {}) = (A={})" by (unfold constrains_def, blast) lemma constrains_UNIV [iff]: "(F \<in> UNIV co B) = (B = UNIV)" by (unfold constrains_def, blast) lemma constrains_UNIV2 [iff]: "F \<in> A co UNIV" by (unfold constrains_def, blast) text\<open>monotonic in 2nd argument\<close> lemma constrains_weaken_R: "[| F \<in> A co A'; A'<=B' |] ==> F \<in> A co B'" by (unfold constrains_def, blast) text\<open>anti-monotonic in 1st argument\<close> lemma constrains_weaken_L: "[| F \<in> A co A'; B \<subseteq> A |] ==> F \<in> B co A'" by (unfold constrains_def, blast) lemma constrains_weaken: "[| F \<in> A co A'; B \<subseteq> A; A'<=B' |] ==> F \<in> B co B'" by (unfold constrains_def, blast) subsubsection\<open>Union\<close> lemma constrains_Un: "[| F \<in> A co A'; F \<in> B co B' |] ==> F \<in> (A \<union> B) co (A' \<union> B')" by (unfold constrains_def, blast) lemma constrains_UN: "(!!i. i \<in> I ==> F \<in> (A i) co (A' i)) ==> F \<in> (\<Union>i \<in> I. A i) co (\<Union>i \<in> I. A' i)" by (unfold constrains_def, blast) lemma constrains_Un_distrib: "(A \<union> B) co C = (A co C) \<inter> (B co C)" by (unfold constrains_def, blast) lemma constrains_UN_distrib: "(\<Union>i \<in> I. A i) co B = (\<Inter>i \<in> I. A i co B)" by (unfold constrains_def, blast) lemma constrains_Int_distrib: "C co (A \<inter> B) = (C co A) \<inter> (C co B)" by (unfold constrains_def, blast) lemma constrains_INT_distrib: "A co (\<Inter>i \<in> I. B i) = (\<Inter>i \<in> I. A co B i)" by (unfold constrains_def, blast) subsubsection\<open>Intersection\<close> lemma constrains_Int: "[| F \<in> A co A'; F \<in> B co B' |] ==> F \<in> (A \<inter> B) co (A' \<inter> B')" by (unfold constrains_def, blast) lemma constrains_INT: "(!!i. i \<in> I ==> F \<in> (A i) co (A' i)) ==> F \<in> (\<Inter>i \<in> I. A i) co (\<Inter>i \<in> I. A' i)" by (unfold constrains_def, blast) lemma constrains_imp_subset: "F \<in> A co A' ==> A \<subseteq> A'" by (unfold constrains_def, auto) text\<open>The reasoning is by subsets since "co" refers to single actions only. So this rule isn't that useful.\<close> lemma constrains_trans: "[| F \<in> A co B; F \<in> B co C |] ==> F \<in> A co C" by (unfold constrains_def, blast) lemma constrains_cancel: "[| F \<in> A co (A' \<union> B); F \<in> B co B' |] ==> F \<in> A co (A' \<union> B')" by (unfold constrains_def, clarify, blast) subsubsection\<open>unless\<close> lemma unlessI: "F \<in> (A-B) co (A \<union> B) ==> F \<in> A unless B" by (unfold unless_def, assumption) lemma unlessD: "F \<in> A unless B ==> F \<in> (A-B) co (A \<union> B)" by (unfold unless_def, assumption) subsubsection\<open>stable\<close> lemma stableI: "F \<in> A co A ==> F \<in> stable A" by (unfold stable_def, assumption) lemma stableD: "F \<in> stable A ==> F \<in> A co A" by (unfold stable_def, assumption) lemma stable_UNIV [simp]: "stable UNIV = UNIV" by (unfold stable_def constrains_def, auto) subsubsection\<open>Union\<close> lemma stable_Un: "[| F \<in> stable A; F \<in> stable A' |] ==> F \<in> stable (A \<union> A')" apply (unfold stable_def) apply (blast intro: constrains_Un) done lemma stable_UN: "(!!i. i \<in> I ==> F \<in> stable (A i)) ==> F \<in> stable (\<Union>i \<in> I. A i)" apply (unfold stable_def) apply (blast intro: constrains_UN) done lemma stable_Union: "(!!A. A \<in> X ==> F \<in> stable A) ==> F \<in> stable (\<Union>X)" by (unfold stable_def constrains_def, blast) subsubsection\<open>Intersection\<close> lemma stable_Int: "[| F \<in> stable A; F \<in> stable A' |] ==> F \<in> stable (A \<inter> A')" apply (unfold stable_def) apply (blast intro: constrains_Int) done lemma stable_INT: "(!!i. i \<in> I ==> F \<in> stable (A i)) ==> F \<in> stable (\<Inter>i \<in> I. A i)" apply (unfold stable_def) apply (blast intro: constrains_INT) done lemma stable_Inter: "(!!A. A \<in> X ==> F \<in> stable A) ==> F \<in> stable (\<Inter>X)" by (unfold stable_def constrains_def, blast) lemma stable_constrains_Un: "[| F \<in> stable C; F \<in> A co (C \<union> A') |] ==> F \<in> (C \<union> A) co (C \<union> A')" by (unfold stable_def constrains_def, blast) lemma stable_constrains_Int: "[| F \<in> stable C; F \<in> (C \<inter> A) co A' |] ==> F \<in> (C \<inter> A) co (C \<inter> A')" by (unfold stable_def constrains_def, blast) (*[| F \<in> stable C; F \<in> (C \<inter> A) co A |] ==> F \<in> stable (C \<inter> A) *) lemmas stable_constrains_stable = stable_constrains_Int[THEN stableI] subsubsection\<open>invariant\<close> lemma invariantI: "[| Init F \<subseteq> A; F \<in> stable A |] ==> F \<in> invariant A" by (simp add: invariant_def) text\<open>Could also say \<^term>\<open>invariant A \<inter> invariant B \<subseteq> invariant(A \<inter> B)\<close>\<close> lemma invariant_Int: "[| F \<in> invariant A; F \<in> invariant B |] ==> F \<in> invariant (A \<inter> B)" by (auto simp add: invariant_def stable_Int) subsubsection\<open>increasing\<close> lemma increasingD: "F \<in> increasing f ==> F \<in> stable {s. z \<subseteq> f s}" by (unfold increasing_def, blast) lemma increasing_constant [iff]: "F \<in> increasing (%s. c)" by (unfold increasing_def stable_def, auto) lemma mono_increasing_o: "mono g ==> increasing f \<subseteq> increasing (g o f)" apply (unfold increasing_def stable_def constrains_def, auto) apply (blast intro: monoD order_trans) done (*Holds by the theorem (Suc m \<subseteq> n) = (m < n) *) lemma strict_increasingD: "!!z::nat. F \<in> increasing f ==> F \<in> stable {s. z < f s}" by (simp add: increasing_def Suc_le_eq [symmetric]) (** The Elimination Theorem. The "free" m has become universally quantified! Should the premise be !!m instead of \<forall>m ? Would make it harder to use in forward proof. **) lemma elimination: "[| \<forall>m \<in> M. F \<in> {s. s x = m} co (B m) |] ==> F \<in> {s. s x \<in> M} co (\<Union>m \<in> M. B m)" by (unfold constrains_def, blast) text\<open>As above, but for the trivial case of a one-variable state, in which the state is identified with its one variable.\<close> lemma elimination_sing: "(\<forall>m \<in> M. F \<in> {m} co (B m)) ==> F \<in> M co (\<Union>m \<in> M. B m)" by (unfold constrains_def, blast) subsubsection\<open>Theoretical Results from Section 6\<close> lemma constrains_strongest_rhs: "F \<in> A co (strongest_rhs F A )" by (unfold constrains_def strongest_rhs_def, blast) lemma strongest_rhs_is_strongest: "F \<in> A co B ==> strongest_rhs F A \<subseteq> B" by (unfold constrains_def strongest_rhs_def, blast) subsubsection\<open>Ad-hoc set-theory rules\<close> lemma Un_Diff_Diff [simp]: "A \<union> B - (A - B) = B" by blast lemma Int_Union_Union: "\<Union>B \<inter> A = \<Union>((%C. C \<inter> A)`B)" by blast text\<open>Needed for WF reasoning in WFair.thy\<close> lemma Image_less_than [simp]: "less_than `` {k} = greaterThan k" by blast lemma Image_inverse_less_than [simp]: "less_than\<inverse> `` {k} = lessThan k" by blast subsection\<open>Partial versus Total Transitions\<close> definition totalize_act :: "('a * 'a)set => ('a * 'a)set" where "totalize_act act == act \<union> Id_on (-(Domain act))" definition totalize :: "'a program => 'a program" where "totalize F == mk_program (Init F, totalize_act ` Acts F, AllowedActs F)" definition mk_total_program :: "('a set * ('a * 'a)set set * ('a * 'a)set set) => 'a program" where "mk_total_program args == totalize (mk_program args)" definition all_total :: "'a program => bool" where "all_total F == \<forall>act \<in> Acts F. Domain act = UNIV" lemma insert_Id_image_Acts: "f Id = Id ==> insert Id (f`Acts F) = f ` Acts F" by (blast intro: sym [THEN image_eqI]) subsubsection\<open>Basic properties\<close> lemma totalize_act_Id [simp]: "totalize_act Id = Id" by (simp add: totalize_act_def) lemma Domain_totalize_act [simp]: "Domain (totalize_act act) = UNIV" by (auto simp add: totalize_act_def) lemma Init_totalize [simp]: "Init (totalize F) = Init F" by (unfold totalize_def, auto) lemma Acts_totalize [simp]: "Acts (totalize F) = (totalize_act ` Acts F)" by (simp add: totalize_def insert_Id_image_Acts) lemma AllowedActs_totalize [simp]: "AllowedActs (totalize F) = AllowedActs F" by (simp add: totalize_def) lemma totalize_constrains_iff [simp]: "(totalize F \<in> A co B) = (F \<in> A co B)" by (simp add: totalize_def totalize_act_def constrains_def, blast) lemma totalize_stable_iff [simp]: "(totalize F \<in> stable A) = (F \<in> stable A)" by (simp add: stable_def) lemma totalize_invariant_iff [simp]: "(totalize F \<in> invariant A) = (F \<in> invariant A)" by (simp add: invariant_def) lemma all_total_totalize: "all_total (totalize F)" by (simp add: totalize_def all_total_def) lemma Domain_iff_totalize_act: "(Domain act = UNIV) = (totalize_act act = act)" by (force simp add: totalize_act_def) lemma all_total_imp_totalize: "all_total F ==> (totalize F = F)" apply (simp add: all_total_def totalize_def) apply (rule program_equalityI) apply (simp_all add: Domain_iff_totalize_act image_def) done lemma all_total_iff_totalize: "all_total F = (totalize F = F)" apply (rule iffI) apply (erule all_total_imp_totalize) apply (erule subst) apply (rule all_total_totalize) done lemma mk_total_program_constrains_iff [simp]: "(mk_total_program args \<in> A co B) = (mk_program args \<in> A co B)" by (simp add: mk_total_program_def) subsection\<open>Rules for Lazy Definition Expansion\<close> text\<open>They avoid expanding the full program, which is a large expression\<close> lemma def_prg_Init: "F = mk_total_program (init,acts,allowed) ==> Init F = init" by (simp add: mk_total_program_def) lemma def_prg_Acts: "F = mk_total_program (init,acts,allowed) ==> Acts F = insert Id (totalize_act ` acts)" by (simp add: mk_total_program_def) lemma def_prg_AllowedActs: "F = mk_total_program (init,acts,allowed) ==> AllowedActs F = insert Id allowed" by (simp add: mk_total_program_def) text\<open>An action is expanded if a pair of states is being tested against it\<close> lemma def_act_simp: "act = {(s,s'). P s s'} ==> ((s,s') \<in> act) = P s s'" by (simp add: mk_total_program_def) text\<open>A set is expanded only if an element is being tested against it\<close> lemma def_set_simp: "A = B ==> (x \<in> A) = (x \<in> B)" by (simp add: mk_total_program_def) subsubsection\<open>Inspectors for type "program"\<close> lemma Init_total_eq [simp]: "Init (mk_total_program (init,acts,allowed)) = init" by (simp add: mk_total_program_def) lemma Acts_total_eq [simp]: "Acts(mk_total_program(init,acts,allowed)) = insert Id (totalize_act`acts)" by (simp add: mk_total_program_def) lemma AllowedActs_total_eq [simp]: "AllowedActs (mk_total_program (init,acts,allowed)) = insert Id allowed" by (auto simp add: mk_total_program_def) end
Formal statement is: lemma contour_integrable_lmul: "f contour_integrable_on g \<Longrightarrow> (\<lambda>x. c * f x) contour_integrable_on g" Informal statement is: If $f$ is contour-integrable on a contour $g$, then $cf$ is contour-integrable on $g$.
Formal statement is: lemma translation_eq_singleton_plus: "(\<lambda>x. a + x) ` T = {a} + T" Informal statement is: The image of a set $T$ under the translation map $x \mapsto a + x$ is equal to the set $a + T$.
module Charsets %default total %access public export data Charset : Type where UTF8 : Charset %name Charset charset
(* Attempt to do examples from the SEwB book *) Require Import List. Section Resources. Variable Elt : Set. Definition Res := list Elt. Variable eq_dec : forall (x y : Elt), {x = y} + {x <> y}. Definition free : forall (x:Elt) (rfree : Res), ~ In x rfree -> {rfree' : Res | In x rfree' /\ forall (y:Elt), x <> y -> In y rfree -> In y rfree'}. Proof. refine (fun (x : Elt) (rfree: Res) (p : ~In x rfree) => exist _ (x::rfree) _). firstorder. Defined. Fixpoint remove (a : Elt) (r : Res) {struct r} : Res := match r with | nil => nil | h::t => match eq_dec a h with | left _ => remove a t | right _ => h::(remove a t) end end. Lemma remove_correct : forall (x : Elt) (r : Res), ~ In x (remove x r). Proof. simple induction r. firstorder. intros. simpl. case (eq_dec x a). firstorder. firstorder. Defined. Hint Resolve remove_correct. Ltac case_eq_dec := match goal with | [ _ : _ |- context[eq_dec ?x ?y] ] => case (eq_dec x y) ; firstorder ; try subst ; intros ; try congruence end. Hint Extern 1 (In _ _) => case_eq_dec. Lemma remove_inv_neq : forall (x y : Elt) (r : Res), x <> y -> In y r -> In y (remove x r). Proof. simple induction r ; simpl ; eauto. Defined. Hint Resolve remove_inv_neq. Definition alloc : forall (x:Elt) (rfree : Res), In x rfree -> {rfree' : Res | ~In x rfree' /\ forall (y:Elt), x <> y -> In y rfree -> In y rfree'}. Proof. refine (fun (x : Elt) (rfree: Res) (p : In x rfree) => exist _ (remove x rfree) _). firstorder. Defined. End Resources. Require Import Coq.Sets.Constructive_sets. Section Res_Prop. Variable Elt : Set. Variable eq_dec : forall (x y : Elt), {x = y} + {x <> y}. Definition ResSet := Ensemble Elt. (* Implicit Arguments In [U]. *) Definition freeRes : forall (x:Elt) (rfree : ResSet), ~ In Elt rfree x -> sigT (fun (rfree' : ResSet) => In Elt rfree' x /\ forall (y:Elt), x <> y -> In Elt rfree y -> In Elt rfree' y). Proof. firstorder. refine (existT _ (Add Elt rfree x) _). firstorder. Defined. Definition allocRes : forall (x:Elt) (rfree : ResSet), In Elt rfree x -> sigT (fun (rfree' : ResSet) => ~ In Elt rfree' x /\ forall (y:Elt), x <> y -> In Elt rfree y -> In Elt rfree' y). Proof. firstorder. refine (existT _ (Subtract Elt rfree x) _). firstorder. Defined. End Res_Prop. Section. End.
{-# OPTIONS --without-K --safe #-} module Categories.Category.Discrete where -- Discrete Category. -- https://ncatlab.org/nlab/show/discrete+category -- says: -- A category is discrete if it is both a groupoid and a preorder. That is, -- every morphism should be invertible, any two parallel morphisms should be equal. -- The idea is that in a discrete category, no two distinct (nonisomorphic) objects -- are connectable by any path (morphism), and an object connects to itself only through -- its identity morphism. open import Level using (Level; suc; _⊔_) open import Categories.Category using (Category) open import Categories.Category.Groupoid using (IsGroupoid) record IsDiscrete {o ℓ e} (C : Category o ℓ e) : Set (o ⊔ ℓ ⊔ e) where open Category C using (Obj; _⇒_; _≈_) field isGroupoid : IsGroupoid C preorder : {A B : Obj} → (f g : A ⇒ B) → f ≈ g record DiscreteCategory (o ℓ e : Level) : Set (suc (o ⊔ ℓ ⊔ e)) where field category : Category o ℓ e isDiscrete : IsDiscrete category open IsDiscrete isDiscrete public
||| module Toolkit.Data.Graph.EdgeBounded.DegreeCommon import Decidable.Equality import Data.String import Data.List.Elem import Data.List.Quantifiers import Toolkit.Decidable.Do import Toolkit.Decidable.Informative import Toolkit.Data.Nat import Toolkit.Data.Pair import Toolkit.Data.List.Size import Toolkit.Data.List.Occurs.Does %default total namespace HasDegree public export data DegreeType = I | O public export record Error where constructor MkError vertexID : Nat degType : DegreeType values : Occurs.Error -- [ EOF ]
-- --------------------------------------------------------------- [ State.idr ] -- Module : Exercises.Test.State -- Description : Test covering the Chapter 12 exercises in Edwin Brady's -- book, "Type-Driven Development with Idris." -- --------------------------------------------------------------------- [ EOH ] module Exercises.Test.State import Exercises.State import Test.Helpers import Control.Monad.State import System import Data.Vect %hide Data.Vect.overLength %access export testIncrease : IO Bool testIncrease = "increase" `assertEqual'` ((), 94) $ runState (increase 5) 89 testCountEmpty : IO Bool testCountEmpty = "countEmpty" `assertEqual'` 7 $ execState (countEmpty testTree) 0 testCountEmptyNode : IO Bool testCountEmptyNode = "countEmptyNode" `assertEqual'` (7, 6) $ execState (countEmptyNode testTree) (0, 0) testUpdateGameState : IO Bool testUpdateGameState = do let command = updateGameState addCorrect rnds <- pure (randoms . fromInteger) <*> time (_, _, st) <- runCommand rnds initState command "updateGameState" `assertEqual'` 1 $ record { score->correct } st goodSite : Article goodSite = MkArticle "Good Page" "http://example.com/good" (MkVotes 101 7) badSite : Article badSite = MkArticle "Bad Page" "http://example.com/bad" (MkVotes 5 47) testGetScore : (article : Article) -> (expected : Integer) -> IO Bool testGetScore article expected = ("getScore " ++ title article) `assertEqual'` expected $ getScore article testAddUpvote : IO Bool testAddUpvote = "addUpvote" `assertEqual'` 102 $ record { score->upvotes } $ addUpvote goodSite testAddDownvote : IO Bool testAddDownvote = "addDownvote" `assertEqual'` 48 $ record { score->downvotes } $ addDownvote badSite allTests : List (IO Bool) allTests = [ testIncrease , testCountEmpty , testCountEmptyNode , testUpdateGameState , testGetScore goodSite 94 , testGetScore badSite (-42) , testAddUpvote , testAddDownvote ] runTests : IO (Vect (length State.allTests) Bool) runTests = testChapter "12: State" allTests -- --------------------------------------------------------------------- [ EOF ]
p := 5; # b(i) is the image in H_{2i}(QS^0) of the standard generator of H_{2i}(BC_p) # This is zero unless i is divisible by p-1. An expression like b(8,4,6) # represents the circle product of b(8), b(4) and b(6). b := proc() if map(mods,{0,args},p-1) <> {0} or min(0,args) < 0 then return(0); fi; 'b'(op(sort([args]))); end: # Signature of permutations of {1,...,n}, represented as lists of values. # Sends non-permutations to zero. signature := proc(s) local i,j,x; x := 1; for i from 1 to nops(s)-1 do for j from i+1 to nops(s) do if op(i,s) > op(j,s) then x := -x; elif op(i,s) = op(j,s) then return(0); fi; od; od; x; end: # a(i) is the image in H_{2i+1}(QS^0) of the standard generator of H_{2i+1}(BC_p) # This is zero unless i+1 is divisible by p-1. An expression like a(11,3,7) # represents the circle product of a(11), a(3) and a(7). a := proc() if map(modp,{-1,args},p-1) <> {p-2} or min(0,args) < 0 then return(0); fi; signature([args]) * 'a'(op(sort([args]))); end: # The elements b(i) satisfy \sum b(i,j) s^i t^j=\sum b(i,j) s^i (s+t)^j. # By expanding this out we see that b_rel(i,j) = 0 for all i and j, # where b_rel(i, j) is as defined below. b_rel := proc(i,j) add(mods(binomial(i+j-u,j),p) * b(u,i+j-u),u=0..i-1); end: b_rels := proc(d) [seq(b_rel(i,d-i),i=0..d)]; end: # The elements a(i) satisfy \sum a(i,j) s^i t^j=\sum a(i,j) s^i (s+t)^j. # By expanding this out we see that a_rel(i,j) = 0 for all i and j, # where a_rel(i, j) is as defined below. a_rel := proc(i,j) add(mods(binomial(i+j-u,j),p) * a(u,i+j-u),u=0..i-1); end: a_rels := proc(d) [seq(a_rel(i,d-i),i=0..d)]; end: # Degree function for expressions in a's, b's, P's and Q's. # Should be refactored to use apply_deg # Not sure what the P's and Q's are deg := proc(x) local d,n; if type(x,`+`) then d := map(deg,{op(x)}); if nops(d) = 1 then return(op(1,d)); else error("inhomogeneous sum"); fi; elif type(x,`*`) then return(`+`(op(map(deg,[op(x)])))); elif type(x,function) and op(0,x) = o then return(`+`(op(map(deg,[op(x)])))); elif type(x,integer) then return(0); elif type(x,function) and op(0,x) = a then return(`+`(op(map(i->2*i+1,[op(x)])))); elif type(x,function) and op(0,x) = b then return(`+`(op(map(i->2*i,[op(x)])))); elif type(x,function) and op(0,x) = P then n := nops(x)/2; return( -2*(p-1)*add(op(2*i,x),i=1..n) - add(op(2*i-1,x),i=1..n)); elif type(x,function) and op(0,x) = Q then n := nops(x)/2; return( 2*(p-1)*add(op(2*i,x),i=1..n) - add(op(2*i-1,x),i=1..n)); fi; end: # Circle product. Shoud be refactored to use apply_* o := proc() local xx; xx := map(mods,[args],p); if member(0,xx) then return(0); else return('o'(op(xx))); fi; end: # Bockstein operation. Recognises star and circle products, a's, b's and Q's beta := proc(x) local xx,n,s,y,i,j; if type(x,`+`) then return(map(beta,x)); elif type(x,`*`) then xx := [op(x)]; n := nops(xx); s := 1; y := 0; for i from 1 to n do y := y + s * mul(xx[j],j=1..(i-1)) * beta(xx[i]) * mul(xx[j],j=i+1..n); s := s * (-1)^deg(xx[i]); od; return(mods(expand(y),p)); elif type(x,function) and op(0,x) = o then xx := [op(x)]; n := nops(xx); s := 1; y := 0; for i from 1 to n do y := y + s * o(seq(xx[j],j=1..(i-1)),beta(xx[i]),seq(xx[j],j=i+1..n)); s := s * (-1)^deg(xx[i]); od; return(mods(expand(y),p)); elif type(x,integer) then return(0); elif type(x,function) and op(0,x) = a then return(0); elif type(x,function) and op(0,x) = b then xx := [op(x)]; n := nops(xx); y := 0; for i from 1 to n do if xx[i] > 0 then y := y + o(a(xx[i]-1),b(seq(xx[j],j=1..i-1),seq(xx[j],j=i+1..n))); fi; od; return(mods(expand(y),p)); elif type(x,function) and op(0,x) = Q then if nops(x) = 0 or op(1,x) = 1 then return(0); fi; return(Q(1,op(2..-1,x))); else return('beta'(x)); fi; end: # Dyer-Lashof operation. Only knows linearity and the Cartan rule QQ := proc(i,x) local y,z; if type(x,`+`) then return(map2(QQ,i,x)); elif type(x,`*`) then y := op(1,x); z := `*`(op(2..-1,x)); if type(y,integer) then return(mods(expand(y*QQ(i,z)),p)); else return(mods(expand(add(QQ(j,y)*QQ(i-j,z),j=0..i)),p)); fi; elif type(x,integer) then if i = 0 then return(x); else return(0); fi; else return('QQ'(i,x)); fi; end: # Steenrod operation. Knows the Cartan rule for star and circle products, # and behaviour on a's, b's and Q's. PP := proc(i,x) local y,z,j,s; if i<0 then return(0); elif i=0 then return(x); elif type(x,`+`) then return(map2(PP,i,x)); elif type(x,`*`) then y := op(1,x); z := `*`(op(2..-1,x)); if type(y,integer) then return(mods(expand(y*PP(i,z)),p)); else return(mods(expand(add(PP(j,y)*PP(i-j,z),j=0..i)),p)); fi; elif type(x,function) and op(0,x) = o then y := op(1,x); z := o(op(2..-1,x)); if type(y,integer) then return(mods(expand(y * PP(i,z)),p)); else return(mods(expand(add(o(PP(j,y),PP(i-j,z)),j=0..i)),p)); fi; elif type(x,integer) then if i = 0 then return(x); else return(0); fi; elif type(x,function) and op(0,x) = b then j := op(1,x); if nops(x) = 1 then return(mods(binomial(j-(p-1)*i,i),p)*b(j-(p-1)*i)); else z := b(op(2..-1,x)); return(mods(expand(add(binomial(j-(p-1)*k,k)*o(b(j-(p-1)*k),PP(i-k,z)),k=0..j/(p-1))),p)); fi; elif type(x,function) and op(0,x) = a then j := op(1,x); if nops(x) = 1 then return(mods(binomial(j-(p-1)*i,i),p)*a(j-(p-1)*i)); else z := a(op(2..-1,x)); return(mods(expand(add(binomial(j-(p-1)*k,k)*o(a(j-(p-1)*k),PP(i-k,z)),k=0..j/(p-1))),p)); fi; elif type(x,function) and op(0,x) = Q then if nops(x) = 0 then if i=0 then return(x) else return(0); fi; fi; s := op(2,x); y := Q(op(3..-1,x)); if op(1,x) = 0 then return(add((-1)^(i+k)*binomial((s-i)*(p-1),i-p*k)*oQ(Q(0,s-i+k),PP(k,y)),k=0..i/p)); else return(zap( add((-1)^(i+k)*binomial((s-i)*(p-1)-1,i-p*k)*oQ(Q(1,s-i+k),PP(k,y)),k=0..i/p) + add((-1)^(i+k)*binomial((s-i)*(p-1)-1,i-p*k-1)*oQ(Q(0,s-i+k),PP(k,beta(y))),k=0..i/p) )); fi; else return('PP'(i,x)); fi; end: # Length function for Steenrod or Dyer-Lashof words. len := proc(x) if type(x,function) and (op(0,x) = P or op(0,x) = Q) then return(nops(x)/2); else return('len'(x)); fi; end: # Excess for Dyer-Lashof words excess := proc(x) local n; if type(x,function) and op(0,x) = Q then n := nops(x)/2; if n = 0 then return(0); fi; return(2*op(2,x) - op(1,x) - add(2*(p-1)*op(2*i,x)-op(2*i-1,x),i=2..n)); else return('excess'(x)); fi; end: # Admissibility criterion for Dyer-Lashof words is_admissible := proc(x) local i,n; if type(x,function) and op(0,x) = Q then n := nops(x)/2; if n = 0 then return(true); fi; if op(2,x) < op(1,x) then return(false); fi; for i from 2 to n do if p*op(2*i,x) - op(2*i-1,x) < op(2*i-2,x) then return(false); fi; od; return(true); else return('is_admissible'(x)); fi; end: Q_adem := proc() local i,j,u,ep,r,dl,s,v; if nargs = 0 then return(Q()); fi; if args[2] < args[1] then # (we must have args[1] = 1, args[2] = 0) if nargs = 2 then # error("naked beta"); return(Q(1,0)); fi; if args[3] = 1 then return(0); else return(Q(1,args[4..-1])); fi; fi; for i from 2 to nargs/2 do u := args[1..2*i-4]; ep := args[2*i-3]; r := args[2*i-2]; dl := args[2*i-1]; s := args[2*i ]; v := args[2*i+1..-1]; if r > p*s-dl then if dl = 0 then return( mods(add( (-1)^(r+j)*binomial((p-1)*(j-s)-1,p*j-r)* Q(u,ep,r+s-j,0,j,v), j=ceil(r/p)..(r-(p-1)*s-1) ),p) ); else if ep = 0 then return(mods(add( (-1)^(r+j)*binomial((p-1)*(j-s),p*j-r)* Q(u,1,r+s-j,0,j,v), j=ceil(r/p)..(r-(p-1)*s) ),p) - mods(add( (-1)^(r+j)*binomial((p-1)*(j-s)-1,p*j-r-1)* Q(u,0,r+s-j,1,j,v), j = ceil((r+1)/p)..(r-(p-1)*s) ),p)); else return(mods(add( (-1)^(r+j+1)*binomial((p-1)*(j-s)-1,p*j-r-1)* Q(u,1,r+s-j,1,j,v), j = ceil((r+1)/p)..(r-(p-1)*s) ),p)); fi; fi; fi; od; return(Q(args)); end: Q_exc0 := proc() if excess(Q(args)) < 0 then return(0); else return(Q(args)); fi; end: Q_comp := proc(a,b) local aa,bb,n,m,i,d; aa := a; bb := b; if type(aa,`*`) then aa := select(type,a,specfunc(integer,Q)); fi; if type(bb,`*`) then bb := select(type,b,specfunc(integer,Q)); fi; if not(type([aa,bb],[specfunc(integer,Q)$2])) then error("invalid arguments"); fi; n := nops(aa)/2; m := nops(bb)/2; for i from 1 to min(n,m) do d := 2*op(2*i,aa) - op(2*i-1,aa) - 2*op(2*i,bb) + op(2*i-1,bb); if d < 0 then return(true); elif d > 0 then return(false); fi; od; if n<m then return(true); fi; return(false); end: Q_terms := proc(x) if type(x,specfunc(integer,Q)) then return([x]); elif type(x,`*`) then return(select(type,[op(x)],specfunc(integer,Q))); elif type(x,`+`) then return(map(op,map(Q_terms,[op(x)]))); else return([]); fi; end: Q_bot := proc(x) local t; t := sort(Q_terms(x),Q_comp); if t = [] then return(0); else return(t[1]); fi; end: Q_top := proc(x) local t; t := sort(Q_terms(x),Q_comp); if t = [] then return(0); else return(t[nops(t)]); fi; end: oQ := proc(a,b) local n,aa,bb; if type(a,`+`) then return(map(oQ,a,b)); elif type(b,`+`) then return(map2(oQ,a,b)); fi; if type(a,`*`) then n,aa := selectremove(type,a,integer); if n<>1 then return(expand(n*oQ(aa,b))); fi; fi; if type(b,`*`) then n,bb := selectremove(type,b,integer); if n<> 1 then return(expand(n*oQ(a,bb))); fi; fi; if type(a,integer) or type(b,integer) then return(expand(a*b)); fi; if type(a,specfunc(integer,Q)) and type(b,specfunc(integer,Q)) then return(Q(op(a),op(b))); fi; end: zap := proc(x) mods(eval(subs(Q=Q_exc0,eval(subs(Q = Q_adem,x)))),p); end:
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Yaël Dillies -/ import data.set.pointwise import order.filter.n_ary import order.filter.ultrafilter /-! # Pointwise operations on filters This file defines pointwise operations on filters. This is useful because usual algebraic operations distribute over pointwise operations. For example, * `(f₁ * f₂).map m = f₁.map m * f₂.map m` * `𝓝 (x * y) = 𝓝 x * 𝓝 y` ## Main declarations * `0` (`filter.has_zero`): Pure filter at `0 : α`, or alternatively principal filter at `0 : set α`. * `1` (`filter.has_one`): Pure filter at `1 : α`, or alternatively principal filter at `1 : set α`. * `f + g` (`filter.has_add`): Addition, filter generated by all `s + t` where `s ∈ f` and `t ∈ g`. * `f * g` (`filter.has_mul`): Multiplication, filter generated by all `s * t` where `s ∈ f` and `t ∈ g`. * `-f` (`filter.has_neg`): Negation, filter of all `-s` where `s ∈ f`. * `f⁻¹` (`filter.has_inv`): Inversion, filter of all `s⁻¹` where `s ∈ f`. * `f - g` (`filter.has_sub`): Subtraction, filter generated by all `s - t` where `s ∈ f` and `t ∈ g`. * `f / g` (`filter.has_div`): Division, filter generated by all `s / t` where `s ∈ f` and `t ∈ g`. * `f +ᵥ g` (`filter.has_vadd`): Scalar addition, filter generated by all `s +ᵥ t` where `s ∈ f` and `t ∈ g`. * `f -ᵥ g` (`filter.has_vsub`): Scalar subtraction, filter generated by all `s -ᵥ t` where `s ∈ f` and `t ∈ g`. * `f • g` (`filter.has_smul`): Scalar multiplication, filter generated by all `s • t` where `s ∈ f` and `t ∈ g`. * `a +ᵥ f` (`filter.has_vadd_filter`): Translation, filter of all `a +ᵥ s` where `s ∈ f`. * `a • f` (`filter.has_smul_filter`): Scaling, filter of all `a • s` where `s ∈ f`. For `α` a semigroup/monoid, `filter α` is a semigroup/monoid. As an unfortunate side effect, this means that `n • f`, where `n : ℕ`, is ambiguous between pointwise scaling and repeated pointwise addition. See note [pointwise nat action]. ## Implementation notes We put all instances in the locale `pointwise`, so that these instances are not available by default. Note that we do not mark them as reducible (as argued by note [reducible non-instances]) since we expect the locale to be open whenever the instances are actually used (and making the instances reducible changes the behavior of `simp`. ## Tags filter multiplication, filter addition, pointwise addition, pointwise multiplication, -/ open function set open_locale filter pointwise variables {F α β γ δ ε : Type*} namespace filter /-! ### `0`/`1` as filters -/ section has_one variables [has_one α] {f : filter α} {s : set α} /-- `1 : filter α` is defined as the filter of sets containing `1 : α` in locale `pointwise`. -/ @[to_additive "`0 : filter α` is defined as the filter of sets containing `0 : α` in locale `pointwise`."] protected def has_one : has_one (filter α) := ⟨pure 1⟩ localized "attribute [instance] filter.has_one filter.has_zero" in pointwise @[simp, to_additive] lemma mem_one : s ∈ (1 : filter α) ↔ (1 : α) ∈ s := mem_pure @[to_additive] lemma one_mem_one : (1 : set α) ∈ (1 : filter α) := mem_pure.2 one_mem_one @[simp, to_additive] lemma pure_one : pure 1 = (1 : filter α) := rfl @[simp, to_additive] lemma principal_one : 𝓟 1 = (1 : filter α) := principal_singleton _ @[to_additive] lemma one_ne_bot : (1 : filter α).ne_bot := filter.pure_ne_bot @[simp, to_additive] protected lemma map_one' (f : α → β) : (1 : filter α).map f = pure (f 1) := rfl @[simp, to_additive] lemma le_one_iff : f ≤ 1 ↔ (1 : set α) ∈ f := le_pure_iff @[to_additive] protected lemma ne_bot.le_one_iff (h : f.ne_bot) : f ≤ 1 ↔ f = 1 := h.le_pure_iff @[simp, to_additive] lemma eventually_one {p : α → Prop} : (∀ᶠ x in 1, p x) ↔ p 1 := eventually_pure @[simp, to_additive] lemma tendsto_one {a : filter β} {f : β → α} : tendsto f a 1 ↔ ∀ᶠ x in a, f x = 1 := tendsto_pure /-- `pure` as a `one_hom`. -/ @[to_additive "`pure` as a `zero_hom`."] def pure_one_hom : one_hom α (filter α) := ⟨pure, pure_one⟩ @[simp, to_additive] lemma coe_pure_one_hom : (pure_one_hom : α → filter α) = pure := rfl @[simp, to_additive] lemma pure_one_hom_apply (a : α) : pure_one_hom a = pure a := rfl variables [has_one β] @[simp, to_additive] protected lemma map_one [one_hom_class F α β] (φ : F) : map φ 1 = 1 := by rw [filter.map_one', map_one, pure_one] end has_one /-! ### Filter negation/inversion -/ section has_inv variables [has_inv α] {f g : filter α} {s : set α} {a : α} /-- The inverse of a filter is the pointwise preimage under `⁻¹` of its sets. -/ @[to_additive "The negation of a filter is the pointwise preimage under `-` of its sets."] instance : has_inv (filter α) := ⟨map has_inv.inv⟩ @[simp, to_additive] protected lemma map_inv : f.map has_inv.inv = f⁻¹ := rfl @[to_additive] lemma mem_inv : s ∈ f⁻¹ ↔ has_inv.inv ⁻¹' s ∈ f := iff.rfl @[to_additive] protected lemma inv_le_inv (hf : f ≤ g) : f⁻¹ ≤ g⁻¹ := map_mono hf @[simp, to_additive] lemma inv_pure : (pure a : filter α)⁻¹ = pure a⁻¹ := rfl @[simp, to_additive] lemma inv_eq_bot_iff : f⁻¹ = ⊥ ↔ f = ⊥ := map_eq_bot_iff @[simp, to_additive] lemma ne_bot_inv_iff : f⁻¹.ne_bot ↔ ne_bot f := map_ne_bot_iff _ @[to_additive] lemma ne_bot.inv : f.ne_bot → f⁻¹.ne_bot := λ h, h.map _ end has_inv section has_involutive_inv variables [has_involutive_inv α] {f : filter α} {s : set α} @[to_additive] lemma inv_mem_inv (hs : s ∈ f) : s⁻¹ ∈ f⁻¹ := by rwa [mem_inv, inv_preimage, inv_inv] /-- Inversion is involutive on `filter α` if it is on `α`. -/ @[to_additive "Negation is involutive on `filter α` if it is on `α`."] protected def has_involutive_inv : has_involutive_inv (filter α) := { inv_inv := λ f, map_map.trans $ by rw [inv_involutive.comp_self, map_id], ..filter.has_inv } end has_involutive_inv /-! ### Filter addition/multiplication -/ section has_mul variables [has_mul α] [has_mul β] {f f₁ f₂ g g₁ g₂ h : filter α} {s t : set α} {a b : α} /-- The filter `f * g` is generated by `{s * t | s ∈ f, t ∈ g}` in locale `pointwise`. -/ @[to_additive "The filter `f + g` is generated by `{s + t | s ∈ f, t ∈ g}` in locale `pointwise`."] protected def has_mul : has_mul (filter α) := /- This is defeq to `map₂ (*) f g`, but the hypothesis unfolds to `t₁ * t₂ ⊆ s` rather than all the way to `set.image2 (*) t₁ t₂ ⊆ s`. -/ ⟨λ f g, { sets := {s | ∃ t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ * t₂ ⊆ s}, ..map₂ (*) f g }⟩ localized "attribute [instance] filter.has_mul filter.has_add" in pointwise @[simp, to_additive] lemma map₂_mul : map₂ (*) f g = f * g := rfl @[to_additive] lemma mem_mul : s ∈ f * g ↔ ∃ t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ * t₂ ⊆ s := iff.rfl @[to_additive] lemma mul_mem_mul : s ∈ f → t ∈ g → s * t ∈ f * g := image2_mem_map₂ @[simp, to_additive] lemma bot_mul : ⊥ * g = ⊥ := map₂_bot_left @[simp, to_additive] lemma mul_bot : f * ⊥ = ⊥ := map₂_bot_right @[simp, to_additive] lemma mul_eq_bot_iff : f * g = ⊥ ↔ f = ⊥ ∨ g = ⊥ := map₂_eq_bot_iff @[simp, to_additive] lemma mul_ne_bot_iff : (f * g).ne_bot ↔ f.ne_bot ∧ g.ne_bot := map₂_ne_bot_iff @[to_additive] lemma ne_bot.mul : ne_bot f → ne_bot g → ne_bot (f * g) := ne_bot.map₂ @[to_additive] lemma ne_bot.of_mul_left : (f * g).ne_bot → f.ne_bot := ne_bot.of_map₂_left @[to_additive] lemma ne_bot.of_mul_right : (f * g).ne_bot → g.ne_bot := ne_bot.of_map₂_right @[simp, to_additive] lemma pure_mul : pure a * g = g.map ((*) a) := map₂_pure_left @[simp, to_additive] lemma mul_pure : f * pure b = f.map (* b) := map₂_pure_right @[simp, to_additive] lemma pure_mul_pure : (pure a : filter α) * pure b = pure (a * b) := map₂_pure @[simp, to_additive] lemma le_mul_iff : h ≤ f * g ↔ ∀ ⦃s⦄, s ∈ f → ∀ ⦃t⦄, t ∈ g → s * t ∈ h := le_map₂_iff @[to_additive] instance covariant_mul : covariant_class (filter α) (filter α) (*) (≤) := ⟨λ f g h, map₂_mono_left⟩ @[to_additive] instance covariant_swap_mul : covariant_class (filter α) (filter α) (swap (*)) (≤) := ⟨λ f g h, map₂_mono_right⟩ @[to_additive] protected lemma map_mul [mul_hom_class F α β] (m : F) : (f₁ * f₂).map m = f₁.map m * f₂.map m := map_map₂_distrib $ map_mul m /-- `pure` operation as a `mul_hom`. -/ @[to_additive "The singleton operation as an `add_hom`."] def pure_mul_hom : α →ₙ* filter α := ⟨pure, λ a b, pure_mul_pure.symm⟩ @[simp, to_additive] lemma coe_pure_mul_hom : (pure_mul_hom : α → filter α) = pure := rfl @[simp, to_additive] lemma pure_mul_hom_apply (a : α) : pure_mul_hom a = pure a := rfl end has_mul /-! ### Filter subtraction/division -/ section div variables [has_div α] {f f₁ f₂ g g₁ g₂ h : filter α} {s t : set α} {a b : α} /-- The filter `f / g` is generated by `{s / t | s ∈ f, t ∈ g}` in locale `pointwise`. -/ @[to_additive "The filter `f - g` is generated by `{s - t | s ∈ f, t ∈ g}` in locale `pointwise`."] protected def has_div : has_div (filter α) := /- This is defeq to `map₂ (/) f g`, but the hypothesis unfolds to `t₁ / t₂ ⊆ s` rather than all the way to `set.image2 (/) t₁ t₂ ⊆ s`. -/ ⟨λ f g, { sets := {s | ∃ t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ / t₂ ⊆ s}, ..map₂ (/) f g }⟩ localized "attribute [instance] filter.has_div filter.has_sub" in pointwise @[simp, to_additive] lemma map₂_div : map₂ (/) f g = f / g := rfl @[to_additive] lemma mem_div : s ∈ f / g ↔ ∃ t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ / t₂ ⊆ s := iff.rfl @[to_additive] lemma div_mem_div : s ∈ f → t ∈ g → s / t ∈ f / g := image2_mem_map₂ @[simp, to_additive] lemma bot_div : ⊥ / g = ⊥ := map₂_bot_left @[simp, to_additive] lemma div_bot : f / ⊥ = ⊥ := map₂_bot_right @[simp, to_additive] lemma div_eq_bot_iff : f / g = ⊥ ↔ f = ⊥ ∨ g = ⊥ := map₂_eq_bot_iff @[simp, to_additive] lemma div_ne_bot_iff : (f / g).ne_bot ↔ f.ne_bot ∧ g.ne_bot := map₂_ne_bot_iff @[to_additive] lemma ne_bot.div : ne_bot f → ne_bot g → ne_bot (f / g) := ne_bot.map₂ @[to_additive] lemma ne_bot.of_div_left : (f / g).ne_bot → f.ne_bot := ne_bot.of_map₂_left @[to_additive] lemma ne_bot.of_div_right : (f / g).ne_bot → g.ne_bot := ne_bot.of_map₂_right @[simp, to_additive] lemma pure_div : pure a / g = g.map ((/) a) := map₂_pure_left @[simp, to_additive] lemma div_pure : f / pure b = f.map (/ b) := map₂_pure_right @[simp, to_additive] lemma pure_div_pure : (pure a : filter α) / pure b = pure (a / b) := map₂_pure @[to_additive] protected lemma div_le_div : f₁ ≤ f₂ → g₁ ≤ g₂ → f₁ / g₁ ≤ f₂ / g₂ := map₂_mono @[to_additive] protected lemma div_le_div_left : g₁ ≤ g₂ → f / g₁ ≤ f / g₂ := map₂_mono_left @[to_additive] protected lemma div_le_div_right : f₁ ≤ f₂ → f₁ / g ≤ f₂ / g := map₂_mono_right @[simp, to_additive] protected lemma le_div_iff : h ≤ f / g ↔ ∀ ⦃s⦄, s ∈ f → ∀ ⦃t⦄, t ∈ g → s / t ∈ h := le_map₂_iff @[to_additive] instance covariant_div : covariant_class (filter α) (filter α) (/) (≤) := ⟨λ f g h, map₂_mono_left⟩ @[to_additive] instance covariant_swap_div : covariant_class (filter α) (filter α) (swap (/)) (≤) := ⟨λ f g h, map₂_mono_right⟩ end div open_locale pointwise /-- Repeated pointwise addition (not the same as pointwise repeated addition!) of a `filter`. See Note [pointwise nat action].-/ protected def has_nsmul [has_zero α] [has_add α] : has_smul ℕ (filter α) := ⟨nsmul_rec⟩ /-- Repeated pointwise multiplication (not the same as pointwise repeated multiplication!) of a `filter`. See Note [pointwise nat action]. -/ @[to_additive] protected def has_npow [has_one α] [has_mul α] : has_pow (filter α) ℕ := ⟨λ s n, npow_rec n s⟩ /-- Repeated pointwise addition/subtraction (not the same as pointwise repeated addition/subtraction!) of a `filter`. See Note [pointwise nat action]. -/ protected def has_zsmul [has_zero α] [has_add α] [has_neg α] : has_smul ℤ (filter α) := ⟨zsmul_rec⟩ /-- Repeated pointwise multiplication/division (not the same as pointwise repeated multiplication/division!) of a `filter`. See Note [pointwise nat action]. -/ @[to_additive] protected def has_zpow [has_one α] [has_mul α] [has_inv α] : has_pow (filter α) ℤ := ⟨λ s n, zpow_rec n s⟩ localized "attribute [instance] filter.has_nsmul filter.has_npow filter.has_zsmul filter.has_zpow" in pointwise /-- `filter α` is a `semigroup` under pointwise operations if `α` is.-/ @[to_additive "`filter α` is an `add_semigroup` under pointwise operations if `α` is."] protected def semigroup [semigroup α] : semigroup (filter α) := { mul := (*), mul_assoc := λ f g h, map₂_assoc mul_assoc } /-- `filter α` is a `comm_semigroup` under pointwise operations if `α` is. -/ @[to_additive "`filter α` is an `add_comm_semigroup` under pointwise operations if `α` is."] protected def comm_semigroup [comm_semigroup α] : comm_semigroup (filter α) := { mul_comm := λ f g, map₂_comm mul_comm, ..filter.semigroup } section mul_one_class variables [mul_one_class α] [mul_one_class β] /-- `filter α` is a `mul_one_class` under pointwise operations if `α` is. -/ @[to_additive "`filter α` is an `add_zero_class` under pointwise operations if `α` is."] protected def mul_one_class : mul_one_class (filter α) := { one := 1, mul := (*), one_mul := λ f, by simp only [←pure_one, ←map₂_mul, map₂_pure_left, one_mul, map_id'], mul_one := λ f, by simp only [←pure_one, ←map₂_mul, map₂_pure_right, mul_one, map_id'] } localized "attribute [instance] filter.semigroup filter.add_semigroup filter.comm_semigroup filter.add_comm_semigroup filter.mul_one_class filter.add_zero_class" in pointwise /-- If `φ : α →* β` then `map_monoid_hom φ` is the monoid homomorphism `filter α →* filter β` induced by `map φ`. -/ @[to_additive "If `φ : α →+ β` then `map_add_monoid_hom φ` is the monoid homomorphism `filter α →+ filter β` induced by `map φ`."] def map_monoid_hom [monoid_hom_class F α β] (φ : F) : filter α →* filter β := { to_fun := map φ, map_one' := filter.map_one φ, map_mul' := λ _ _, filter.map_mul φ } -- The other direction does not hold in general @[to_additive] lemma comap_mul_comap_le [mul_hom_class F α β] (m : F) {f g : filter β} : f.comap m * g.comap m ≤ (f * g).comap m := λ s ⟨t, ⟨t₁, t₂, ht₁, ht₂, t₁t₂⟩, mt⟩, ⟨m ⁻¹' t₁, m ⁻¹' t₂, ⟨t₁, ht₁, subset.rfl⟩, ⟨t₂, ht₂, subset.rfl⟩, (preimage_mul_preimage_subset _).trans $ (preimage_mono t₁t₂).trans mt⟩ @[to_additive] lemma tendsto.mul_mul [mul_hom_class F α β] (m : F) {f₁ g₁ : filter α} {f₂ g₂ : filter β} : tendsto m f₁ f₂ → tendsto m g₁ g₂ → tendsto m (f₁ * g₁) (f₂ * g₂) := λ hf hg, (filter.map_mul m).trans_le $ mul_le_mul' hf hg /-- `pure` as a `monoid_hom`. -/ @[to_additive "`pure` as an `add_monoid_hom`."] def pure_monoid_hom : α →* filter α := { ..pure_mul_hom, ..pure_one_hom } @[simp, to_additive] lemma coe_pure_monoid_hom : (pure_monoid_hom : α → filter α) = pure := rfl @[simp, to_additive] lemma pure_monoid_hom_apply (a : α) : pure_monoid_hom a = pure a := rfl end mul_one_class section monoid variables [monoid α] {f g : filter α} {s : set α} {a : α} {m n : ℕ} /-- `filter α` is a `monoid` under pointwise operations if `α` is. -/ @[to_additive "`filter α` is an `add_monoid` under pointwise operations if `α` is."] protected def monoid : monoid (filter α) := { ..filter.mul_one_class, ..filter.semigroup, ..filter.has_npow } localized "attribute [instance] filter.monoid filter.add_monoid" in pointwise @[to_additive] lemma pow_mem_pow (hs : s ∈ f) : ∀ n : ℕ, s ^ n ∈ f ^ n | 0 := by { rw pow_zero, exact one_mem_one } | (n + 1) := by { rw pow_succ, exact mul_mem_mul hs (pow_mem_pow _) } @[simp, to_additive nsmul_bot] lemma bot_pow {n : ℕ} (hn : n ≠ 0) : (⊥ : filter α) ^ n = ⊥ := by rw [←tsub_add_cancel_of_le (nat.succ_le_of_lt $ nat.pos_of_ne_zero hn), pow_succ, bot_mul] @[to_additive] lemma mul_top_of_one_le (hf : 1 ≤ f) : f * ⊤ = ⊤ := begin refine top_le_iff.1 (λ s, _), simp only [mem_mul, mem_top, exists_and_distrib_left, exists_eq_left], rintro ⟨t, ht, hs⟩, rwa [mul_univ_of_one_mem (mem_one.1 $ hf ht), univ_subset_iff] at hs, end @[to_additive] lemma top_mul_of_one_le (hf : 1 ≤ f) : ⊤ * f = ⊤ := begin refine top_le_iff.1 (λ s, _), simp only [mem_mul, mem_top, exists_and_distrib_left, exists_eq_left], rintro ⟨t, ht, hs⟩, rwa [univ_mul_of_one_mem (mem_one.1 $ hf ht), univ_subset_iff] at hs, end @[simp, to_additive] lemma top_mul_top : (⊤ : filter α) * ⊤ = ⊤ := mul_top_of_one_le le_top --TODO: `to_additive` trips up on the `1 : ℕ` used in the pattern-matching. lemma nsmul_top {α : Type*} [add_monoid α] : ∀ {n : ℕ}, n ≠ 0 → n • (⊤ : filter α) = ⊤ | 0 := λ h, (h rfl).elim | 1 := λ _, one_nsmul _ | (n + 2) := λ _, by { rw [succ_nsmul, nsmul_top n.succ_ne_zero, top_add_top] } @[to_additive nsmul_top] lemma top_pow : ∀ {n : ℕ}, n ≠ 0 → (⊤ : filter α) ^ n = ⊤ | 0 := λ h, (h rfl).elim | 1 := λ _, pow_one _ | (n + 2) := λ _, by { rw [pow_succ, top_pow n.succ_ne_zero, top_mul_top] } @[to_additive] protected lemma _root_.is_unit.filter : is_unit a → is_unit (pure a : filter α) := is_unit.map (pure_monoid_hom : α →* filter α) end monoid /-- `filter α` is a `comm_monoid` under pointwise operations if `α` is. -/ @[to_additive "`filter α` is an `add_comm_monoid` under pointwise operations if `α` is."] protected def comm_monoid [comm_monoid α] : comm_monoid (filter α) := { ..filter.mul_one_class, ..filter.comm_semigroup } open_locale pointwise section division_monoid variables [division_monoid α] {f g : filter α} @[to_additive] protected lemma mul_eq_one_iff : f * g = 1 ↔ ∃ a b, f = pure a ∧ g = pure b ∧ a * b = 1 := begin refine ⟨λ hfg, _, _⟩, { obtain ⟨t₁, t₂, h₁, h₂, h⟩ : (1 : set α) ∈ f * g := hfg.symm.subst one_mem_one, have hfg : (f * g).ne_bot := hfg.symm.subst one_ne_bot, rw [(hfg.nonempty_of_mem $ mul_mem_mul h₁ h₂).subset_one_iff, set.mul_eq_one_iff] at h, obtain ⟨a, b, rfl, rfl, h⟩ := h, refine ⟨a, b, _, _, h⟩, { rwa [←hfg.of_mul_left.le_pure_iff, le_pure_iff] }, { rwa [←hfg.of_mul_right.le_pure_iff, le_pure_iff] } }, { rintro ⟨a, b, rfl, rfl, h⟩, rw [pure_mul_pure, h, pure_one] } end /-- `filter α` is a division monoid under pointwise operations if `α` is. -/ @[to_additive subtraction_monoid "`filter α` is a subtraction monoid under pointwise operations if `α` is."] protected def division_monoid : division_monoid (filter α) := { mul_inv_rev := λ s t, map_map₂_antidistrib mul_inv_rev, inv_eq_of_mul := λ s t h, begin obtain ⟨a, b, rfl, rfl, hab⟩ := filter.mul_eq_one_iff.1 h, rw [inv_pure, inv_eq_of_mul_eq_one_right hab], end, div_eq_mul_inv := λ f g, map_map₂_distrib_right div_eq_mul_inv, ..filter.monoid, ..filter.has_involutive_inv, ..filter.has_div, ..filter.has_zpow } @[to_additive] lemma is_unit_iff : is_unit f ↔ ∃ a, f = pure a ∧ is_unit a := begin split, { rintro ⟨u, rfl⟩, obtain ⟨a, b, ha, hb, h⟩ := filter.mul_eq_one_iff.1 u.mul_inv, refine ⟨a, ha, ⟨a, b, h, pure_injective _⟩, rfl⟩, rw [←pure_mul_pure, ←ha, ←hb], exact u.inv_mul }, { rintro ⟨a, rfl, ha⟩, exact ha.filter } end end division_monoid /-- `filter α` is a commutative division monoid under pointwise operations if `α` is. -/ @[to_additive subtraction_comm_monoid "`filter α` is a commutative subtraction monoid under pointwise operations if `α` is."] protected def division_comm_monoid [division_comm_monoid α] : division_comm_monoid (filter α) := { ..filter.division_monoid, ..filter.comm_semigroup } /-- `filter α` has distributive negation if `α` has. -/ protected def has_distrib_neg [has_mul α] [has_distrib_neg α] : has_distrib_neg (filter α) := { neg_mul := λ _ _, map₂_map_left_comm neg_mul, mul_neg := λ _ _, map_map₂_right_comm mul_neg, ..filter.has_involutive_neg } localized "attribute [instance] filter.comm_monoid filter.add_comm_monoid filter.division_monoid filter.subtraction_monoid filter.division_comm_monoid filter.subtraction_comm_monoid filter.has_distrib_neg" in pointwise section distrib variables [distrib α] {f g h : filter α} /-! Note that `filter α` is not a `distrib` because `f * g + f * h` has cross terms that `f * (g + h)` lacks. -/ lemma mul_add_subset : f * (g + h) ≤ f * g + f * h := map₂_distrib_le_left mul_add lemma add_mul_subset : (f + g) * h ≤ f * h + g * h := map₂_distrib_le_right add_mul end distrib section mul_zero_class variables [mul_zero_class α] {f g : filter α} /-! Note that `filter` is not a `mul_zero_class` because `0 * ⊥ ≠ 0`. -/ lemma ne_bot.mul_zero_nonneg (hf : f.ne_bot) : 0 ≤ f * 0 := le_mul_iff.2 $ λ t₁ h₁ t₂ h₂, let ⟨a, ha⟩ := hf.nonempty_of_mem h₁ in ⟨_, _, ha, h₂, mul_zero _⟩ lemma ne_bot.zero_mul_nonneg (hg : g.ne_bot) : 0 ≤ 0 * g := le_mul_iff.2 $ λ t₁ h₁ t₂ h₂, let ⟨b, hb⟩ := hg.nonempty_of_mem h₂ in ⟨_, _, h₁, hb, zero_mul _⟩ end mul_zero_class section group variables [group α] [division_monoid β] [monoid_hom_class F α β] (m : F) {f g f₁ g₁ : filter α} {f₂ g₂ : filter β} /-! Note that `filter α` is not a group because `f / f ≠ 1` in general -/ @[simp, to_additive] protected lemma one_le_div_iff : 1 ≤ f / g ↔ ¬ disjoint f g := begin refine ⟨λ h hfg, _, _⟩, { obtain ⟨s, hs, t, ht, hst⟩ := hfg (mem_bot : ∅ ∈ ⊥), exact set.one_mem_div_iff.1 (h $ div_mem_div hs ht) (disjoint_iff.2 hst.symm) }, { rintro h s ⟨t₁, t₂, h₁, h₂, hs⟩, exact hs (set.one_mem_div_iff.2 $ λ ht, h $ disjoint_of_disjoint_of_mem ht h₁ h₂) } end @[to_additive] lemma not_one_le_div_iff : ¬ 1 ≤ f / g ↔ disjoint f g := filter.one_le_div_iff.not_left @[to_additive] lemma ne_bot.one_le_div (h : f.ne_bot) : 1 ≤ f / f := begin rintro s ⟨t₁, t₂, h₁, h₂, hs⟩, obtain ⟨a, ha₁, ha₂⟩ := set.not_disjoint_iff.1 (h.not_disjoint h₁ h₂), rw [mem_one, ←div_self' a], exact hs (set.div_mem_div ha₁ ha₂), end @[to_additive] lemma is_unit_pure (a : α) : is_unit (pure a : filter α) := (group.is_unit a).filter @[simp] lemma is_unit_iff_singleton : is_unit f ↔ ∃ a, f = pure a := by simp only [is_unit_iff, group.is_unit, and_true] include β @[to_additive] lemma map_inv' : f⁻¹.map m = (f.map m)⁻¹ := map_comm (funext $ map_inv m) _ @[to_additive] lemma tendsto.inv_inv : tendsto m f₁ f₂ → tendsto m f₁⁻¹ f₂⁻¹ := λ hf, (filter.map_inv' m).trans_le $ filter.inv_le_inv hf @[to_additive] protected lemma map_div : (f / g).map m = f.map m / g.map m := map_map₂_distrib $ map_div m @[to_additive] lemma tendsto.div_div : tendsto m f₁ f₂ → tendsto m g₁ g₂ → tendsto m (f₁ / g₁) (f₂ / g₂) := λ hf hg, (filter.map_div m).trans_le $ filter.div_le_div hf hg end group open_locale pointwise section group_with_zero variables [group_with_zero α] {f g : filter α} lemma ne_bot.div_zero_nonneg (hf : f.ne_bot) : 0 ≤ f / 0 := filter.le_div_iff.2 $ λ t₁ h₁ t₂ h₂, let ⟨a, ha⟩ := hf.nonempty_of_mem h₁ in ⟨_, _, ha, h₂, div_zero _⟩ lemma ne_bot.zero_div_nonneg (hg : g.ne_bot) : 0 ≤ 0 / g := filter.le_div_iff.2 $ λ t₁ h₁ t₂ h₂, let ⟨b, hb⟩ := hg.nonempty_of_mem h₂ in ⟨_, _, h₁, hb, zero_div _⟩ end group_with_zero /-! ### Scalar addition/multiplication of filters -/ section smul variables [has_smul α β] {f f₁ f₂ : filter α} {g g₁ g₂ h : filter β} {s : set α} {t : set β} {a : α} {b : β} /-- The filter `f • g` is generated by `{s • t | s ∈ f, t ∈ g}` in locale `pointwise`. -/ @[to_additive filter.has_vadd "The filter `f +ᵥ g` is generated by `{s +ᵥ t | s ∈ f, t ∈ g}` in locale `pointwise`."] protected def has_smul : has_smul (filter α) (filter β) := /- This is defeq to `map₂ (•) f g`, but the hypothesis unfolds to `t₁ • t₂ ⊆ s` rather than all the way to `set.image2 (•) t₁ t₂ ⊆ s`. -/ ⟨λ f g, { sets := {s | ∃ t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ • t₂ ⊆ s}, ..map₂ (•) f g }⟩ localized "attribute [instance] filter.has_smul filter.has_vadd" in pointwise @[simp, to_additive] lemma map₂_smul : map₂ (•) f g = f • g := rfl @[to_additive] lemma mem_smul : t ∈ f • g ↔ ∃ t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ • t₂ ⊆ t := iff.rfl @[to_additive] lemma smul_mem_smul : s ∈ f → t ∈ g → s • t ∈ f • g := image2_mem_map₂ @[simp, to_additive] lemma bot_smul : (⊥ : filter α) • g = ⊥ := map₂_bot_left @[simp, to_additive] lemma smul_bot : f • (⊥ : filter β) = ⊥ := map₂_bot_right @[simp, to_additive] lemma smul_eq_bot_iff : f • g = ⊥ ↔ f = ⊥ ∨ g = ⊥ := map₂_eq_bot_iff @[simp, to_additive] lemma smul_ne_bot_iff : (f • g).ne_bot ↔ f.ne_bot ∧ g.ne_bot := map₂_ne_bot_iff @[to_additive] lemma ne_bot.smul : ne_bot f → ne_bot g → ne_bot (f • g) := ne_bot.map₂ @[to_additive] lemma ne_bot.of_smul_left : (f • g).ne_bot → f.ne_bot := ne_bot.of_map₂_left @[to_additive] lemma ne_bot.of_smul_right : (f • g).ne_bot → g.ne_bot := ne_bot.of_map₂_right @[simp, to_additive] lemma pure_smul : (pure a : filter α) • g = g.map ((•) a) := map₂_pure_left @[simp, to_additive] lemma smul_pure : f • pure b = f.map (• b) := map₂_pure_right @[simp, to_additive] lemma pure_smul_pure : (pure a : filter α) • (pure b : filter β) = pure (a • b) := map₂_pure @[to_additive] lemma smul_le_smul : f₁ ≤ f₂ → g₁ ≤ g₂ → f₁ • g₁ ≤ f₂ • g₂ := map₂_mono @[to_additive] lemma smul_le_smul_left : g₁ ≤ g₂ → f • g₁ ≤ f • g₂ := map₂_mono_left @[to_additive] lemma smul_le_smul_right : f₁ ≤ f₂ → f₁ • g ≤ f₂ • g := map₂_mono_right @[simp, to_additive] lemma le_smul_iff : h ≤ f • g ↔ ∀ ⦃s⦄, s ∈ f → ∀ ⦃t⦄, t ∈ g → s • t ∈ h := le_map₂_iff @[to_additive] instance covariant_smul : covariant_class (filter α) (filter β) (•) (≤) := ⟨λ f g h, map₂_mono_left⟩ end smul /-! ### Scalar subtraction of filters -/ section vsub variables [has_vsub α β] {f f₁ f₂ g g₁ g₂ : filter β} {h : filter α} {s t : set β} {a b : β} include α /-- The filter `f -ᵥ g` is generated by `{s -ᵥ t | s ∈ f, t ∈ g}` in locale `pointwise`. -/ protected def has_vsub : has_vsub (filter α) (filter β) := /- This is defeq to `map₂ (-ᵥ) f g`, but the hypothesis unfolds to `t₁ -ᵥ t₂ ⊆ s` rather than all the way to `set.image2 (-ᵥ) t₁ t₂ ⊆ s`. -/ ⟨λ f g, { sets := {s | ∃ t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ -ᵥ t₂ ⊆ s}, ..map₂ (-ᵥ) f g }⟩ localized "attribute [instance] filter.has_vsub" in pointwise @[simp] lemma map₂_vsub : map₂ (-ᵥ) f g = f -ᵥ g := rfl lemma mem_vsub {s : set α} : s ∈ f -ᵥ g ↔ ∃ t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ -ᵥ t₂ ⊆ s := iff.rfl lemma vsub_mem_vsub : s ∈ f → t ∈ g → s -ᵥ t ∈ f -ᵥ g := image2_mem_map₂ @[simp] lemma bot_vsub : (⊥ : filter β) -ᵥ g = ⊥ := map₂_bot_left @[simp] lemma vsub_bot : f -ᵥ (⊥ : filter β) = ⊥ := map₂_bot_right @[simp] lemma vsub_eq_bot_iff : f -ᵥ g = ⊥ ↔ f = ⊥ ∨ g = ⊥ := map₂_eq_bot_iff @[simp] lemma vsub_ne_bot_iff : (f -ᵥ g : filter α).ne_bot ↔ f.ne_bot ∧ g.ne_bot := map₂_ne_bot_iff lemma ne_bot.vsub : ne_bot f → ne_bot g → ne_bot (f -ᵥ g) := ne_bot.map₂ lemma ne_bot.of_vsub_left : (f -ᵥ g : filter α).ne_bot → f.ne_bot := ne_bot.of_map₂_left lemma ne_bot.of_vsub_right : (f -ᵥ g : filter α).ne_bot → g.ne_bot := ne_bot.of_map₂_right @[simp] lemma pure_vsub : (pure a : filter β) -ᵥ g = g.map ((-ᵥ) a) := map₂_pure_left @[simp] lemma vsub_pure : f -ᵥ pure b = f.map (-ᵥ b) := map₂_pure_right @[simp] lemma pure_vsub_pure : (pure a : filter β) -ᵥ pure b = (pure (a -ᵥ b) : filter α) := map₂_pure lemma vsub_le_vsub : f₁ ≤ f₂ → g₁ ≤ g₂ → f₁ -ᵥ g₁ ≤ f₂ -ᵥ g₂ := map₂_mono lemma vsub_le_vsub_left : g₁ ≤ g₂ → f -ᵥ g₁ ≤ f -ᵥ g₂ := map₂_mono_left lemma vsub_le_vsub_right : f₁ ≤ f₂ → f₁ -ᵥ g ≤ f₂ -ᵥ g := map₂_mono_right @[simp] lemma le_vsub_iff : h ≤ f -ᵥ g ↔ ∀ ⦃s⦄, s ∈ f → ∀ ⦃t⦄, t ∈ g → s -ᵥ t ∈ h := le_map₂_iff end vsub /-! ### Translation/scaling of filters -/ section smul variables [has_smul α β] {f f₁ f₂ : filter β} {s : set β} {a : α} /-- `a • f` is the map of `f` under `a •` in locale `pointwise`. -/ @[to_additive filter.has_vadd_filter "`a +ᵥ f` is the map of `f` under `a +ᵥ` in locale `pointwise`."] protected def has_smul_filter : has_smul α (filter β) := ⟨λ a, map ((•) a)⟩ localized "attribute [instance] filter.has_smul_filter filter.has_vadd_filter" in pointwise @[simp, to_additive] lemma map_smul : map (λ b, a • b) f = a • f := rfl @[to_additive] lemma mem_smul_filter : s ∈ a • f ↔ (•) a ⁻¹' s ∈ f := iff.rfl @[to_additive] lemma smul_set_mem_smul_filter : s ∈ f → a • s ∈ a • f := image_mem_map @[simp, to_additive] lemma smul_filter_bot : a • (⊥ : filter β) = ⊥ := map_bot @[simp, to_additive] lemma smul_filter_eq_bot_iff : a • f = ⊥ ↔ f = ⊥ := map_eq_bot_iff @[simp, to_additive] lemma smul_filter_ne_bot_iff : (a • f).ne_bot ↔ f.ne_bot := map_ne_bot_iff _ @[to_additive] lemma ne_bot.smul_filter : f.ne_bot → (a • f).ne_bot := λ h, h.map _ @[to_additive] lemma ne_bot.of_smul_filter : (a • f).ne_bot → f.ne_bot := ne_bot.of_map @[to_additive] lemma smul_filter_le_smul_filter (hf : f₁ ≤ f₂) : a • f₁ ≤ a • f₂ := map_mono hf @[to_additive] instance covariant_smul_filter : covariant_class α (filter β) (•) (≤) := ⟨λ f, map_mono⟩ end smul open_locale pointwise @[to_additive] instance smul_comm_class_filter [has_smul α γ] [has_smul β γ] [smul_comm_class α β γ] : smul_comm_class α β (filter γ) := ⟨λ _ _ _, map_comm (funext $ smul_comm _ _) _⟩ @[to_additive] instance smul_comm_class_filter' [has_smul α γ] [has_smul β γ] [smul_comm_class α β γ] : smul_comm_class α (filter β) (filter γ) := ⟨λ a f g, map_map₂_distrib_right $ smul_comm a⟩ @[to_additive] instance smul_comm_class_filter'' [has_smul α γ] [has_smul β γ] [smul_comm_class α β γ] : smul_comm_class (filter α) β (filter γ) := by haveI := smul_comm_class.symm α β γ; exact smul_comm_class.symm _ _ _ @[to_additive] instance smul_comm_class [has_smul α γ] [has_smul β γ] [smul_comm_class α β γ] : smul_comm_class (filter α) (filter β) (filter γ) := ⟨λ f g h, map₂_left_comm smul_comm⟩ instance is_scalar_tower [has_smul α β] [has_smul α γ] [has_smul β γ] [is_scalar_tower α β γ] : is_scalar_tower α β (filter γ) := ⟨λ a b f, by simp only [←map_smul, map_map, smul_assoc]⟩ instance is_scalar_tower' [has_smul α β] [has_smul α γ] [has_smul β γ] [is_scalar_tower α β γ] : is_scalar_tower α (filter β) (filter γ) := ⟨λ a f g, by { refine (map_map₂_distrib_left $ λ _ _, _).symm, exact (smul_assoc a _ _).symm }⟩ instance is_scalar_tower'' [has_smul α β] [has_smul α γ] [has_smul β γ] [is_scalar_tower α β γ] : is_scalar_tower (filter α) (filter β) (filter γ) := ⟨λ f g h, map₂_assoc smul_assoc⟩ instance is_central_scalar [has_smul α β] [has_smul αᵐᵒᵖ β] [is_central_scalar α β] : is_central_scalar α (filter β) := ⟨λ a f, congr_arg (λ m, map m f) $ by exact funext (λ _, op_smul_eq_smul _ _)⟩ /-- A multiplicative action of a monoid `α` on a type `β` gives a multiplicative action of `filter α` on `filter β`. -/ @[to_additive "An additive action of an additive monoid `α` on a type `β` gives an additive action of `filter α` on `filter β`"] protected def mul_action [monoid α] [mul_action α β] : mul_action (filter α) (filter β) := { one_smul := λ f, map₂_pure_left.trans $ by simp_rw [one_smul, map_id'], mul_smul := λ f g h, map₂_assoc mul_smul } /-- A multiplicative action of a monoid on a type `β` gives a multiplicative action on `filter β`. -/ @[to_additive "An additive action of an additive monoid on a type `β` gives an additive action on `filter β`."] protected def mul_action_filter [monoid α] [mul_action α β] : mul_action α (filter β) := { mul_smul := λ a b f, by simp only [←map_smul, map_map, function.comp, ←mul_smul], one_smul := λ f, by simp only [←map_smul, one_smul, map_id'] } localized "attribute [instance] filter.mul_action filter.add_action filter.mul_action_filter filter.add_action_filter" in pointwise /-- A distributive multiplicative action of a monoid on an additive monoid `β` gives a distributive multiplicative action on `filter β`. -/ protected def distrib_mul_action_filter [monoid α] [add_monoid β] [distrib_mul_action α β] : distrib_mul_action α (filter β) := { smul_add := λ _ _ _, map_map₂_distrib $ smul_add _, smul_zero := λ _, (map_pure _ _).trans $ by rw [smul_zero, pure_zero] } /-- A multiplicative action of a monoid on a monoid `β` gives a multiplicative action on `set β`. -/ protected def mul_distrib_mul_action_filter [monoid α] [monoid β] [mul_distrib_mul_action α β] : mul_distrib_mul_action α (set β) := { smul_mul := λ _ _ _, image_image2_distrib $ smul_mul' _, smul_one := λ _, image_singleton.trans $ by rw [smul_one, singleton_one] } localized "attribute [instance] filter.distrib_mul_action_filter filter.mul_distrib_mul_action_filter" in pointwise section smul_with_zero variables [has_zero α] [has_zero β] [smul_with_zero α β] {f : filter α} {g : filter β} /-! Note that we have neither `smul_with_zero α (filter β)` nor `smul_with_zero (filter α) (filter β)` because `0 * ⊥ ≠ 0`. -/ lemma ne_bot.smul_zero_nonneg (hf : f.ne_bot) : 0 ≤ f • (0 : filter β) := le_smul_iff.2 $ λ t₁ h₁ t₂ h₂, let ⟨a, ha⟩ := hf.nonempty_of_mem h₁ in ⟨_, _, ha, h₂, smul_zero' _ _⟩ lemma ne_bot.zero_smul_nonneg (hg : g.ne_bot) : 0 ≤ (0 : filter α) • g := le_smul_iff.2 $ λ t₁ h₁ t₂ h₂, let ⟨b, hb⟩ := hg.nonempty_of_mem h₂ in ⟨_, _, h₁, hb, zero_smul _ _⟩ lemma zero_smul_filter_nonpos : (0 : α) • g ≤ 0 := begin refine λ s hs, mem_smul_filter.2 _, convert univ_mem, refine eq_univ_iff_forall.2 (λ a, _), rwa [mem_preimage, zero_smul], end lemma zero_smul_filter (hg : g.ne_bot) : (0 : α) • g = 0 := zero_smul_filter_nonpos.antisymm $ le_map_iff.2 $ λ s hs, begin simp_rw [set.image_eta, zero_smul, (hg.nonempty_of_mem hs).image_const], exact zero_mem_zero, end end smul_with_zero end filter
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies ! This file was ported from Lean 3 source module data.nat.interval ! leanprover-community/mathlib commit a11f9106a169dd302a285019e5165f8ab32ff433 ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathbin.Data.Finset.LocallyFinite /-! # Finite intervals of naturals > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file proves that `ℕ` is a `locally_finite_order` and calculates the cardinality of its intervals as finsets and fintypes. ## TODO Some lemmas can be generalized using `ordered_group`, `canonically_ordered_monoid` or `succ_order` and subsequently be moved upstream to `data.finset.locally_finite`. -/ open Finset Nat instance : LocallyFiniteOrder ℕ where finsetIcc a b := ⟨List.range' a (b + 1 - a), List.nodup_range' _ _⟩ finsetIco a b := ⟨List.range' a (b - a), List.nodup_range' _ _⟩ finsetIoc a b := ⟨List.range' (a + 1) (b - a), List.nodup_range' _ _⟩ finsetIoo a b := ⟨List.range' (a + 1) (b - a - 1), List.nodup_range' _ _⟩ finset_mem_Icc a b x := by rw [Finset.mem_mk, Multiset.mem_coe, List.mem_range'] cases le_or_lt a b · rw [add_tsub_cancel_of_le (Nat.lt_succ_of_le h).le, Nat.lt_succ_iff] · rw [tsub_eq_zero_iff_le.2 (succ_le_of_lt h), add_zero] exact iff_of_false (fun hx => hx.2.not_le hx.1) fun hx => h.not_le (hx.1.trans hx.2) finset_mem_Ico a b x := by rw [Finset.mem_mk, Multiset.mem_coe, List.mem_range'] cases le_or_lt a b · rw [add_tsub_cancel_of_le h] · rw [tsub_eq_zero_iff_le.2 h.le, add_zero] exact iff_of_false (fun hx => hx.2.not_le hx.1) fun hx => h.not_le (hx.1.trans hx.2.le) finset_mem_Ioc a b x := by rw [Finset.mem_mk, Multiset.mem_coe, List.mem_range'] cases le_or_lt a b · rw [← succ_sub_succ, add_tsub_cancel_of_le (succ_le_succ h), Nat.lt_succ_iff, Nat.succ_le_iff] · rw [tsub_eq_zero_iff_le.2 h.le, add_zero] exact iff_of_false (fun hx => hx.2.not_le hx.1) fun hx => h.not_le (hx.1.le.trans hx.2) finset_mem_Ioo a b x := by rw [Finset.mem_mk, Multiset.mem_coe, List.mem_range', ← tsub_add_eq_tsub_tsub] cases le_or_lt (a + 1) b · rw [add_tsub_cancel_of_le h, Nat.succ_le_iff] · rw [tsub_eq_zero_iff_le.2 h.le, add_zero] exact iff_of_false (fun hx => hx.2.not_le hx.1) fun hx => h.not_le (hx.1.trans hx.2) variable (a b c : ℕ) namespace Nat #print Nat.Icc_eq_range' /- theorem Icc_eq_range' : Icc a b = ⟨List.range' a (b + 1 - a), List.nodup_range' _ _⟩ := rfl #align nat.Icc_eq_range' Nat.Icc_eq_range' -/ #print Nat.Ico_eq_range' /- theorem Ico_eq_range' : Ico a b = ⟨List.range' a (b - a), List.nodup_range' _ _⟩ := rfl #align nat.Ico_eq_range' Nat.Ico_eq_range' -/ #print Nat.Ioc_eq_range' /- theorem Ioc_eq_range' : Ioc a b = ⟨List.range' (a + 1) (b - a), List.nodup_range' _ _⟩ := rfl #align nat.Ioc_eq_range' Nat.Ioc_eq_range' -/ #print Nat.Ioo_eq_range' /- theorem Ioo_eq_range' : Ioo a b = ⟨List.range' (a + 1) (b - a - 1), List.nodup_range' _ _⟩ := rfl #align nat.Ioo_eq_range' Nat.Ioo_eq_range' -/ #print Nat.Iio_eq_range /- theorem Iio_eq_range : Iio = range := by ext (b x) rw [mem_Iio, mem_range] #align nat.Iio_eq_range Nat.Iio_eq_range -/ #print Nat.Ico_zero_eq_range /- @[simp] theorem Ico_zero_eq_range : Ico 0 = range := by rw [← bot_eq_zero, ← Iio_eq_Ico, Iio_eq_range] #align nat.Ico_zero_eq_range Nat.Ico_zero_eq_range -/ #print Finset.range_eq_Ico /- theorem Finset.range_eq_Ico : range = Ico 0 := Ico_zero_eq_range.symm #align finset.range_eq_Ico Finset.range_eq_Ico -/ #print Nat.card_Icc /- @[simp] theorem card_Icc : (Icc a b).card = b + 1 - a := List.length_range' _ _ #align nat.card_Icc Nat.card_Icc -/ #print Nat.card_Ico /- @[simp] theorem card_Ico : (Ico a b).card = b - a := List.length_range' _ _ #align nat.card_Ico Nat.card_Ico -/ #print Nat.card_Ioc /- @[simp] theorem card_Ioc : (Ioc a b).card = b - a := List.length_range' _ _ #align nat.card_Ioc Nat.card_Ioc -/ #print Nat.card_Ioo /- @[simp] theorem card_Ioo : (Ioo a b).card = b - a - 1 := List.length_range' _ _ #align nat.card_Ioo Nat.card_Ioo -/ #print Nat.card_Iic /- @[simp] theorem card_Iic : (Iic b).card = b + 1 := by rw [Iic_eq_Icc, card_Icc, bot_eq_zero, tsub_zero] #align nat.card_Iic Nat.card_Iic -/ #print Nat.card_Iio /- @[simp] theorem card_Iio : (Iio b).card = b := by rw [Iio_eq_Ico, card_Ico, bot_eq_zero, tsub_zero] #align nat.card_Iio Nat.card_Iio -/ #print Nat.card_fintypeIcc /- @[simp] theorem card_fintypeIcc : Fintype.card (Set.Icc a b) = b + 1 - a := by rw [Fintype.card_ofFinset, card_Icc] #align nat.card_fintype_Icc Nat.card_fintypeIcc -/ #print Nat.card_fintypeIco /- @[simp] theorem card_fintypeIco : Fintype.card (Set.Ico a b) = b - a := by rw [Fintype.card_ofFinset, card_Ico] #align nat.card_fintype_Ico Nat.card_fintypeIco -/ #print Nat.card_fintypeIoc /- @[simp] theorem card_fintypeIoc : Fintype.card (Set.Ioc a b) = b - a := by rw [Fintype.card_ofFinset, card_Ioc] #align nat.card_fintype_Ioc Nat.card_fintypeIoc -/ #print Nat.card_fintypeIoo /- @[simp] theorem card_fintypeIoo : Fintype.card (Set.Ioo a b) = b - a - 1 := by rw [Fintype.card_ofFinset, card_Ioo] #align nat.card_fintype_Ioo Nat.card_fintypeIoo -/ #print Nat.card_fintypeIic /- @[simp] theorem card_fintypeIic : Fintype.card (Set.Iic b) = b + 1 := by rw [Fintype.card_ofFinset, card_Iic] #align nat.card_fintype_Iic Nat.card_fintypeIic -/ #print Nat.card_fintypeIio /- @[simp] theorem card_fintypeIio : Fintype.card (Set.Iio b) = b := by rw [Fintype.card_ofFinset, card_Iio] #align nat.card_fintype_Iio Nat.card_fintypeIio -/ #print Nat.Icc_succ_left /- -- TODO@Yaël: Generalize all the following lemmas to `succ_order` theorem Icc_succ_left : Icc a.succ b = Ioc a b := by ext x rw [mem_Icc, mem_Ioc, succ_le_iff] #align nat.Icc_succ_left Nat.Icc_succ_left -/ #print Nat.Ico_succ_right /- theorem Ico_succ_right : Ico a b.succ = Icc a b := by ext x rw [mem_Ico, mem_Icc, lt_succ_iff] #align nat.Ico_succ_right Nat.Ico_succ_right -/ #print Nat.Ico_succ_left /- theorem Ico_succ_left : Ico a.succ b = Ioo a b := by ext x rw [mem_Ico, mem_Ioo, succ_le_iff] #align nat.Ico_succ_left Nat.Ico_succ_left -/ #print Nat.Icc_pred_right /- theorem Icc_pred_right {b : ℕ} (h : 0 < b) : Icc a (b - 1) = Ico a b := by ext x rw [mem_Icc, mem_Ico, lt_iff_le_pred h] #align nat.Icc_pred_right Nat.Icc_pred_right -/ #print Nat.Ico_succ_succ /- theorem Ico_succ_succ : Ico a.succ b.succ = Ioc a b := by ext x rw [mem_Ico, mem_Ioc, succ_le_iff, lt_succ_iff] #align nat.Ico_succ_succ Nat.Ico_succ_succ -/ #print Nat.Ico_succ_singleton /- @[simp] theorem Ico_succ_singleton : Ico a (a + 1) = {a} := by rw [Ico_succ_right, Icc_self] #align nat.Ico_succ_singleton Nat.Ico_succ_singleton -/ #print Nat.Ico_pred_singleton /- @[simp] theorem Ico_pred_singleton {a : ℕ} (h : 0 < a) : Ico (a - 1) a = {a - 1} := by rw [← Icc_pred_right _ h, Icc_self] #align nat.Ico_pred_singleton Nat.Ico_pred_singleton -/ #print Nat.Ioc_succ_singleton /- @[simp] theorem Ioc_succ_singleton : Ioc b (b + 1) = {b + 1} := by rw [← Nat.Icc_succ_left, Icc_self] #align nat.Ioc_succ_singleton Nat.Ioc_succ_singleton -/ variable {a b c} /- warning: nat.Ico_succ_right_eq_insert_Ico -> Nat.Ico_succ_right_eq_insert_Ico is a dubious translation: lean 3 declaration is forall {a : Nat} {b : Nat}, (LE.le.{0} Nat Nat.hasLe a b) -> (Eq.{1} (Finset.{0} Nat) (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (OrderedCancelAddCommMonoid.toPartialOrder.{0} Nat (StrictOrderedSemiring.toOrderedCancelAddCommMonoid.{0} Nat Nat.strictOrderedSemiring))) Nat.locallyFiniteOrder a (HAdd.hAdd.{0, 0, 0} Nat Nat Nat (instHAdd.{0} Nat Nat.hasAdd) b (OfNat.ofNat.{0} Nat 1 (OfNat.mk.{0} Nat 1 (One.one.{0} Nat Nat.hasOne))))) (Insert.insert.{0, 0} Nat (Finset.{0} Nat) (Finset.hasInsert.{0} Nat (fun (a : Nat) (b : Nat) => Nat.decidableEq a b)) b (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (OrderedCancelAddCommMonoid.toPartialOrder.{0} Nat (StrictOrderedSemiring.toOrderedCancelAddCommMonoid.{0} Nat Nat.strictOrderedSemiring))) Nat.locallyFiniteOrder a b))) but is expected to have type forall {a : Nat} {b : Nat}, (LE.le.{0} Nat instLENat a b) -> (Eq.{1} (Finset.{0} Nat) (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (StrictOrderedSemiring.toPartialOrder.{0} Nat Nat.strictOrderedSemiring)) instLocallyFiniteOrderNatToPreorderToPartialOrderStrictOrderedSemiring a (HAdd.hAdd.{0, 0, 0} Nat Nat Nat (instHAdd.{0} Nat instAddNat) b (OfNat.ofNat.{0} Nat 1 (instOfNatNat 1)))) (Insert.insert.{0, 0} Nat (Finset.{0} Nat) (Finset.instInsertFinset.{0} Nat (fun (a : Nat) (b : Nat) => instDecidableEqNat a b)) b (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (StrictOrderedSemiring.toPartialOrder.{0} Nat Nat.strictOrderedSemiring)) instLocallyFiniteOrderNatToPreorderToPartialOrderStrictOrderedSemiring a b))) Case conversion may be inaccurate. Consider using '#align nat.Ico_succ_right_eq_insert_Ico Nat.Ico_succ_right_eq_insert_Icoₓ'. -/ theorem Ico_succ_right_eq_insert_Ico (h : a ≤ b) : Ico a (b + 1) = insert b (Ico a b) := by rw [Ico_succ_right, ← Ico_insert_right h] #align nat.Ico_succ_right_eq_insert_Ico Nat.Ico_succ_right_eq_insert_Ico /- warning: nat.Ico_insert_succ_left -> Nat.Ico_insert_succ_left is a dubious translation: lean 3 declaration is forall {a : Nat} {b : Nat}, (LT.lt.{0} Nat Nat.hasLt a b) -> (Eq.{1} (Finset.{0} Nat) (Insert.insert.{0, 0} Nat (Finset.{0} Nat) (Finset.hasInsert.{0} Nat (fun (a : Nat) (b : Nat) => Nat.decidableEq a b)) a (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (OrderedCancelAddCommMonoid.toPartialOrder.{0} Nat (StrictOrderedSemiring.toOrderedCancelAddCommMonoid.{0} Nat Nat.strictOrderedSemiring))) Nat.locallyFiniteOrder (Nat.succ a) b)) (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (OrderedCancelAddCommMonoid.toPartialOrder.{0} Nat (StrictOrderedSemiring.toOrderedCancelAddCommMonoid.{0} Nat Nat.strictOrderedSemiring))) Nat.locallyFiniteOrder a b)) but is expected to have type forall {a : Nat} {b : Nat}, (LT.lt.{0} Nat instLTNat a b) -> (Eq.{1} (Finset.{0} Nat) (Insert.insert.{0, 0} Nat (Finset.{0} Nat) (Finset.instInsertFinset.{0} Nat (fun (a : Nat) (b : Nat) => instDecidableEqNat a b)) a (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (StrictOrderedSemiring.toPartialOrder.{0} Nat Nat.strictOrderedSemiring)) instLocallyFiniteOrderNatToPreorderToPartialOrderStrictOrderedSemiring (Nat.succ a) b)) (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (StrictOrderedSemiring.toPartialOrder.{0} Nat Nat.strictOrderedSemiring)) instLocallyFiniteOrderNatToPreorderToPartialOrderStrictOrderedSemiring a b)) Case conversion may be inaccurate. Consider using '#align nat.Ico_insert_succ_left Nat.Ico_insert_succ_leftₓ'. -/ theorem Ico_insert_succ_left (h : a < b) : insert a (Ico a.succ b) = Ico a b := by rw [Ico_succ_left, ← Ioo_insert_left h] #align nat.Ico_insert_succ_left Nat.Ico_insert_succ_left /- warning: nat.image_sub_const_Ico -> Nat.image_sub_const_Ico is a dubious translation: lean 3 declaration is forall {a : Nat} {b : Nat} {c : Nat}, (LE.le.{0} Nat Nat.hasLe c a) -> (Eq.{1} (Finset.{0} Nat) (Finset.image.{0, 0} Nat Nat (fun (a : Nat) (b : Nat) => Nat.decidableEq a b) (fun (x : Nat) => HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat Nat.hasSub) x c) (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (OrderedCancelAddCommMonoid.toPartialOrder.{0} Nat (StrictOrderedSemiring.toOrderedCancelAddCommMonoid.{0} Nat Nat.strictOrderedSemiring))) Nat.locallyFiniteOrder a b)) (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (OrderedCancelAddCommMonoid.toPartialOrder.{0} Nat (StrictOrderedSemiring.toOrderedCancelAddCommMonoid.{0} Nat Nat.strictOrderedSemiring))) Nat.locallyFiniteOrder (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat Nat.hasSub) a c) (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat Nat.hasSub) b c))) but is expected to have type forall {a : Nat} {b : Nat} {c : Nat}, (LE.le.{0} Nat instLENat c a) -> (Eq.{1} (Finset.{0} Nat) (Finset.image.{0, 0} Nat Nat (fun (a : Nat) (b : Nat) => instDecidableEqNat a b) (fun (x : Nat) => HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat instSubNat) x c) (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (StrictOrderedSemiring.toPartialOrder.{0} Nat Nat.strictOrderedSemiring)) instLocallyFiniteOrderNatToPreorderToPartialOrderStrictOrderedSemiring a b)) (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (StrictOrderedSemiring.toPartialOrder.{0} Nat Nat.strictOrderedSemiring)) instLocallyFiniteOrderNatToPreorderToPartialOrderStrictOrderedSemiring (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat instSubNat) a c) (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat instSubNat) b c))) Case conversion may be inaccurate. Consider using '#align nat.image_sub_const_Ico Nat.image_sub_const_Icoₓ'. -/ theorem image_sub_const_Ico (h : c ≤ a) : ((Ico a b).image fun x => x - c) = Ico (a - c) (b - c) := by ext x rw [mem_image] constructor · rintro ⟨x, hx, rfl⟩ rw [mem_Ico] at hx⊢ exact ⟨tsub_le_tsub_right hx.1 _, tsub_lt_tsub_right_of_le (h.trans hx.1) hx.2⟩ · rintro h refine' ⟨x + c, _, add_tsub_cancel_right _ _⟩ rw [mem_Ico] at h⊢ exact ⟨tsub_le_iff_right.1 h.1, lt_tsub_iff_right.1 h.2⟩ #align nat.image_sub_const_Ico Nat.image_sub_const_Ico /- warning: nat.Ico_image_const_sub_eq_Ico -> Nat.Ico_image_const_sub_eq_Ico is a dubious translation: lean 3 declaration is forall {a : Nat} {b : Nat} {c : Nat}, (LE.le.{0} Nat Nat.hasLe a c) -> (Eq.{1} (Finset.{0} Nat) (Finset.image.{0, 0} Nat Nat (fun (a : Nat) (b : Nat) => Nat.decidableEq a b) (fun (x : Nat) => HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat Nat.hasSub) c x) (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (OrderedCancelAddCommMonoid.toPartialOrder.{0} Nat (StrictOrderedSemiring.toOrderedCancelAddCommMonoid.{0} Nat Nat.strictOrderedSemiring))) Nat.locallyFiniteOrder a b)) (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (OrderedCancelAddCommMonoid.toPartialOrder.{0} Nat (StrictOrderedSemiring.toOrderedCancelAddCommMonoid.{0} Nat Nat.strictOrderedSemiring))) Nat.locallyFiniteOrder (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat Nat.hasSub) (HAdd.hAdd.{0, 0, 0} Nat Nat Nat (instHAdd.{0} Nat Nat.hasAdd) c (OfNat.ofNat.{0} Nat 1 (OfNat.mk.{0} Nat 1 (One.one.{0} Nat Nat.hasOne)))) b) (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat Nat.hasSub) (HAdd.hAdd.{0, 0, 0} Nat Nat Nat (instHAdd.{0} Nat Nat.hasAdd) c (OfNat.ofNat.{0} Nat 1 (OfNat.mk.{0} Nat 1 (One.one.{0} Nat Nat.hasOne)))) a))) but is expected to have type forall {a : Nat} {b : Nat} {c : Nat}, (LE.le.{0} Nat instLENat a c) -> (Eq.{1} (Finset.{0} Nat) (Finset.image.{0, 0} Nat Nat (fun (a : Nat) (b : Nat) => instDecidableEqNat a b) (fun (x : Nat) => HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat instSubNat) c x) (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (StrictOrderedSemiring.toPartialOrder.{0} Nat Nat.strictOrderedSemiring)) instLocallyFiniteOrderNatToPreorderToPartialOrderStrictOrderedSemiring a b)) (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (StrictOrderedSemiring.toPartialOrder.{0} Nat Nat.strictOrderedSemiring)) instLocallyFiniteOrderNatToPreorderToPartialOrderStrictOrderedSemiring (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat instSubNat) (HAdd.hAdd.{0, 0, 0} Nat Nat Nat (instHAdd.{0} Nat instAddNat) c (OfNat.ofNat.{0} Nat 1 (instOfNatNat 1))) b) (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat instSubNat) (HAdd.hAdd.{0, 0, 0} Nat Nat Nat (instHAdd.{0} Nat instAddNat) c (OfNat.ofNat.{0} Nat 1 (instOfNatNat 1))) a))) Case conversion may be inaccurate. Consider using '#align nat.Ico_image_const_sub_eq_Ico Nat.Ico_image_const_sub_eq_Icoₓ'. -/ theorem Ico_image_const_sub_eq_Ico (hac : a ≤ c) : ((Ico a b).image fun x => c - x) = Ico (c + 1 - b) (c + 1 - a) := by ext x rw [mem_image, mem_Ico] constructor · rintro ⟨x, hx, rfl⟩ rw [mem_Ico] at hx refine' ⟨_, ((tsub_le_tsub_iff_left hac).2 hx.1).trans_lt ((tsub_lt_tsub_iff_right hac).2 (Nat.lt_succ_self _))⟩ cases lt_or_le c b · rw [tsub_eq_zero_iff_le.mpr (succ_le_of_lt h)] exact zero_le _ · rw [← succ_sub_succ c] exact (tsub_le_tsub_iff_left (succ_le_succ <| hx.2.le.trans h)).2 hx.2 · rintro ⟨hb, ha⟩ rw [lt_tsub_iff_left, lt_succ_iff] at ha have hx : x ≤ c := (Nat.le_add_left _ _).trans ha refine' ⟨c - x, _, tsub_tsub_cancel_of_le hx⟩ · rw [mem_Ico] exact ⟨le_tsub_of_add_le_right ha, (tsub_lt_iff_left hx).2 <| succ_le_iff.1 <| tsub_le_iff_right.1 hb⟩ #align nat.Ico_image_const_sub_eq_Ico Nat.Ico_image_const_sub_eq_Ico /- warning: nat.Ico_succ_left_eq_erase_Ico -> Nat.Ico_succ_left_eq_erase_Ico is a dubious translation: lean 3 declaration is forall {a : Nat} {b : Nat}, Eq.{1} (Finset.{0} Nat) (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (OrderedCancelAddCommMonoid.toPartialOrder.{0} Nat (StrictOrderedSemiring.toOrderedCancelAddCommMonoid.{0} Nat Nat.strictOrderedSemiring))) Nat.locallyFiniteOrder (Nat.succ a) b) (Finset.erase.{0} Nat (fun (a : Nat) (b : Nat) => Nat.decidableEq a b) (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (OrderedCancelAddCommMonoid.toPartialOrder.{0} Nat (StrictOrderedSemiring.toOrderedCancelAddCommMonoid.{0} Nat Nat.strictOrderedSemiring))) Nat.locallyFiniteOrder a b) a) but is expected to have type forall {a : Nat} {b : Nat}, Eq.{1} (Finset.{0} Nat) (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (StrictOrderedSemiring.toPartialOrder.{0} Nat Nat.strictOrderedSemiring)) instLocallyFiniteOrderNatToPreorderToPartialOrderStrictOrderedSemiring (Nat.succ a) b) (Finset.erase.{0} Nat (fun (a : Nat) (b : Nat) => instDecidableEqNat a b) (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (StrictOrderedSemiring.toPartialOrder.{0} Nat Nat.strictOrderedSemiring)) instLocallyFiniteOrderNatToPreorderToPartialOrderStrictOrderedSemiring a b) a) Case conversion may be inaccurate. Consider using '#align nat.Ico_succ_left_eq_erase_Ico Nat.Ico_succ_left_eq_erase_Icoₓ'. -/ theorem Ico_succ_left_eq_erase_Ico : Ico a.succ b = erase (Ico a b) a := by ext x rw [Ico_succ_left, mem_erase, mem_Ico, mem_Ioo, ← and_assoc', ne_comm, and_comm' (a ≠ x), lt_iff_le_and_ne] #align nat.Ico_succ_left_eq_erase_Ico Nat.Ico_succ_left_eq_erase_Ico #print Nat.mod_injOn_Ico /- theorem mod_injOn_Ico (n a : ℕ) : Set.InjOn (· % a) (Finset.Ico n (n + a)) := by induction' n with n ih · simp only [zero_add, nat_zero_eq_zero, Ico_zero_eq_range] rintro k hk l hl (hkl : k % a = l % a) simp only [Finset.mem_range, Finset.mem_coe] at hk hl rwa [mod_eq_of_lt hk, mod_eq_of_lt hl] at hkl rw [Ico_succ_left_eq_erase_Ico, succ_add, Ico_succ_right_eq_insert_Ico le_self_add] rintro k hk l hl (hkl : k % a = l % a) have ha : 0 < a := by by_contra ha simp only [not_lt, nonpos_iff_eq_zero] at ha simpa [ha] using hk simp only [Finset.mem_coe, Finset.mem_insert, Finset.mem_erase] at hk hl rcases hk with ⟨hkn, rfl | hk⟩ <;> rcases hl with ⟨hln, rfl | hl⟩ · rfl · rw [add_mod_right] at hkl refine' (hln <| ih hl _ hkl.symm).elim simp only [lt_add_iff_pos_right, Set.left_mem_Ico, Finset.coe_Ico, ha] · rw [add_mod_right] at hkl suffices k = n by contradiction refine' ih hk _ hkl simp only [lt_add_iff_pos_right, Set.left_mem_Ico, Finset.coe_Ico, ha] · refine' ih _ _ hkl <;> simp only [Finset.mem_coe, hk, hl] #align nat.mod_inj_on_Ico Nat.mod_injOn_Ico -/ /- warning: nat.image_Ico_mod -> Nat.image_Ico_mod is a dubious translation: lean 3 declaration is forall (n : Nat) (a : Nat), Eq.{1} (Finset.{0} Nat) (Finset.image.{0, 0} Nat Nat (fun (a : Nat) (b : Nat) => Nat.decidableEq a b) (fun (_x : Nat) => HMod.hMod.{0, 0, 0} Nat Nat Nat (instHMod.{0} Nat Nat.hasMod) _x a) (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (OrderedCancelAddCommMonoid.toPartialOrder.{0} Nat (StrictOrderedSemiring.toOrderedCancelAddCommMonoid.{0} Nat Nat.strictOrderedSemiring))) Nat.locallyFiniteOrder n (HAdd.hAdd.{0, 0, 0} Nat Nat Nat (instHAdd.{0} Nat Nat.hasAdd) n a))) (Finset.range a) but is expected to have type forall (n : Nat) (a : Nat), Eq.{1} (Finset.{0} Nat) (Finset.image.{0, 0} Nat Nat (fun (a : Nat) (b : Nat) => instDecidableEqNat a b) (fun (_x : Nat) => HMod.hMod.{0, 0, 0} Nat Nat Nat (instHMod.{0} Nat Nat.instModNat) _x a) (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (StrictOrderedSemiring.toPartialOrder.{0} Nat Nat.strictOrderedSemiring)) instLocallyFiniteOrderNatToPreorderToPartialOrderStrictOrderedSemiring n (HAdd.hAdd.{0, 0, 0} Nat Nat Nat (instHAdd.{0} Nat instAddNat) n a))) (Finset.range a) Case conversion may be inaccurate. Consider using '#align nat.image_Ico_mod Nat.image_Ico_modₓ'. -/ /-- Note that while this lemma cannot be easily generalized to a type class, it holds for ℤ as well. See `int.image_Ico_mod` for the ℤ version. -/ theorem image_Ico_mod (n a : ℕ) : (Ico n (n + a)).image (· % a) = range a := by obtain rfl | ha := eq_or_ne a 0 · rw [range_zero, add_zero, Ico_self, image_empty] ext i simp only [mem_image, exists_prop, mem_range, mem_Ico] constructor · rintro ⟨i, h, rfl⟩ exact mod_lt i ha.bot_lt intro hia have hn := Nat.mod_add_div n a obtain hi | hi := lt_or_le i (n % a) · refine' ⟨i + a * (n / a + 1), ⟨_, _⟩, _⟩ · rw [add_comm (n / a), mul_add, mul_one, ← add_assoc] refine' hn.symm.le.trans (add_le_add_right _ _) simpa only [zero_add] using add_le_add (zero_le i) (Nat.mod_lt n ha.bot_lt).le · refine' lt_of_lt_of_le (add_lt_add_right hi (a * (n / a + 1))) _ rw [mul_add, mul_one, ← add_assoc, hn] · rw [Nat.add_mul_mod_self_left, Nat.mod_eq_of_lt hia] · refine' ⟨i + a * (n / a), ⟨_, _⟩, _⟩ · exact hn.symm.le.trans (add_le_add_right hi _) · rw [add_comm n a] refine' add_lt_add_of_lt_of_le hia (le_trans _ hn.le) simp only [zero_le, le_add_iff_nonneg_left] · rw [Nat.add_mul_mod_self_left, Nat.mod_eq_of_lt hia] #align nat.image_Ico_mod Nat.image_Ico_mod section Multiset open Multiset #print Nat.multiset_Ico_map_mod /- theorem multiset_Ico_map_mod (n a : ℕ) : (Multiset.Ico n (n + a)).map (· % a) = range a := by convert congr_arg Finset.val (image_Ico_mod n a) refine' ((nodup_map_iff_inj_on (Finset.Ico _ _).Nodup).2 <| _).dedup.symm exact mod_inj_on_Ico _ _ #align nat.multiset_Ico_map_mod Nat.multiset_Ico_map_mod -/ end Multiset end Nat namespace Finset /- warning: finset.range_image_pred_top_sub -> Finset.range_image_pred_top_sub is a dubious translation: lean 3 declaration is forall (n : Nat), Eq.{1} (Finset.{0} Nat) (Finset.image.{0, 0} Nat Nat (fun (a : Nat) (b : Nat) => Nat.decidableEq a b) (fun (j : Nat) => HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat Nat.hasSub) (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat Nat.hasSub) n (OfNat.ofNat.{0} Nat 1 (OfNat.mk.{0} Nat 1 (One.one.{0} Nat Nat.hasOne)))) j) (Finset.range n)) (Finset.range n) but is expected to have type forall (n : Nat), Eq.{1} (Finset.{0} Nat) (Finset.image.{0, 0} Nat Nat (fun (a : Nat) (b : Nat) => instDecidableEqNat a b) (fun (j : Nat) => HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat instSubNat) (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat instSubNat) n (OfNat.ofNat.{0} Nat 1 (instOfNatNat 1))) j) (Finset.range n)) (Finset.range n) Case conversion may be inaccurate. Consider using '#align finset.range_image_pred_top_sub Finset.range_image_pred_top_subₓ'. -/ theorem range_image_pred_top_sub (n : ℕ) : ((Finset.range n).image fun j => n - 1 - j) = Finset.range n := by cases n · rw [range_zero, image_empty] · rw [Finset.range_eq_Ico, Nat.Ico_image_const_sub_eq_Ico (zero_le _)] simp_rw [succ_sub_succ, tsub_zero, tsub_self] #align finset.range_image_pred_top_sub Finset.range_image_pred_top_sub /- warning: finset.range_add_eq_union -> Finset.range_add_eq_union is a dubious translation: lean 3 declaration is forall (a : Nat) (b : Nat), Eq.{1} (Finset.{0} Nat) (Finset.range (HAdd.hAdd.{0, 0, 0} Nat Nat Nat (instHAdd.{0} Nat Nat.hasAdd) a b)) (Union.union.{0} (Finset.{0} Nat) (Finset.hasUnion.{0} Nat (fun (a : Nat) (b : Nat) => Nat.decidableEq a b)) (Finset.range a) (Finset.map.{0, 0} Nat Nat (addLeftEmbedding.{0} Nat (AddLeftCancelMonoid.toAddLeftCancelSemigroup.{0} Nat (AddCancelCommMonoid.toAddLeftCancelMonoid.{0} Nat (OrderedCancelAddCommMonoid.toCancelAddCommMonoid.{0} Nat (StrictOrderedSemiring.toOrderedCancelAddCommMonoid.{0} Nat Nat.strictOrderedSemiring)))) a) (Finset.range b))) but is expected to have type forall (a : Nat) (b : Nat), Eq.{1} (Finset.{0} Nat) (Finset.range (HAdd.hAdd.{0, 0, 0} Nat Nat Nat (instHAdd.{0} Nat instAddNat) a b)) (Union.union.{0} (Finset.{0} Nat) (Finset.instUnionFinset.{0} Nat (fun (a : Nat) (b : Nat) => instDecidableEqNat a b)) (Finset.range a) (Finset.map.{0, 0} Nat Nat (addLeftEmbedding.{0} Nat (AddLeftCancelMonoid.toAddLeftCancelSemigroup.{0} Nat (AddCancelCommMonoid.toAddLeftCancelMonoid.{0} Nat (OrderedCancelAddCommMonoid.toCancelAddCommMonoid.{0} Nat (StrictOrderedSemiring.toOrderedCancelAddCommMonoid.{0} Nat Nat.strictOrderedSemiring)))) a) (Finset.range b))) Case conversion may be inaccurate. Consider using '#align finset.range_add_eq_union Finset.range_add_eq_unionₓ'. -/ theorem range_add_eq_union : range (a + b) = range a ∪ (range b).map (addLeftEmbedding a) := by rw [Finset.range_eq_Ico, map_eq_image] convert(Ico_union_Ico_eq_Ico a.zero_le le_self_add).symm exact image_add_left_Ico _ _ _ #align finset.range_add_eq_union Finset.range_add_eq_union end Finset section Induction variable {P : ℕ → Prop} (h : ∀ n, P (n + 1) → P n) include h #print Nat.decreasing_induction_of_not_bddAbove /- theorem Nat.decreasing_induction_of_not_bddAbove (hP : ¬BddAbove { x | P x }) (n : ℕ) : P n := let ⟨m, hm, hl⟩ := not_bddAbove_iff.1 hP n decreasingInduction h hl.le hm #align nat.decreasing_induction_of_not_bdd_above Nat.decreasing_induction_of_not_bddAbove -/ #print Nat.decreasing_induction_of_infinite /- theorem Nat.decreasing_induction_of_infinite (hP : { x | P x }.Infinite) (n : ℕ) : P n := Nat.decreasing_induction_of_not_bddAbove h (mt BddAbove.finite hP) n #align nat.decreasing_induction_of_infinite Nat.decreasing_induction_of_infinite -/ #print Nat.cauchy_induction' /- theorem Nat.cauchy_induction' (seed : ℕ) (hs : P seed) (hi : ∀ x, seed ≤ x → P x → ∃ y, x < y ∧ P y) (n : ℕ) : P n := by apply Nat.decreasing_induction_of_infinite h fun hf => _ obtain ⟨m, hP, hm⟩ := hf.exists_maximal_wrt id _ ⟨seed, hs⟩ obtain ⟨y, hl, hy⟩ := hi m (le_of_not_lt fun hl => hl.Ne <| hm seed hs hl.le) hP exact hl.ne (hm y hy hl.le) #align nat.cauchy_induction' Nat.cauchy_induction' -/ #print Nat.cauchy_induction /- theorem Nat.cauchy_induction (seed : ℕ) (hs : P seed) (f : ℕ → ℕ) (hf : ∀ x, seed ≤ x → P x → x < f x ∧ P (f x)) (n : ℕ) : P n := seed.cauchy_induction' h hs (fun x hl hx => ⟨f x, hf x hl hx⟩) n #align nat.cauchy_induction Nat.cauchy_induction -/ #print Nat.cauchy_induction_mul /- theorem Nat.cauchy_induction_mul (k seed : ℕ) (hk : 1 < k) (hs : P seed.succ) (hm : ∀ x, seed < x → P x → P (k * x)) (n : ℕ) : P n := by apply Nat.cauchy_induction h _ hs ((· * ·) k) fun x hl hP => ⟨_, hm x hl hP⟩ convert(mul_lt_mul_right <| seed.succ_pos.trans_le hl).2 hk rw [one_mul] #align nat.cauchy_induction_mul Nat.cauchy_induction_mul -/ #print Nat.cauchy_induction_two_mul /- theorem Nat.cauchy_induction_two_mul (seed : ℕ) (hs : P seed.succ) (hm : ∀ x, seed < x → P x → P (2 * x)) (n : ℕ) : P n := Nat.cauchy_induction_mul h 2 seed one_lt_two hs hm n #align nat.cauchy_induction_two_mul Nat.cauchy_induction_two_mul -/ end Induction
Require Import Memory Memimpl. Require Import Unusedglobproof. Module Mem. Export Memimpl.Mem. Export Unusedglobproof.Mem. Local Existing Instances memory_model_ops memory_model_prf. Local Instance memory_model_x_prf: MemoryModelX mem. Proof. split. exact Memimpl.Mem.zero_delta_inject. Qed. End Mem.
{-# OPTIONS --universe-polymorphism #-} module TrustMe where open import Common.Equality postulate A : Set x : A eq : x ≡ x eq = primTrustMe evaluates-to-refl : sym (sym eq) ≡ eq evaluates-to-refl = refl
State Before: k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : Ring k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hp : p ∈ s ⊢ ↑(direction s) = (fun x => x -ᵥ p) '' ↑s State After: k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : Ring k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hp : p ∈ s ⊢ ↑s -ᵥ ↑s = (fun x => x -ᵥ p) '' ↑s Tactic: rw [coe_direction_eq_vsub_set ⟨p, hp⟩] State Before: k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : Ring k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hp : p ∈ s ⊢ ↑s -ᵥ ↑s = (fun x => x -ᵥ p) '' ↑s State After: case refine'_1 k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : Ring k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hp : p ∈ s ⊢ ↑s -ᵥ ↑s ≤ (fun x => x -ᵥ p) '' ↑s case refine'_2 k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : Ring k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hp : p ∈ s ⊢ (fun x => x -ᵥ p) '' ↑s ≤ ↑s -ᵥ ↑s Tactic: refine' le_antisymm _ _ State Before: case refine'_1 k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : Ring k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hp : p ∈ s ⊢ ↑s -ᵥ ↑s ≤ (fun x => x -ᵥ p) '' ↑s State After: case refine'_1.intro.intro.intro.intro k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : Ring k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hp : p ∈ s p1 p2 : P hp1 : p1 ∈ ↑s hp2 : p2 ∈ ↑s ⊢ (fun x x_1 => x -ᵥ x_1) p1 p2 ∈ (fun x => x -ᵥ p) '' ↑s Tactic: rintro v ⟨p1, p2, hp1, hp2, rfl⟩ State Before: case refine'_1.intro.intro.intro.intro k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : Ring k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hp : p ∈ s p1 p2 : P hp1 : p1 ∈ ↑s hp2 : p2 ∈ ↑s ⊢ (fun x x_1 => x -ᵥ x_1) p1 p2 ∈ (fun x => x -ᵥ p) '' ↑s State After: no goals Tactic: exact ⟨p1 -ᵥ p2 +ᵥ p, vadd_mem_of_mem_direction (vsub_mem_direction hp1 hp2) hp, vadd_vsub _ _⟩ State Before: case refine'_2 k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : Ring k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hp : p ∈ s ⊢ (fun x => x -ᵥ p) '' ↑s ≤ ↑s -ᵥ ↑s State After: case refine'_2.intro.intro k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : Ring k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hp : p ∈ s p2 : P hp2 : p2 ∈ ↑s ⊢ (fun x => x -ᵥ p) p2 ∈ ↑s -ᵥ ↑s Tactic: rintro v ⟨p2, hp2, rfl⟩ State Before: case refine'_2.intro.intro k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : Ring k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hp : p ∈ s p2 : P hp2 : p2 ∈ ↑s ⊢ (fun x => x -ᵥ p) p2 ∈ ↑s -ᵥ ↑s State After: no goals Tactic: exact ⟨p2, p, hp2, hp, rfl⟩
{-# OPTIONS --without-K --safe #-} module Categories.Comonad.Relative where open import Level open import Categories.Category using (Category) open import Categories.Functor using (Functor; Endofunctor; _∘F_) renaming (id to idF) import Categories.Morphism.Reasoning as MR open import Categories.NaturalTransformation renaming (id to idN) open import Categories.NaturalTransformation.NaturalIsomorphism hiding (_≃_) open import Categories.NaturalTransformation.Equivalence open NaturalIsomorphism private variable o ℓ e o′ ℓ′ e′ : Level C : Category o ℓ e D : Category o′ ℓ′ e′ record Comonad {C : Category o ℓ e} {D : Category o′ ℓ′ e′} (J : Functor C D) : Set (o ⊔ o′ ⊔ ℓ′ ⊔ e′) where private module C = Category C module D = Category D module J = Functor J open D using (_⇒_; _∘_; _≈_) field F₀ : C.Obj → D.Obj counit : {c : C.Obj} → F₀ c ⇒ J.₀ c cobind : {x y : C.Obj} → (F₀ x ⇒ J.₀ y) → F₀ x ⇒ F₀ y identityʳ : {x y : C.Obj} { k : F₀ x ⇒ J.₀ y} → counit ∘ cobind k ≈ k identityˡ : {x : C.Obj} → cobind {x} counit ≈ D.id assoc : {x y z : C.Obj} {k : F₀ x ⇒ J.₀ y} {l : F₀ y ⇒ J.₀ z} → cobind (l ∘ cobind k) ≈ cobind l ∘ cobind k cobind-≈ : {x y : C.Obj} {k h : F₀ x ⇒ J.₀ y} → k ≈ h → cobind k ≈ cobind h -- From a Relative Comonad, we can extract a functor RComonad⇒Functor : {J : Functor C D} → Comonad J → Functor C D RComonad⇒Functor {C = C} {D = D} {J = J} r = record { F₀ = F₀ ; F₁ = λ f → cobind (J.₁ f ∘ counit) ; identity = identity′ ; homomorphism = hom′ ; F-resp-≈ = λ f≈g → cobind-≈ (∘-resp-≈ˡ (J.F-resp-≈ f≈g)) } where open Comonad r module C = Category C module D = Category D module J = Functor J open Category D hiding (identityˡ; identityʳ; assoc) open HomReasoning open MR D identity′ : {c : C.Obj} → cobind {c} (J.₁ C.id ∘ counit) ≈ id identity′ = begin cobind (J.₁ C.id ∘ counit) ≈⟨ cobind-≈ (elimˡ J.identity) ⟩ cobind counit ≈⟨ identityˡ ⟩ id ∎ hom′ : {X Y Z : C.Obj} {f : X C.⇒ Y} {g : Y C.⇒ Z} → cobind (J.₁ (g C.∘ f) ∘ counit) ≈ cobind (J.₁ g ∘ counit) ∘ cobind (J.₁ f ∘ counit) hom′ {f = f} {g} = begin cobind (J.₁ (g C.∘ f) ∘ counit) ≈⟨ cobind-≈ (pushˡ J.homomorphism) ⟩ cobind (J.₁ g ∘ J.₁ f ∘ counit) ≈⟨ cobind-≈ (pushʳ (⟺ identityʳ)) ⟩ cobind ((J.₁ g ∘ counit) ∘ (cobind (J.F₁ f ∘ counit))) ≈⟨ assoc ⟩ cobind (J.₁ g ∘ counit) ∘ cobind (J.F₁ f ∘ counit) ∎
Formal statement is: lemma LIMSEQ_offset: "(\<lambda>n. f (n + k)) \<longlonglongrightarrow> a \<Longrightarrow> f \<longlonglongrightarrow> a" Informal statement is: If the sequence $f(n + k)$ converges to $a$, then the sequence $f(n)$ converges to $a$.
module Cat where open import Agda.Builtin.Equality {- A category is very much like a graph. It has vertices named objects and vertices named arrows. Each arrow goes from an object to an object (possibly the same!). -} record Cat (obj : Set) (arr : obj -> obj -> Set) : Set where constructor MkCat field {- For each object, there is an arrow called `id` which goes from the object to itself. -} id : {o : obj} -> arr o o {- Given an arrow `f` from object `a` to `b` and an arrow `g` from `b` to `c`. We can compose these arrow. The result is an arrow from `a` to `c`. -} compose : {a b c : obj} -> arr a b -> arr b c -> arr a c -- Here comes some properties of `id` and `compose` {- For any arrow `f`, compose id f = f -} neutralLeft : {a b : obj} -> (f : arr a b) -> compose id f ≡ f {- For any arrow `f`, compose f id = f -} neutralRight : {a b : obj} -> (f : arr a b) -> compose f id ≡ f {- For any arrows `f`, `g` and `h`, composing f with g, and then the result with h gives exatctly the same result as composing f with the result of the composition of g and h Which means, like string concatenation than we can commpose the way we preserve the order of each element in the sequence. -} associativity : {a b c d : obj} -> (f : arr a b) -> (g : arr b c) -> (h : arr c d) -> compose f (compose g h) ≡ compose (compose f g) h open import Agda.Builtin.Nat {- `LE n m` encode the property that `n ≤ m` i.e. `n` is less or equal to `m` -} data LE : Nat -> Nat -> Set where LERefl : {n : Nat} -> LE n n LENext : {n m : Nat} -> LE n m -> LE n (suc m) {- Taking naturals as objects and `LE` as arrows, this actually forms a category! -} natPoset : Cat Nat LE natPoset = ???
-- {-# OPTIONS -v tc.rec:100 -v tc.signature:20 #-} module Issue414 where record P : Set₁ where field q : Set x : P x = record { q = q } -- Andreas 2011-05-19 -- record constructor should have been added to the signature -- before record module is constructed!
This method is very simple to implement for different photocurable resins to create 3D porous objects with complicated shapes. In addition, this new method has the advantages of self-supporting and can be used to print hollow components, especially the part with Droste effect (one object within another). Georgia Tech is one university in the US that has embraced the utility of MakerSpaces for students. A number of the facilities have been opened by the university in specific schools, including one for Materials Science and Engineering in the Materials Innovation & Learning Lab. In December 2016, 3D Printing Industry also reported on Georgia Tech’s development of personal 3D printed valves that can be used in planning for heart procedures. To stay up to date on the latest research relating to 3D printing sign up to the 3D Printing Industry newsletter, and follow our active social media channels. You can also vote now in the 1st annual 3D Printing Industry Awards.
{-# LANGUAGE BangPatterns, DeriveDataTypeable, DeriveGeneric #-} -- | -- Module : Statistics.Resampling -- Copyright : (c) 2009, 2010 Bryan O'Sullivan -- License : BSD3 -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- Resampling statistics. module Statistics.Resampling ( Resample(..) , jackknife , jackknifeMean , jackknifeVariance , jackknifeVarianceUnb , jackknifeStdDev , resample , estimate , splitGen ) where import Data.Aeson (FromJSON, ToJSON) import Control.Concurrent (forkIO, newChan, readChan, writeChan) import Control.Monad (forM_, liftM, replicateM, replicateM_) import Data.Binary (Binary(..)) import Data.Data (Data, Typeable) import Data.Vector.Algorithms.Intro (sort) import Data.Vector.Binary () import Data.Vector.Generic (unsafeFreeze) import Data.Word (Word32) import GHC.Conc (numCapabilities) import GHC.Generics (Generic) import Numeric.Sum (Summation(..), kbn) import Statistics.Function (indices) import Statistics.Sample (mean, stdDev, variance, varianceUnbiased) import Statistics.Types (Estimator(..), Sample) import System.Random.MWC (GenIO, initialize, uniform, uniformVector) import qualified Data.Vector.Generic as G import qualified Data.Vector.Unboxed as U import qualified Data.Vector.Unboxed.Mutable as MU -- | A resample drawn randomly, with replacement, from a set of data -- points. Distinct from a normal array to make it harder for your -- humble author's brain to go wrong. newtype Resample = Resample { fromResample :: U.Vector Double } deriving (Eq, Read, Show, Typeable, Data, Generic) instance FromJSON Resample instance ToJSON Resample instance Binary Resample where put = put . fromResample get = fmap Resample get -- | /O(e*r*s)/ Resample a data set repeatedly, with replacement, -- computing each estimate over the resampled data. -- -- This function is expensive; it has to do work proportional to -- /e*r*s/, where /e/ is the number of estimation functions, /r/ is -- the number of resamples to compute, and /s/ is the number of -- original samples. -- -- To improve performance, this function will make use of all -- available CPUs. At least with GHC 7.0, parallel performance seems -- best if the parallel garbage collector is disabled (RTS option -- @-qg@). resample :: GenIO -> [Estimator] -- ^ Estimation functions. -> Int -- ^ Number of resamples to compute. -> Sample -- ^ Original sample. -> IO [Resample] resample gen ests numResamples samples = do let !numSamples = U.length samples ixs = scanl (+) 0 $ zipWith (+) (replicate numCapabilities q) (replicate r 1 ++ repeat 0) where (q,r) = numResamples `quotRem` numCapabilities results <- mapM (const (MU.new numResamples)) ests done <- newChan gens <- splitGen numCapabilities gen forM_ (zip3 ixs (tail ixs) gens) $ \ (start,!end,gen') -> do forkIO $ do let loop k ers | k >= end = writeChan done () | otherwise = do re <- U.replicateM numSamples $ do r <- uniform gen' return (U.unsafeIndex samples (r `mod` numSamples)) forM_ ers $ \(est,arr) -> MU.write arr k . est $ re loop (k+1) ers loop start (zip ests' results) replicateM_ numCapabilities $ readChan done mapM_ sort results mapM (liftM Resample . unsafeFreeze) results where ests' = map estimate ests -- | Run an 'Estimator' over a sample. estimate :: Estimator -> Sample -> Double estimate Mean = mean estimate Variance = variance estimate VarianceUnbiased = varianceUnbiased estimate StdDev = stdDev estimate (Function est) = est -- | /O(n) or O(n^2)/ Compute a statistical estimate repeatedly over a -- sample, each time omitting a successive element. jackknife :: Estimator -> Sample -> U.Vector Double jackknife Mean sample = jackknifeMean sample jackknife Variance sample = jackknifeVariance sample jackknife VarianceUnbiased sample = jackknifeVarianceUnb sample jackknife StdDev sample = jackknifeStdDev sample jackknife (Function est) sample | G.length sample == 1 = singletonErr "jackknife" | otherwise = U.map f . indices $ sample where f i = est (dropAt i sample) -- | /O(n)/ Compute the jackknife mean of a sample. jackknifeMean :: Sample -> U.Vector Double jackknifeMean samp | len == 1 = singletonErr "jackknifeMean" | otherwise = G.map (/l) $ G.zipWith (+) (pfxSumL samp) (pfxSumR samp) where l = fromIntegral (len - 1) len = G.length samp -- | /O(n)/ Compute the jackknife variance of a sample with a -- correction factor @c@, so we can get either the regular or -- \"unbiased\" variance. jackknifeVariance_ :: Double -> Sample -> U.Vector Double jackknifeVariance_ c samp | len == 1 = singletonErr "jackknifeVariance" | otherwise = G.zipWith4 go als ars bls brs where als = pfxSumL . G.map goa $ samp ars = pfxSumR . G.map goa $ samp goa x = v * v where v = x - m bls = pfxSumL . G.map (subtract m) $ samp brs = pfxSumR . G.map (subtract m) $ samp m = mean samp n = fromIntegral len go al ar bl br = (al + ar - (b * b) / q) / (q - c) where b = bl + br q = n - 1 len = G.length samp -- | /O(n)/ Compute the unbiased jackknife variance of a sample. jackknifeVarianceUnb :: Sample -> U.Vector Double jackknifeVarianceUnb = jackknifeVariance_ 1 -- | /O(n)/ Compute the jackknife variance of a sample. jackknifeVariance :: Sample -> U.Vector Double jackknifeVariance = jackknifeVariance_ 0 -- | /O(n)/ Compute the jackknife standard deviation of a sample. jackknifeStdDev :: Sample -> U.Vector Double jackknifeStdDev = G.map sqrt . jackknifeVarianceUnb pfxSumL :: U.Vector Double -> U.Vector Double pfxSumL = G.map kbn . G.scanl add zero pfxSumR :: U.Vector Double -> U.Vector Double pfxSumR = G.tail . G.map kbn . G.scanr (flip add) zero -- | Drop the /k/th element of a vector. dropAt :: U.Unbox e => Int -> U.Vector e -> U.Vector e dropAt n v = U.slice 0 n v U.++ U.slice (n+1) (U.length v - n - 1) v singletonErr :: String -> a singletonErr func = error $ "Statistics.Resampling." ++ func ++ ": singleton input" -- | Split a generator into several that can run independently. splitGen :: Int -> GenIO -> IO [GenIO] splitGen n gen | n <= 0 = return [] | otherwise = fmap (gen:) . replicateM (n-1) $ initialize =<< (uniformVector gen 256 :: IO (U.Vector Word32))
The convex hull of a set $p$ is the set of all points $x$ that can be written as a convex combination of at most $n + 1$ points in $p$, where $n$ is the dimension of the space.
#include <bunsan/process/executor.hpp> #include <bunsan/process/native_executor.hpp> #include <mutex> #include <boost/assert.hpp> namespace bunsan::process { static std::mutex global_lock; static executor_ptr global_instance; static void register_native_unlocked() { global_instance = std::make_shared<native_executor>(); } executor::~executor() {} void executor::register_native() { const std::lock_guard<std::mutex> lk(global_lock); register_native_unlocked(); BOOST_ASSERT(global_instance); } void executor::register_instance(std::shared_ptr<executor> impl) { BOOST_ASSERT(impl); const std::lock_guard<std::mutex> lk(global_lock); global_instance = impl; } executor_ptr executor::instance() { const std::lock_guard<std::mutex> lk(global_lock); if (!global_instance) register_native_unlocked(); BOOST_ASSERT(global_instance); return global_instance; } } // namespace bunsan::process
State Before: α : Type u n : ℕ f : Fin n → α ⊢ ofFn f = [] ↔ n = 0 State After: no goals Tactic: cases n <;> simp only [ofFn_zero, ofFn_succ, eq_self_iff_true, Nat.succ_ne_zero]
import analysis.special_functions.exp open real variables a b c d e : ℝ #check le_refl #check add_lt_add_of_lt_of_le #check add_lt_add_of_le_of_lt #check exp_lt_exp.mpr -- BEGIN example (h₀ : a ≤ b) (h₁ : c < d) : a + exp c + e < b + exp d + e := begin apply add_lt_add_of_lt_of_le, { sorry, }, sorry, end -- END
{-# OPTIONS --cubical --no-import-sorts --safe #-} module Cubical.Algebra.RingSolver.Examples where open import Cubical.Foundations.Prelude open import Cubical.Algebra.CommRing open import Cubical.Algebra.RingSolver.ReflectionSolving private variable ℓ : Level module Test (R : CommRing {ℓ}) where open CommRingStr (snd R) _ : 1r · (1r + 0r) ≡ (1r · 0r) + 1r _ = solve R _ : 1r · 0r + (1r - 1r) ≡ 0r - 0r _ = solve R _ : (x : fst R) → x ≡ x _ = solve R _ : (x y : fst R) → x ≡ x _ = solve R _ : (x y : fst R) → x + y ≡ y + x _ = solve R _ : (x y : fst R) → (x + y) · (x - y) ≡ x · x - y · y _ = solve R {- A bigger example, copied from the other example files: -} _ : (x y z : (fst R)) → (x + y) · (x + y) · (x + y) · (x + y) ≡ x · x · x · x + (fromℤ R 4) · x · x · x · y + (fromℤ R 6) · x · x · y · y + (fromℤ R 4) · x · y · y · y + y · y · y · y _ = solve R {- Keep in mind, that the solver can lead to wrong error locations. For example, the commented code below tries to solve an equation that does not hold, with the result of an error at the wrong location. _ : (x y : (fst R)) → x ≡ y _ = solve R -}
Formal statement is: lemma islimpt_sequential: fixes x :: "'a::first_countable_topology" shows "x islimpt S \<longleftrightarrow> (\<exists>f. (\<forall>n::nat. f n \<in> S - {x}) \<and> (f \<longlongrightarrow> x) sequentially)" (is "?lhs = ?rhs") Informal statement is: A point $x$ is a limit point of a set $S$ if and only if there exists a sequence of points in $S$ that converges to $x$.
[STATEMENT] lemma parent_upper_bound: "parent l c < c \<longleftrightarrow> l \<le> c" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (parent l c < c) = (l \<le> c) [PROOF STEP] unfolding parent_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. (l + (c - l - 1) div 2 < c) = (l \<le> c) [PROOF STEP] by auto
{-# OPTIONS --cubical --no-import-sorts --safe #-} open import Cubical.Core.Everything open import Cubical.Algebra.Magma module Cubical.Algebra.Magma.Construct.Opposite {ℓ} (M : Magma ℓ) where open import Cubical.Foundations.Prelude open Magma M _•ᵒᵖ_ : Op₂ Carrier y •ᵒᵖ x = x • y Op-isMagma : IsMagma Carrier _•ᵒᵖ_ Op-isMagma = record { is-set = is-set } Mᵒᵖ : Magma ℓ Mᵒᵖ = record { isMagma = Op-isMagma }
State Before: α : Type u_1 inst✝ : LinearOrder α s t : Set α x y z : α ⊢ y ∈ ordConnectedComponent s x ↔ x ∈ ordConnectedComponent s y State After: no goals Tactic: rw [mem_ordConnectedComponent, mem_ordConnectedComponent, uIcc_comm]
library(rstan) args_line <- as.list(commandArgs(trailingOnly=TRUE)) if(length(args_line) > 0) { stopifnot(args_line[[1]]=='-csv_file') stopifnot(args_line[[3]]=='-rda_file') args <- list() args[['csv_file']] <- args_line[[2]] args[['rda_file']] <- args_line[[4]] } # convert to stanfit object and save fit <- rstan::read_stan_csv(args$csv_file) save(fit, file=args$rda_file)
{-# OPTIONS --cubical --safe #-} module Data.List.Smart where open import Prelude open import Data.Nat.Properties using (_≡ᴮ_; complete-==) infixr 5 _∷′_ _++′_ data List {a} (A : Type a) : Type a where []′ : List A _∷′_ : A → List A → List A _++′_ : List A → List A → List A sz′ : List A → ℕ → ℕ sz′ []′ k = k sz′ (x ∷′ xs) k = k sz′ (xs ++′ ys) k = suc (sz′ xs (sz′ ys k)) sz : List A → ℕ sz []′ = zero sz (x ∷′ xs) = zero sz (xs ++′ ys) = sz′ xs (sz ys) _HasSize_ : List A → ℕ → Type xs HasSize n = T (sz xs ≡ᴮ n) data ListView {a} (A : Type a) : Type a where Nil : ListView A Cons : A → List A → ListView A viewˡ : List A → ListView A viewˡ xs = go xs (sz xs) (complete-== (sz xs)) where go : (xs : List A) → (n : ℕ) → xs HasSize n → ListView A go []′ n p = Nil go (x ∷′ xs) n p = Cons x xs go ((x ∷′ xs) ++′ ys) n p = Cons x (xs ++′ ys) go ([]′ ++′ ys) n p = go ys n p go ((xs ++′ ys) ++′ zs) (suc n) p = go (xs ++′ (ys ++′ zs)) n p
Require Import util. Require Import Fourier. Require Export flow. Set Implicit Arguments. Open Local Scope R_scope. Require Import Coq.Reals.Reals. Section function_properties. Variable f: R -> R. Definition strongly_increasing: Prop := forall x x', x < x' -> f x < f x'. Definition strongly_decreasing: Prop := forall x x', x < x' -> f x' < f x. Lemma mildly_increasing: strongly_increasing -> forall x x', x <= x' -> f x <= f x'. Proof with auto with real. intros. destruct H0... subst... Qed. Lemma mildly_decreasing: strongly_decreasing -> forall x x', x <= x' -> f x' <= f x. Proof with auto with real. intros. destruct H0... subst... Qed. Lemma strongly_increasing_rev: strongly_increasing -> forall x x', f x < f x' -> x < x'. Proof with auto with real. unfold strongly_increasing. intros. destruct (Rlt_le_dec x x')... destruct (Rle_lt_or_eq_dec x' x r). elimtype False... apply (Rlt_asym _ _ H0)... subst. elimtype False. apply (Rlt_irrefl _ H0). Qed. Lemma strongly_decreasing_rev: strongly_decreasing -> forall x x', f x < f x' -> x' < x. Proof with auto with real. unfold strongly_decreasing. intros. destruct (Rlt_le_dec x x'). elimtype False... apply (Rlt_asym _ _ H0)... destruct (Rle_lt_or_eq_dec x' x r)... subst. elimtype False. apply (Rlt_irrefl _ H0). Qed. Definition monotonic: Set := { strongly_increasing } + { strongly_decreasing }. Lemma mono_eq: monotonic -> forall x x', f x = f x' <-> x = x'. Proof with auto. split. intros. destruct (Rle_lt_dec x x'). destruct r... elimtype False. destruct H; set (s _ _ H1); rewrite H0 in r; apply Rlt_irrefl with (f x')... elimtype False. destruct H; set (s _ _ r); rewrite H0 in r0; apply Rlt_irrefl with (f x')... intros. subst... Qed. End function_properties. Section single_inverses. Variable f: Flow R. Definition mono: Set := { forall x, strongly_increasing (f x) } + { forall x, strongly_decreasing (f x) }. Variable fmono: mono. Lemma purify_mono: forall x, monotonic (f x). Proof. intros. unfold monotonic. destruct fmono; set (s x); [left | right]; assumption. Qed. Definition mle (x x': R): Prop := if fmono then x <= x' else x' <= x. Definition mlt (x x': R): Prop := if fmono then x < x' else x' < x. Lemma mle_refl x: mle x x. Proof. unfold mle. destruct fmono; simpl; auto with real. Qed. Lemma mle_trans x y z: mle x y -> mle y z -> mle x z. Proof. unfold mle. destruct fmono; simpl; intros; apply Rle_trans with y; assumption. Qed. Lemma mlt_le x x': mlt x x' -> mle x x'. Proof. unfold mlt, mle. destruct fmono; simpl; auto with real. Qed. Lemma mle_lt_or_eq_dec x x': mle x x' -> { mlt x x' } + { x = x' }. Proof with auto with real. unfold mle, mlt. destruct fmono; simpl; intros. apply Rle_lt_or_eq_dec... destruct (Rle_lt_or_eq_dec _ _ H)... Qed. Lemma mono_opp v t t': t' <= t -> mle (f v t') (f v t). Proof with auto with real. unfold mle. destruct fmono. intros. set (s v). unfold strongly_increasing in s0. destruct H... subst... intros. set (s v). unfold strongly_increasing in s0. destruct H... subst... Qed. Variables (inv: R -> R -> Time) (inv_correct: forall x x', f x (inv x x') = x'). Definition f_eq x t t': f x t = f x t' <-> t = t' := mono_eq (purify_mono x) t t'. Lemma inv_correct' x t: inv x (f x t) = t. Proof. intros. destruct (f_eq x (inv x (f x t)) t). clear H0. apply H. rewrite inv_correct. reflexivity. Qed. Lemma inv_plus x y z: inv x z = inv x y + inv y z. Proof with auto. intros. destruct (f_eq x (inv x z) (inv x y + inv y z)). clear H0. apply H. rewrite flow_additive... repeat rewrite inv_correct... Qed. Lemma inv_refl x: inv x x = 0. Proof with auto. intros. destruct (f_eq x (inv x x) 0). clear H0. apply H. repeat rewrite inv_correct... rewrite flow_zero... Qed. Lemma f_lt x t t': mlt (f x t) (f x t') -> t < t'. Proof with auto with real. unfold mlt. destruct fmono; intros. apply strongly_increasing_rev with (f x)... apply strongly_decreasing_rev with (f x)... Qed. Lemma f_le x t t': mle (f x t) (f x t') -> t <= t'. Proof with auto with real. unfold mle. intros. set (f_lt x t t'). clearbody r. unfold mlt in r. destruct fmono; destruct H. apply Rlt_le... right. destruct (f_eq x t t')... apply Rlt_le... right. destruct (f_eq x t t')... Qed. Lemma inv_lt_right a x x': inv a x < inv a x' <-> mlt x x'. Proof with auto. unfold mlt. split; intros. replace x with (f a (inv a x))... replace x' with (f a (inv a x'))... destruct fmono; apply s... set f_lt. clearbody r. unfold mlt in r. destruct fmono; apply r with a; repeat rewrite inv_correct... Qed. Lemma inv_pos x x': 0 < inv x x' <-> mlt x x'. Proof with auto with real. unfold mlt. split; intros. set f_lt. clearbody r. intros. replace x with (f x 0)... replace x' with (f x (inv x x'))... destruct fmono; apply s... rewrite flow_zero... rewrite <- inv_refl with x. destruct (inv_lt_right x x x')... Qed. Lemma inv_very_correct t x: inv (f x t) x = -t. Proof with auto with real. intros. assert (inv x x = 0). apply inv_refl. rewrite (inv_plus x (f x t) x) in H. rewrite inv_correct' in H. replace (-t) with (0-t)... rewrite <- H. unfold Rminus. rewrite Rplus_comm. rewrite <- Rplus_assoc. rewrite Rplus_opp_l... Qed. Lemma inv_inv x y: inv x y = - inv y x. Proof with auto with real. intros. set (inv_very_correct (inv y x) y). rewrite inv_correct in e... Qed. Lemma inv_uniq_0 x x': inv x x' = - inv 0 x + inv 0 x'. Proof. intros. rewrite (inv_plus x 0 x'). rewrite (inv_inv x 0). auto with real. Qed. (* hm, this shows that inv is uniquely determined by the values it takes with 0 as first argument. perhaps the reason we don't just take inv as a unary function is that it is problematic for flow functions with singularities at 0? *) Lemma inv_le a x x': mle x x' -> inv a x <= inv a x'. Proof with auto. intros. set f_le. clearbody r. apply r with a. do 2 rewrite inv_correct... Qed. Lemma inv_nonneg x x': 0 <= inv x x' <-> mle x x'. Proof with auto with real. unfold mle. split; intros. set f_le. clearbody r. intros. replace x with (f x 0)... replace x' with (f x (inv x x'))... apply mono_opp... apply flow_zero. rewrite <- inv_refl with x. apply inv_le... Qed. Lemma inv_zero x x': inv x x' = 0 <-> x = x'. Proof with auto. split; intros. replace x' with (f x (inv x x'))... rewrite H. rewrite flow_zero... subst. rewrite inv_refl... Qed. Lemma f_lt_left x x' t: x < x' <-> f x t < f x' t. Proof with auto with real. split. intros. replace x' with (f x (inv x x'))... rewrite <- flow_additive... destruct (inv_pos x x'). destruct (inv_pos x' x). unfold mlt in *. destruct fmono. apply s. set (H1 H). fourier. apply s. rewrite inv_inv. set (H3 H). fourier. set f_lt. set inv_pos. clearbody r i. unfold mlt in r, i. destruct fmono; intros. replace (f x' t) with (f (f x (inv x x')) t) in H... rewrite <- flow_additive in H... set (r _ _ _ H). assert (0 < inv x x') by fourier. destruct (i x x'). apply H1... rewrite inv_correct... replace (f x t) with (f (f x' (inv x' x)) t) in H... rewrite <- flow_additive in H... set (r _ _ _ H). assert (0 < inv x' x) by fourier. destruct (i x' x). apply H1... rewrite inv_correct... Qed. Lemma f_eq_left x x' t: f x t = f x' t <-> x = x'. Proof with auto with real. intros. split; intros. intros. destruct (Rlt_le_dec x x'). elimtype False. destruct (f_lt_left x x' t). set (H0 r). rewrite H in r0. apply (Rlt_asym _ _ r0)... destruct (Rle_lt_or_eq_dec _ _ r)... elimtype False. destruct (f_lt_left x' x t). set (H0 r0). rewrite H in r1. apply (Rlt_asym _ _ r1)... subst... Qed. Lemma f_le_left x x' t: x <= x' <-> f x t <= f x' t. Proof with auto with real. intros. destruct (f_lt_left x x' t). split; intro. destruct H1... subst... destruct H1. destruct (f_lt_left x x' t)... replace x' with x... destruct (f_eq_left x x' t)... Qed. Lemma inv_lt_left a x x': mlt x x' <-> inv x' a < inv x a. Proof with auto with real. unfold mlt. intros. rewrite (inv_inv x' a). rewrite (inv_inv x a). destruct (inv_lt_right a x x'). split... intros. apply H... Qed. Lemma inv_le_left a x x': mle x x' -> inv x' a <= inv x a. Proof with auto with real. unfold mle. intros. destruct (inv_lt_left a x x'). unfold mlt in *. destruct fmono; intros; destruct H; subst... Qed. Lemma inv_eq_right a x x': inv a x = inv a x' <-> x = x'. Proof with auto with real. split. intros. replace x with (f a (inv a x))... replace x' with (f a (inv a x'))... intros... Qed. Lemma inv_le_right a x x': inv a x <= inv a x' <-> mle x x'. Proof with auto with real. intros. destruct (inv_lt_right a x x'). split; intro. destruct H1. apply mlt_le... rewrite (conj_fst (inv_eq_right a x x') H1). apply mle_refl. destruct (mle_lt_or_eq_dec _ _ H1)... subst... Qed. Lemma mle_flow t x: 0 <= t -> mle x (f x t). Proof with auto. intros. apply mle_trans with (f x 0). rewrite flow_zero... apply mle_refl. apply mono_opp... Qed. End single_inverses.
[STATEMENT] lemma domains_simp: assumes "arr f" shows "domains f = {dom f}" [PROOF STATE] proof (prove) goal (1 subgoal): 1. domains f = {local.dom f} [PROOF STEP] using assms dom_in_domains has_domain_iff_arr domain_unique [PROOF STATE] proof (prove) using this: arr f domains ?f \<noteq> {} \<Longrightarrow> local.dom ?f \<in> domains ?f (domains ?f \<noteq> {}) = arr ?f \<lbrakk>?a \<in> domains ?f; ?a' \<in> domains ?f\<rbrakk> \<Longrightarrow> ?a = ?a' goal (1 subgoal): 1. domains f = {local.dom f} [PROOF STEP] by auto
-- Conmutatividad de la conjunción -- =============================== -- Demostrar que -- P ∧ Q → Q ∧ P import tactic variables (P Q R : Prop) -- 1ª demostración -- =============== example : P ∧ Q → Q ∧ P := begin intro h, cases h with hP hQ, split, { exact hQ }, { exact hP }, end -- 2ª demostración -- =============== example : P ∧ Q → Q ∧ P := begin rintro ⟨hP, hQ⟩, exact ⟨hQ, hP⟩, end -- 3ª demostración -- =============== example : P ∧ Q → Q ∧ P := λ ⟨hP, hQ⟩, ⟨hQ, hP⟩ -- 4ª demostración -- =============== example : P ∧ Q → Q ∧ P := and.comm.mp -- 5ª demostración -- =============== example : P ∧ Q → Q ∧ P := begin assume h : P ∧ Q, have hP : P := h.left, have hQ : Q := h.right, show Q ∧ P, from ⟨hQ, hP⟩, end -- 6ª demostración -- =============== example : P ∧ Q → Q ∧ P := begin assume h : P ∧ Q, show Q ∧ P, from ⟨h.2, h.1⟩, end example : P ∧ Q → Q ∧ P := λ h, ⟨h.2, h.1⟩ -- 7ª demostración -- =============== example : P ∧ Q → Q ∧ P := by tauto -- 8ª demostración -- =============== example : P ∧ Q → Q ∧ P := by finish
theory T34 imports Main begin lemma "( (\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) & (\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(x, meet(y, z)) = join(over(x, y), over(x, z))) & (\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) & (\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) & (\<forall> x::nat. invo(invo(x)) = x) ) \<longrightarrow> (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(meet(x, y), z) = meet(mult(x, z), mult(y, z))) " nitpick[card nat=4,timeout=86400] oops end
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Scott Morrison, Simon Hudon ! This file was ported from Lean 3 source module category_theory.endomorphism ! leanprover-community/mathlib commit 32253a1a1071173b33dc7d6a218cf722c6feb514 ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathlib.Algebra.Hom.Equiv.Basic import Mathlib.CategoryTheory.Groupoid import Mathlib.CategoryTheory.Opposites import Mathlib.GroupTheory.GroupAction.Defs /-! # Endomorphisms Definition and basic properties of endomorphisms and automorphisms of an object in a category. For each `X : C`, we provide `CategoryTheory.End X := X ⟶ X` with a monoid structure, and `CategoryTheory.Aut X := X ≅ X ` with a group structure. -/ universe v v' u u' namespace CategoryTheory /-- Endomorphisms of an object in a category. Arguments order in multiplication agrees with `Function.comp`, not with `CategoryTheory.CategoryStruct.comp`. -/ def End {C : Type u} [CategoryStruct.{v} C] (X : C) := X ⟶ X #align category_theory.End CategoryTheory.End namespace End section Struct variable {C : Type u} [CategoryStruct.{v} C] (X : C) protected instance one : One (End X) := ⟨𝟙 X⟩ #align category_theory.End.has_one CategoryTheory.End.one protected instance inhabited : Inhabited (End X) := ⟨𝟙 X⟩ #align category_theory.End.inhabited CategoryTheory.End.inhabited /-- Multiplication of endomorphisms agrees with `Function.comp`, not with `CategoryTheory.CategoryStruct.comp`. -/ protected instance mul : Mul (End X) := ⟨fun x y => y ≫ x⟩ #align category_theory.End.has_mul CategoryTheory.End.mul variable {X} /-- Assist the typechecker by expressing a morphism `X ⟶ X` as a term of `CategoryTheory.End X`. -/ def of (f : X ⟶ X) : End X := f #align category_theory.End.of CategoryTheory.End.of /-- Assist the typechecker by expressing an endomorphism `f : CategoryTheory.End X` as a term of `X ⟶ X`. -/ def asHom (f : End X) : X ⟶ X := f #align category_theory.End.as_hom CategoryTheory.End.asHom @[simp] -- porting note: todo: use `of`/`asHom`? theorem one_def : (1 : End X) = 𝟙 X := rfl #align category_theory.End.one_def CategoryTheory.End.one_def @[simp] -- porting note: todo: use `of`/`asHom`? theorem mul_def (xs ys : End X) : xs * ys = ys ≫ xs := rfl #align category_theory.End.mul_def CategoryTheory.End.mul_def end Struct /-- Endomorphisms of an object form a monoid -/ instance monoid {C : Type u} [Category.{v} C] {X : C} : Monoid (End X) where mul_one := Category.id_comp one_mul := Category.comp_id mul_assoc := fun x y z => (Category.assoc z y x).symm #align category_theory.End.monoid CategoryTheory.End.monoid section MulAction variable {C : Type u} [Category.{v} C] open Opposite instance mulActionRight {X Y : C} : MulAction (End Y) (X ⟶ Y) where smul r f := f ≫ r one_smul := Category.comp_id mul_smul _ _ _ := Eq.symm <| Category.assoc _ _ _ #align category_theory.End.mul_action_right CategoryTheory.End.mulActionRight instance mulActionLeft {X : Cᵒᵖ} {Y : C} : MulAction (End X) (unop X ⟶ Y) where smul r f := r.unop ≫ f one_smul := Category.id_comp mul_smul _ _ _ := Category.assoc _ _ _ #align category_theory.End.mul_action_left CategoryTheory.End.mulActionLeft theorem smul_right {X Y : C} {r : End Y} {f : X ⟶ Y} : r • f = f ≫ r := rfl #align category_theory.End.smul_right CategoryTheory.End.smul_right theorem smul_left {X : Cᵒᵖ} {Y : C} {r : End X} {f : unop X ⟶ Y} : r • f = r.unop ≫ f := rfl #align category_theory.End.smul_left CategoryTheory.End.smul_left end MulAction /-- In a groupoid, endomorphisms form a group -/ instance group {C : Type u} [Groupoid.{v} C] (X : C) : Group (End X) where mul_left_inv := Groupoid.comp_inv inv := Groupoid.inv #align category_theory.End.group CategoryTheory.End.group end End theorem isUnit_iff_isIso {C : Type u} [Category.{v} C] {X : C} (f : End X) : IsUnit (f : End X) ↔ IsIso f := ⟨fun h => { out := ⟨h.unit.inv, ⟨h.unit.inv_val, h.unit.val_inv⟩⟩ }, fun h => ⟨⟨f, inv f, by simp, by simp⟩, rfl⟩⟩ #align category_theory.is_unit_iff_is_iso CategoryTheory.isUnit_iff_isIso variable {C : Type u} [Category.{v} C] (X : C) /-- Automorphisms of an object in a category. The order of arguments in multiplication agrees with `Function.comp`, not with `CategoryTheory.CategoryStruct.comp`. -/ def Aut (X : C) := X ≅ X set_option linter.uppercaseLean3 false in #align category_theory.Aut CategoryTheory.Aut namespace Aut protected instance inhabited : Inhabited (Aut X) := ⟨Iso.refl X⟩ set_option linter.uppercaseLean3 false in #align category_theory.Aut.inhabited CategoryTheory.Aut.inhabited instance : Group (Aut X) where one := Iso.refl X inv := Iso.symm mul x y := Iso.trans y x mul_assoc _ _ _ := (Iso.trans_assoc _ _ _).symm one_mul := Iso.trans_refl mul_one := Iso.refl_trans mul_left_inv := Iso.self_symm_id theorem Aut_mul_def (f g : Aut X) : f * g = g.trans f := rfl set_option linter.uppercaseLean3 false in #align category_theory.Aut.Aut_mul_def CategoryTheory.Aut.Aut_mul_def theorem Aut_inv_def (f : Aut X) : f⁻¹ = f.symm := rfl set_option linter.uppercaseLean3 false in #align category_theory.Aut.Aut_inv_def CategoryTheory.Aut.Aut_inv_def /-- Units in the monoid of endomorphisms of an object are (multiplicatively) equivalent to automorphisms of that object. -/ def unitsEndEquivAut : (End X)ˣ ≃* Aut X where toFun f := ⟨f.1, f.2, f.4, f.3⟩ invFun f := ⟨f.1, f.2, f.4, f.3⟩ left_inv := fun ⟨f₁, f₂, f₃, f₄⟩ => rfl right_inv := fun ⟨f₁, f₂, f₃, f₄⟩ => rfl map_mul' f g := by cases f; cases g; rfl set_option linter.uppercaseLean3 false in #align category_theory.Aut.units_End_equiv_Aut CategoryTheory.Aut.unitsEndEquivAut /-- Isomorphisms induce isomorphisms of the automorphism group -/ def autMulEquivOfIso {X Y : C} (h : X ≅ Y) : Aut X ≃* Aut Y where toFun x := ⟨h.inv ≫ x.hom ≫ h.hom, h.inv ≫ x.inv ≫ h.hom, _, _⟩ invFun y := ⟨h.hom ≫ y.hom ≫ h.inv, h.hom ≫ y.inv ≫ h.inv, _, _⟩ left_inv _ := by aesop_cat right_inv _ := by aesop_cat map_mul' := by simp [Aut_mul_def] set_option linter.uppercaseLean3 false in #align category_theory.Aut.Aut_mul_equiv_of_iso CategoryTheory.Aut.autMulEquivOfIso end Aut namespace Functor variable {D : Type u'} [Category.{v'} D] (f : C ⥤ D) /-- `f.map` as a monoid hom between endomorphism monoids. -/ @[simps] def mapEnd : End X →* End (f.obj X) where toFun := f.map map_mul' x y := f.map_comp y x map_one' := f.map_id X #align category_theory.functor.map_End CategoryTheory.Functor.mapEnd /-- `f.mapIso` as a group hom between automorphism groups. -/ def mapAut : Aut X →* Aut (f.obj X) where toFun := f.mapIso map_mul' x y := f.mapIso_trans y x map_one' := f.mapIso_refl X set_option linter.uppercaseLean3 false in #align category_theory.functor.map_Aut CategoryTheory.Functor.mapAut end Functor end CategoryTheory
open import Function using () renaming ( _∘′_ to _∘_ ) open import Relation.Binary.PropositionalEquality using ( _≡_ ; refl ; sym ; cong ; cong₂ ; subst ) open import AssocFree.Util using ( subst-natural ) import AssocFree.STLambdaC.Typ open Relation.Binary.PropositionalEquality.≡-Reasoning using ( begin_ ; _≡⟨_⟩_ ; _∎ ) module AssocFree.STLambdaC.Exp (TConst : Set) (Const : AssocFree.STLambdaC.Typ.Typ TConst → Set) where open module Typ = AssocFree.STLambdaC.Typ TConst using ( Typ ; Var ; Ctxt ; const ; _⇝_ ; [] ; [_] ; _++_ ; _∷_ ; _∈_ ; _≪_ ; _≫_ ; _⋙_ ; uniq ; singleton ; Case ; case ; inj₁ ; inj₂ ; inj₃ ; case-≪ ; case-≫ ; case-⋙ ; Case₃ ; case₃ ; caseˡ ; caseʳ ; caseˡ₃ ; caseʳ₃ ; case⁻¹ ; case-iso ) -- Syntax data Exp (Γ : Ctxt) : Typ → Set where const : ∀ {T} → Const T → Exp Γ T abs : ∀ T {U} → Exp (T ∷ Γ) U → Exp Γ (T ⇝ U) app : ∀ {T U} → Exp Γ (T ⇝ U) → Exp Γ T → Exp Γ U var : ∀ {T} → (T ∈ Γ) → Exp Γ T -- Shorthand var₀ : ∀ {Γ T} → Exp (T ∷ Γ) T var₀ {Γ} {T} = var (singleton T ≪ Γ) var₁ : ∀ {Γ T U} → Exp (U ∷ (T ∷ Γ)) T var₁ {Γ} {T} {U} = var ([ U ] ≫ singleton T ≪ Γ) var₂ : ∀ {Γ T U V} → Exp (V ∷ (U ∷ (T ∷ Γ))) T var₂ {Γ} {T} {U} {V} = var ([ V ] ≫ [ U ] ≫ singleton T ≪ Γ) -- Andreas Abel suggested defining substitution and renaming together, citing: -- -- Conor McBride -- Type Preserving Renaming and Substitution -- -- Thorsten Altenkirch and Bernhard Reus -- Monadic Presentations of Lambda Terms Using Generalized Inductive Types -- -- http://www2.tcs.ifi.lmu.de/~abel/ParallelSubstitution.agda -- The idea is to define two kinds, for expressions and variables, -- such that the kind of variables is contained in the kind of -- expressions (so admits recursion). mutual data Kind : Set where var : Kind exp : ∀ {k} → IsVar k → Kind data IsVar : Kind → Set where var : IsVar var Thing : Kind → Ctxt → Typ → Set Thing var Γ T = (T ∈ Γ) Thing (exp var) Γ T = Exp Γ T Substn : Kind → Ctxt → Ctxt → Set Substn k Γ Δ = ∀ {T} → (T ∈ Δ) → Thing k Γ T -- Convert between variables, things and expressions thing : ∀ {k Γ T} → (T ∈ Γ) → Thing k Γ T thing {var} x = x thing {exp var} x = var x expr : ∀ {k Γ T} → Thing k Γ T → Exp Γ T expr {var} x = var x expr {exp var} M = M -- Extensional equivalence on substitutions (note: not assuming extensionality) _≈_ : ∀ {k Γ Δ} → Substn k Γ Δ → Substn k Γ Δ → Set ρ ≈ σ = ∀ {T} x → ρ {T} x ≡ σ {T} x -- Identity substitution id : ∀ {k} Γ → Substn k Γ Γ id {var} Γ x = x id {exp var} Γ x = var x -- Product structure of substitutions fst : ∀ Γ Δ → Substn var (Γ ++ Δ) Γ fst Γ Δ x = x ≪ Δ snd : ∀ Γ Δ → Substn var (Γ ++ Δ) Δ snd Γ Δ x = Γ ≫ x choose : ∀ {k Γ Δ E T} → Substn k Γ Δ → Substn k Γ E → (Case T Δ E) → Thing k Γ T choose ρ σ (inj₁ x) = ρ x choose ρ σ (inj₂ x) = σ x _&&&_ : ∀ {k Γ Δ E} → Substn k Γ Δ → Substn k Γ E → Substn k Γ (Δ ++ E) (ρ &&& σ) = choose ρ σ ∘ case _ _ -- Singleton substitution ⟨_⟩ : ∀ {k Γ T} → Thing k Γ T → Substn k Γ [ T ] ⟨ M ⟩ x = subst (Thing _ _) (uniq x) M -- Cons on substitutions _◁_ : ∀ {k Γ Δ T} → Thing k Γ T → Substn k Γ Δ → Substn k Γ (T ∷ Δ) M ◁ σ = ⟨ M ⟩ &&& σ -- Applying a substitution mutual substn+ : ∀ {k} B Γ Δ → Substn k Γ Δ → ∀ {T} → Exp (B ++ Δ) T → Exp (B ++ Γ) T substn+ B Γ Δ σ (const c) = const c substn+ B Γ Δ σ (abs T M) = abs T (substn+ (T ∷ B) Γ Δ σ M) substn+ B Γ Δ σ (app M N) = app (substn+ B Γ Δ σ M) (substn+ B Γ Δ σ N) substn+ B Γ Δ σ (var x) = expr (xsubstn+ B Γ Δ σ (case B Δ x)) xsubstn+ : ∀ {k} B Γ Δ → Substn k Γ Δ → ∀ {T} → (Case T B Δ) → Thing k (B ++ Γ) T xsubstn+ B Γ Δ σ (inj₁ x) = thing (x ≪ Γ) xsubstn+ {var} B Γ Δ σ (inj₂ x) = B ≫ σ x xsubstn+ {exp var} B Γ Δ σ (inj₂ x) = substn+ [] (B ++ Γ) Γ (snd B Γ) (σ x) -- weaken* B (σ x) -- Shorthands substn* : ∀ {k Γ Δ} → Substn k Γ Δ → ∀ {T} → Exp Δ T → Exp Γ T substn* {k} {Γ} {Δ} = substn+ [] Γ Δ substn : ∀ {Γ T U} → Exp Γ T → Exp (T ∷ Γ) U → Exp Γ U substn {Γ} M = substn* (M ◁ id Γ) xweaken+ : ∀ B Γ Δ {T} → (T ∈ (B ++ Δ)) → (T ∈ (B ++ Γ ++ Δ)) xweaken+ B Γ Δ x = xsubstn+ B (Γ ++ Δ) Δ (snd Γ Δ) (case B Δ x) weaken+ : ∀ B Γ Δ {T} → Exp (B ++ Δ) T → Exp (B ++ Γ ++ Δ) T weaken+ B Γ Δ = substn+ B (Γ ++ Δ) Δ (snd Γ Δ) weaken* : ∀ Γ {Δ T} → Exp Δ T → Exp (Γ ++ Δ) T weaken* Γ {Δ} = weaken+ [] Γ Δ weakens* : ∀ {Γ Δ} E → Substn (exp var) Γ Δ → Substn (exp var) (E ++ Γ) Δ weakens* E σ x = weaken* E (σ x) weaken*ʳ : ∀ {Γ} Δ {T} → Exp Γ T → Exp (Γ ++ Δ) T weaken*ʳ {Γ} Δ = weaken+ Γ Δ [] weaken : ∀ {Γ} T {U} → Exp Γ U → Exp (T ∷ Γ) U weaken T = weaken* [ T ] -- Composition of substitutions _⊔_ : Kind → Kind → Kind k ⊔ var = k k ⊔ exp var = exp var _∙_ : ∀ {k l Γ Δ E} → Substn k Γ Δ → Substn l Δ E → Substn (k ⊔ l) Γ E _∙_ {k} {var} ρ σ = ρ ∘ σ _∙_ {k} {exp var} ρ σ = substn* ρ ∘ σ -- Functorial action of ++ on substitutions par : ∀ {k Γ Δ Φ Ψ T} → Substn k Γ Φ → Substn k Δ Ψ → (Case T Φ Ψ) → Thing k (Γ ++ Δ) T par {var} {Γ} {Δ} ρ σ (inj₁ x) = ρ x ≪ Δ par {var} {Γ} {Δ} ρ σ (inj₂ x) = Γ ≫ σ x par {exp var} {Γ} {Δ} ρ σ (inj₁ x) = weaken*ʳ Δ (ρ x) par {exp var} {Γ} {Δ} ρ σ (inj₂ x) = weaken* Γ (σ x) _+++_ : ∀ {k Γ Δ Φ Ψ} → Substn k Γ Δ → Substn k Φ Ψ → Substn k (Γ ++ Φ) (Δ ++ Ψ) (ρ +++ σ) = par ρ σ ∘ case _ _ -- Weakening a variable is a variable weaken*-var : ∀ Γ {Δ T} (x : T ∈ Δ) → weaken* Γ (var x) ≡ var (Γ ≫ x) weaken*-var Γ {Δ} x = cong (expr ∘ xsubstn+ [] (Γ ++ Δ) Δ (snd Γ Δ)) (case-≫ [] x) weaken*ʳ-var : ∀ {Γ} Δ {T} (x : T ∈ Γ) → weaken*ʳ Δ (var x) ≡ var (x ≪ Δ) weaken*ʳ-var {Γ} Δ x = cong (expr ∘ xsubstn+ Γ Δ [] (snd Δ [])) (case-≪ x []) weaken+-var₀ : ∀ B Γ Δ {T} → weaken+ (T ∷ B) Γ Δ (var₀ {B ++ Δ}) ≡ var₀ {B ++ Γ ++ Δ} weaken+-var₀ B Γ Δ {T} = cong (var ∘ xsubstn+ (T ∷ B) (Γ ++ Δ) Δ (snd Γ Δ)) (case-≪ (singleton T ≪ B) Δ) -- Substitution respects extensional equality substn+-cong : ∀ {k} B Γ Δ {σ : Substn k Γ Δ} {ρ : Substn k Γ Δ} → (σ ≈ ρ) → ∀ {T} M → substn+ B Γ Δ σ {T} M ≡ substn+ B Γ Δ ρ M substn+-cong B Γ Δ σ≈ρ (const c) = refl substn+-cong B Γ Δ σ≈ρ (abs T M) = cong (abs {B ++ Γ} T) (substn+-cong (T ∷ B) Γ Δ σ≈ρ M) substn+-cong B Γ Δ σ≈ρ (app M N) = cong₂ app (substn+-cong B Γ Δ σ≈ρ M) (substn+-cong B Γ Δ σ≈ρ N) substn+-cong B Γ Δ σ≈ρ (var x) = cong expr (xsubstn+-cong B Γ Δ σ≈ρ (case B Δ x)) where xsubstn+-cong : ∀ {k} B Γ Δ {σ : Substn k Γ Δ} {ρ : Substn k Γ Δ} → (σ ≈ ρ) → ∀ {T} x → xsubstn+ B Γ Δ σ {T} x ≡ xsubstn+ B Γ Δ ρ x xsubstn+-cong {var} B Γ Δ σ≈ρ (inj₁ x) = refl xsubstn+-cong {exp var} B Γ Δ σ≈ρ (inj₁ x) = refl xsubstn+-cong {var} B Γ Δ σ≈ρ (inj₂ x) = cong (_≫_ B) (σ≈ρ x) xsubstn+-cong {exp var} B Γ Δ σ≈ρ (inj₂ x) = cong (substn+ [] (B ++ Γ) Γ (snd B Γ)) (σ≈ρ x) substn*-cong : ∀ {k Γ Δ} {σ : Substn k Γ Δ} {ρ : Substn k Γ Δ} → (σ ≈ ρ) → ∀ {T} M → substn* σ {T} M ≡ substn* ρ M substn*-cong {k} {Γ} {Δ} = substn+-cong [] Γ Δ -- Identity of substitutions xsubstn+-id : ∀ {k} B Γ {T} (x : Case T B Γ) → expr (xsubstn+ B Γ Γ (id {k} Γ) x) ≡ var (case⁻¹ x) xsubstn+-id {var} B Γ (inj₁ x) = refl xsubstn+-id {exp var} B Γ (inj₁ x) = refl xsubstn+-id {var} B Γ (inj₂ x) = refl xsubstn+-id {exp var} B Γ (inj₂ x) = weaken*-var B x substn+-id : ∀ {k} B Γ {T} (M : Exp (B ++ Γ) T) → substn+ B Γ Γ (id {k} Γ) M ≡ M substn+-id B Γ (const c) = refl substn+-id B Γ (abs T M) = cong (abs {B ++ Γ} T) (substn+-id (T ∷ B) Γ M) substn+-id B Γ (app M N) = cong₂ app (substn+-id B Γ M) (substn+-id B Γ N) substn+-id {k} B Γ (var x) = begin substn+ B Γ Γ (id {k} Γ) (var x) ≡⟨ xsubstn+-id {k} B Γ (case B Γ x) ⟩ var (case⁻¹ (case B Γ x)) ≡⟨ cong var (case-iso B Γ x) ⟩ var x ∎ substn*-id : ∀ {k Γ T} (M : Exp Γ T) → substn* (id {k} Γ) M ≡ M substn*-id {k} {Γ} = substn+-id [] Γ weaken*-[] : ∀ {Γ T} (M : Exp Γ T) → weaken* [] M ≡ M weaken*-[] M = substn*-id M mutual -- Composition of substitutions substn+-∙ : ∀ {k l} B Γ Δ E (σ : Substn k Γ Δ) (ρ : Substn l Δ E) {T} (M : Exp (B ++ E) T) → (substn+ B Γ Δ σ (substn+ B Δ E ρ M) ≡ substn+ B Γ E (σ ∙ ρ) M) substn+-∙ B Γ Δ E ρ σ (const c) = refl substn+-∙ B Γ Δ E ρ σ (abs T M) = cong (abs {B ++ Γ} T) (substn+-∙ (T ∷ B) Γ Δ E ρ σ M) substn+-∙ B Γ Δ E ρ σ (app M N) = cong₂ app (substn+-∙ B Γ Δ E ρ σ M) (substn+-∙ B Γ Δ E ρ σ N) substn+-∙ B Γ Δ E ρ σ (var x) = xsubstn+-∙ B Γ Δ E ρ σ (case B E x) where xsubstn+-∙ : ∀ {k l} B Γ Δ E (σ : Substn k Γ Δ) (ρ : Substn l Δ E) {T} (x : Case T B E) → (substn+ B Γ Δ σ (expr (xsubstn+ B Δ E ρ x)) ≡ expr (xsubstn+ B Γ E (σ ∙ ρ) x)) xsubstn+-∙ {k} {var} B Γ Δ E σ ρ (inj₁ x) = cong (expr ∘ xsubstn+ B Γ Δ σ) (case-≪ x Δ) xsubstn+-∙ {var} {exp var} B Γ Δ E σ ρ (inj₁ x) = cong (expr ∘ xsubstn+ B Γ Δ σ) (case-≪ x Δ) xsubstn+-∙ {exp var} {exp var} B Γ Δ E σ ρ (inj₁ x) = cong (expr ∘ xsubstn+ B Γ Δ σ) (case-≪ x Δ) xsubstn+-∙ {var} {var} B Γ Δ E σ ρ (inj₂ x) = cong (expr ∘ xsubstn+ B Γ Δ σ) (case-≫ B (ρ x)) xsubstn+-∙ {exp var} {var} B Γ Δ E σ ρ (inj₂ x) = cong (expr ∘ xsubstn+ B Γ Δ σ) (case-≫ B (ρ x)) xsubstn+-∙ {var} {exp var} B Γ Δ E σ ρ (inj₂ x) = begin substn+ B Γ Δ σ (weaken* B (ρ x)) ≡⟨ substn+* B Γ Δ σ (weaken* B (ρ x)) ⟩ substn* (id B +++ σ) (weaken* B (ρ x)) ≡⟨ substn+-∙ [] (B ++ Γ) (B ++ Δ) Δ (id B +++ σ) (snd B Δ) (ρ x) ⟩ substn* ((id B +++ σ) ∙ snd B Δ) (ρ x) ≡⟨ substn*-cong (λ y → cong (par (id B) σ) (case-≫ B y)) (ρ x) ⟩ substn* (snd B Γ ∙ σ) (ρ x) ≡⟨ sym (substn+-∙ [] (B ++ Γ) Γ Δ (snd B Γ) σ (ρ x)) ⟩ weaken* B (substn* σ (ρ x)) ∎ xsubstn+-∙ {exp var} {exp var} B Γ Δ E σ ρ (inj₂ x) = begin substn+ B Γ Δ σ (weaken* B (ρ x)) ≡⟨ substn+* B Γ Δ σ (weaken* B (ρ x)) ⟩ substn* (id B +++ σ) (weaken* B (ρ x)) ≡⟨ substn+-∙ [] (B ++ Γ) (B ++ Δ) Δ (id B +++ σ) (snd B Δ) (ρ x) ⟩ substn* ((id B +++ σ) ∙ snd B Δ) (ρ x) ≡⟨ substn*-cong (λ y → cong (par (id B) σ) (case-≫ B y))(ρ x) ⟩ substn* (snd B Γ ∙ σ) (ρ x) ≡⟨ sym (substn+-∙ [] (B ++ Γ) Γ Δ (snd B Γ) σ (ρ x)) ⟩ weaken* B (substn* σ (ρ x)) ∎ substn*-∙ : ∀ {k l Γ Δ E} (σ : Substn k Γ Δ) (ρ : Substn l Δ E) {T} (M : Exp E T) → (substn* σ (substn* ρ M) ≡ substn* (σ ∙ ρ) M) substn*-∙ {k} {l} {Γ} {Δ} {E} = substn+-∙ [] Γ Δ E -- Proof uses the fact that substn+ is an instance of substn* substn++ : ∀ {k} A B Γ Δ (σ : Substn k Γ Δ) {T} (M : Exp (A ++ B ++ Δ) T) → substn+ (A ++ B) Γ Δ σ M ≡ substn+ A (B ++ Γ) (B ++ Δ) (id B +++ σ) M substn++ A B Γ Δ σ (const c) = refl substn++ A B Γ Δ σ (abs T M) = cong (abs {A ++ B ++ Γ} T) (substn++ (T ∷ A) B Γ Δ σ M) substn++ A B Γ Δ σ (app M N) = cong₂ app (substn++ A B Γ Δ σ M) (substn++ A B Γ Δ σ N) substn++ A B Γ Δ σ (var x) = cong expr (begin xsubstn+ (A ++ B) Γ Δ σ (case (A ++ B) Δ x) ≡⟨ cong (xsubstn+ (A ++ B) Γ Δ σ) (sym (caseˡ₃ A B Δ x)) ⟩ xsubstn+ (A ++ B) Γ Δ σ (caseˡ (case₃ A B Δ x)) ≡⟨ xsubstn++ A B Γ Δ σ (case₃ A B Δ x) ⟩ xsubstn+ A (B ++ Γ) (B ++ Δ) (id B +++ σ) (caseʳ (case₃ A B Δ x)) ≡⟨ cong (xsubstn+ A (B ++ Γ) (B ++ Δ) (id B +++ σ)) (caseʳ₃ A B Δ x) ⟩ xsubstn+ A (B ++ Γ) (B ++ Δ) (id B +++ σ) (case A (B ++ Δ) x) ∎) where xsubstn++ : ∀ {k} A B Γ Δ (σ : Substn k Γ Δ) {T} (x : Case₃ T A B Δ) → xsubstn+ (A ++ B) Γ Δ σ (caseˡ x) ≡ xsubstn+ A (B ++ Γ) (B ++ Δ) (id B +++ σ) (caseʳ x) xsubstn++ A B Γ Δ σ (inj₁ x) = refl xsubstn++ {var} A B Γ Δ σ (inj₂ x) = cong (λ X → A ≫ par (id B) σ X) (sym (case-≪ x Δ)) xsubstn++ {exp var} A B Γ Δ σ (inj₂ x) = begin var (A ≫ x ≪ Γ) ≡⟨ sym (weaken*-var A (x ≪ Γ)) ⟩ weaken* A (var (x ≪ Γ)) ≡⟨ cong (weaken* A) (sym (weaken*ʳ-var Γ x)) ⟩ weaken* A (weaken*ʳ Γ (var x)) ≡⟨ cong (weaken* A ∘ par (id B) σ) (sym (case-≪ x Δ)) ⟩ weaken* A ((id B +++ σ) (x ≪ Δ)) ∎ xsubstn++ {var} A B Γ Δ σ (inj₃ x) = cong (λ X → A ≫ par (id B) σ X) (sym (case-≫ B x)) xsubstn++ {exp var} A B Γ Δ σ (inj₃ x) = begin weaken* (A ++ B) (σ x) ≡⟨ sym (substn*-∙ (snd A (B ++ Γ)) (snd B Γ) (σ x)) ⟩ weaken* A (weaken* B (σ x)) ≡⟨ cong (weaken* A ∘ par (id B) σ) (sym (case-≫ B x)) ⟩ weaken* A ((id B +++ σ) (B ≫ x)) ∎ substn+* : ∀ {k} B Γ Δ (σ : Substn k Γ Δ) {T} (M : Exp (B ++ Δ) T) → substn+ B Γ Δ σ M ≡ substn* (id B +++ σ) M substn+* = substn++ [] -- Weakening of weakening is weakening weaken*-++ : ∀ A B Γ {T} (M : Exp Γ T) → weaken* A (weaken* B M) ≡ weaken* (A ++ B) M weaken*-++ A B Γ = substn*-∙ (snd A (B ++ Γ)) (snd B Γ) -- Weakening commutes with weakening weaken*-comm : ∀ A B Γ Δ {U} (M : Exp (B ++ Δ) U) → weaken* A (weaken+ B Γ Δ M) ≡ weaken+ (A ++ B) Γ Δ (weaken* A M) weaken*-comm A B Γ Δ M = begin weaken* A (weaken+ B Γ Δ M) ≡⟨ cong (substn* (snd A (B ++ Γ ++ Δ))) (substn+* B (Γ ++ Δ) Δ (snd Γ Δ) M) ⟩ substn* (snd A (B ++ Γ ++ Δ)) (substn* (id B +++ snd Γ Δ) M) ≡⟨ substn*-∙ (snd A (B ++ Γ ++ Δ)) (id B +++ snd Γ Δ) M ⟩ substn* (snd A (B ++ Γ ++ Δ) ∙ (id B +++ snd Γ Δ)) M ≡⟨ substn*-cong lemma₂ M ⟩ substn* ((id (A ++ B) +++ snd Γ Δ) ∙ snd A (B ++ Δ)) M ≡⟨ sym (substn*-∙ (id (A ++ B) +++ snd Γ Δ) (snd A (B ++ Δ)) M) ⟩ substn* (id (A ++ B) +++ snd Γ Δ) (substn* (snd A (B ++ Δ)) M) ≡⟨ sym (substn+* (A ++ B) (Γ ++ Δ) Δ (snd Γ Δ) (substn* (snd A (B ++ Δ)) M)) ⟩ weaken+ (A ++ B) Γ Δ (weaken* A M) ∎ where lemma₁ : ∀ {T} (x : Case T B Δ) → snd A (B ++ Γ ++ Δ) (par (id B) (snd Γ Δ) x) ≡ (par (id (A ++ B)) (snd Γ Δ) (A ⋙ x)) lemma₁ (inj₁ x) = refl lemma₁ (inj₂ x) = refl lemma₂ : (snd A (B ++ Γ ++ Δ) ∙ (id B +++ snd Γ Δ)) ≈ ((id (A ++ B) +++ snd Γ Δ) ∙ snd A (B ++ Δ)) lemma₂ {T} x = begin snd A (B ++ Γ ++ Δ) (par (id B) (snd Γ Δ) (case B Δ x)) ≡⟨ lemma₁ (case B Δ x) ⟩ par (id (A ++ B)) (snd Γ Δ) (A ⋙ (case B Δ x)) ≡⟨ cong (par (id (A ++ B)) (snd Γ Δ)) (case-⋙ A B Δ x) ⟩ par (id (A ++ B)) (snd Γ Δ) (case (A ++ B) Δ (A ≫ x)) ∎ weaken-comm : ∀ T B Γ Δ {U} (M : Exp (B ++ Δ) U) → weaken T (weaken+ B Γ Δ M) ≡ weaken+ (T ∷ B) Γ Δ (weaken T M) weaken-comm T = weaken*-comm [ T ] -- Weakening distributes through susbtn weaken-substn : ∀ B Γ Δ {T U} (M : Exp (B ++ Δ) T) (N : Exp (T ∷ B ++ Δ) U) → substn (weaken+ B Γ Δ M) (weaken+ (T ∷ B) Γ Δ N) ≡ weaken+ B Γ Δ (substn M N) weaken-substn B Γ Δ {T} M N = begin substn (weaken+ B Γ Δ M) (weaken+ (T ∷ B) Γ Δ N) ≡⟨ cong₂ substn (substn+* B (Γ ++ Δ) Δ (snd Γ Δ) M) (substn+* (T ∷ B) (Γ ++ Δ) Δ (snd Γ Δ) N) ⟩ substn (substn* (id B +++ snd Γ Δ) M) (substn* (id (T ∷ B) +++ snd Γ Δ) N) ≡⟨ substn*-∙ (substn* (id B +++ snd Γ Δ) M ◁ id (B ++ Γ ++ Δ)) (id (T ∷ B) +++ snd Γ Δ) N ⟩ substn* ((substn* (id B +++ snd Γ Δ) M ◁ id (B ++ Γ ++ Δ)) ∙ (id (T ∷ B) +++ snd Γ Δ)) N ≡⟨ substn*-cong lemma₂ N ⟩ substn* ((id B +++ snd Γ Δ) ∙ (M ◁ id (B ++ Δ))) N ≡⟨ sym (substn*-∙ (id B +++ snd Γ Δ) (M ◁ id (B ++ Δ)) N) ⟩ substn* (id B +++ snd Γ Δ) (substn M N) ≡⟨ sym (substn+* B (Γ ++ Δ) Δ (snd Γ Δ) (substn M N)) ⟩ weaken+ B Γ Δ (substn M N) ∎ where lemma₁ : ∀ {S} (x : Case₃ S [ T ] B Δ) → (substn* (id B +++ snd Γ Δ) M ◁ id (B ++ Γ ++ Δ)) (par (id (T ∷ B)) (snd Γ Δ) (caseˡ x)) ≡ substn* (id B +++ snd Γ Δ) (choose ⟨ M ⟩ (id (B ++ Δ)) (caseʳ x)) lemma₁ (inj₁ x) = begin (substn* (id B +++ snd Γ Δ) M ◁ id (B ++ Γ ++ Δ)) (x ≪ B ≪ Γ ≪ Δ) ≡⟨ cong (choose ⟨ substn* (id B +++ snd Γ Δ) M ⟩ (id (B ++ Γ ++ Δ))) (case-≪ x (B ++ Γ ++ Δ)) ⟩ ⟨ substn* (id B +++ snd Γ Δ) M ⟩ x ≡⟨ subst-natural (uniq x) (substn* (id B +++ snd Γ Δ)) M ⟩ substn* (id B +++ snd Γ Δ) (⟨ M ⟩ x) ∎ lemma₁ (inj₂ x) = begin (substn* (id B +++ snd Γ Δ) M ◁ id (B ++ Γ ++ Δ)) ([ T ] ≫ x ≪ Γ ≪ Δ) ≡⟨ cong (choose ⟨ substn* (id B +++ snd Γ Δ) M ⟩ (id (B ++ Γ ++ Δ))) (case-≫ [ T ] (x ≪ Γ ≪ Δ)) ⟩ var (x ≪ Γ ≪ Δ) ≡⟨ cong (var ∘ par (id B) (snd Γ Δ)) (sym (case-≪ x Δ)) ⟩ var ((id B +++ snd Γ Δ) (x ≪ Δ)) ≡⟨ cong (var ∘ xsubstn+ [] (B ++ Γ ++ Δ) (B ++ Δ) (id B +++ snd Γ Δ)) (sym (case-≫ [] (x ≪ Δ))) ⟩ substn* (id B +++ snd Γ Δ) (var (x ≪ Δ)) ∎ lemma₁ (inj₃ x) = begin (substn* (id B +++ snd Γ Δ) M ◁ id (B ++ Γ ++ Δ)) ([ T ] ≫ B ≫ Γ ≫ x) ≡⟨ cong (choose ⟨ substn* (id B +++ snd Γ Δ) M ⟩ (id (B ++ Γ ++ Δ))) (case-≫ [ T ] (B ≫ Γ ≫ x)) ⟩ var (B ≫ Γ ≫ x) ≡⟨ cong (var ∘ par (id B) (snd Γ Δ)) (sym (case-≫ B x)) ⟩ var ((id B +++ snd Γ Δ) (B ≫ x)) ≡⟨ cong (var ∘ xsubstn+ [] (B ++ Γ ++ Δ) (B ++ Δ) (id B +++ snd Γ Δ)) (sym (case-≫ [] (B ≫ x))) ⟩ substn* (id B +++ snd Γ Δ) (var (B ≫ x)) ∎ lemma₂ : ((substn* (id B +++ snd Γ Δ) M ◁ id (B ++ Γ ++ Δ)) ∙ (id (T ∷ B) +++ snd Γ Δ)) ≈ ((id B +++ snd Γ Δ) ∙ (M ◁ id (B ++ Δ))) lemma₂ {S} x = begin ((substn* (id B +++ snd Γ Δ) M ◁ id (B ++ Γ ++ Δ)) ∙ (id (T ∷ B) +++ snd Γ Δ)) x ≡⟨ cong (substn* (id B +++ snd Γ Δ) M ◁ id (B ++ Γ ++ Δ) ∘ par (id (T ∷ B)) (snd Γ Δ)) (sym (caseˡ₃ [ T ] B Δ x)) ⟩ (substn* (id B +++ snd Γ Δ) M ◁ id (B ++ Γ ++ Δ)) (par (id (T ∷ B)) (snd Γ Δ) (caseˡ (case₃ [ T ] B Δ x))) ≡⟨ lemma₁ (case₃ [ T ] B Δ x) ⟩ substn* (id B +++ snd Γ Δ) (choose ⟨ M ⟩ (id (B ++ Δ)) (caseʳ (case₃ [ T ] B Δ x))) ≡⟨ cong (substn* (id B +++ snd Γ Δ) ∘ choose ⟨ M ⟩ (id (B ++ Δ))) (caseʳ₃ [ T ] B Δ x) ⟩ ((id B +++ snd Γ Δ) ∙ (M ◁ id (B ++ Δ))) x ∎ -- Substitution into weakening discards the substitution substn-weaken : ∀ {Γ T U} (M : Exp Γ U) (N : Exp Γ T) → substn N (weaken T M) ≡ M substn-weaken {Γ} {T} M N = begin substn N (weaken T M) ≡⟨ substn*-∙ (N ◁ id Γ) (snd [ T ] Γ) M ⟩ substn* ((N ◁ id Γ) ∙ snd [ T ] Γ) M ≡⟨ substn*-cong (λ x → cong (choose ⟨ N ⟩ (id Γ)) (case-≫ [ T ] x)) M ⟩ substn* (id Γ) M ≡⟨ substn*-id M ⟩ M ∎ -- Substitution + weakening respects ◁ substn*-◁ : ∀ Γ Δ E {T U} (M : Exp (T ∷ Γ) U) (N : Exp (E ++ Δ) T) (σ : Substn (exp var) Δ Γ) → substn* (N ◁ weakens* E σ) M ≡ substn N (weaken+ [ T ] E Δ (substn+ [ T ] Δ Γ σ M)) substn*-◁ Γ Δ E {T} M N σ = begin substn* (N ◁ weakens* E σ) M ≡⟨ substn*-cong (λ x → lemma (case [ T ] Γ x)) M ⟩ substn* ((N ◁ id (E ++ Δ)) ∙ (id [ T ] +++ (snd E Δ ∙ σ))) M ≡⟨ sym (substn*-∙ (N ◁ id (E ++ Δ)) (id [ T ] +++ (snd E Δ ∙ σ)) M) ⟩ substn N (substn* (id [ T ] +++ (snd E Δ ∙ σ)) M) ≡⟨ cong (substn N) (sym (substn+* [ T ] (E ++ Δ) Γ (snd E Δ ∙ σ) M)) ⟩ substn N (substn+ [ T ] (E ++ Δ) Γ (snd E Δ ∙ σ) M) ≡⟨ cong (substn N) (sym (substn+-∙ [ T ] (E ++ Δ) Δ Γ (snd E Δ) σ M)) ⟩ substn N (weaken+ [ T ] E Δ (substn+ [ T ] Δ Γ σ M)) ∎ where lemma : ∀ {U} (x : Case U [ T ] Γ) → choose ⟨ N ⟩ (weakens* E σ) x ≡ substn N (par (id [ T ]) (snd E Δ ∙ σ) x) lemma (inj₁ x) = begin subst (Exp (E ++ Δ)) (uniq x) N ≡⟨ cong (choose ⟨ N ⟩ (id (E ++ Δ))) (sym (case-≪ x (E ++ Δ))) ⟩ (N ◁ id (E ++ Δ)) (x ≪ E ≪ Δ) ≡⟨ sym (weaken*-[] ((N ◁ id (E ++ Δ)) (x ≪ E ≪ Δ))) ⟩ weaken* [] ((N ◁ id (E ++ Δ)) (x ≪ E ≪ Δ)) ≡⟨ cong (xsubstn+ [] (E ++ Δ) ([ T ] ++ E ++ Δ) (N ◁ id (E ++ Δ))) (sym (case-≫ [] (x ≪ E ≪ Δ))) ⟩ substn N (var (x ≪ E ≪ Δ)) ≡⟨ cong (substn N) (sym (weaken*ʳ-var (E ++ Δ) x)) ⟩ substn N (weaken*ʳ (E ++ Δ) (var x)) ∎ lemma (inj₂ x) = sym (substn-weaken (weaken* E (σ x)) N)
State Before: α : Type u_1 β : Type ?u.10223 γ : Type ?u.10226 δ : Type ?u.10229 ι : Type ?u.10232 inst✝ : MeasurableSpace α μ μ₁ μ₂ : Measure α s s₁ s₂ t : Set α ⊢ μ₁ = μ₂ → ∀ (s : Set α), MeasurableSet s → ↑↑μ₁ s = ↑↑μ₂ s State After: α : Type u_1 β : Type ?u.10223 γ : Type ?u.10226 δ : Type ?u.10229 ι : Type ?u.10232 inst✝ : MeasurableSpace α μ μ₁ : Measure α s✝ s₁ s₂ t s : Set α _hs : MeasurableSet s ⊢ ↑↑μ₁ s = ↑↑μ₁ s Tactic: rintro rfl s _hs State Before: α : Type u_1 β : Type ?u.10223 γ : Type ?u.10226 δ : Type ?u.10229 ι : Type ?u.10232 inst✝ : MeasurableSpace α μ μ₁ : Measure α s✝ s₁ s₂ t s : Set α _hs : MeasurableSet s ⊢ ↑↑μ₁ s = ↑↑μ₁ s State After: no goals Tactic: rfl
module Core.Metadata import Core.Binary import Core.Context import Core.Context.Log import Core.Core import Core.Directory import Core.Env import Core.FC import Core.Normalise import Core.Options import Core.TT import Core.TTC import Data.List import System.File import Libraries.Data.PosMap import Libraries.Utils.Binary %default covering public export data Decoration : Type where Typ : Decoration Function : Decoration Data : Decoration Keyword : Decoration Bound : Decoration Namespace : Decoration Postulate : Decoration Module : Decoration export nameDecoration : Name -> NameType -> Decoration nameDecoration nm nt = ifThenElse (isUnsafeBuiltin nm) Postulate (nameTypeDecoration nt) where nameTypeDecoration : NameType -> Decoration nameTypeDecoration Bound = Bound nameTypeDecoration Func = Function nameTypeDecoration (DataCon _ _) = Data nameTypeDecoration (TyCon _ _ ) = Typ public export ASemanticDecoration : Type ASemanticDecoration = (NonEmptyFC, Decoration, Maybe Name) public export SemanticDecorations : Type SemanticDecorations = List ASemanticDecoration public export Eq Decoration where Typ == Typ = True Function == Function = True Data == Data = True Keyword == Keyword = True Bound == Bound = True Namespace == Namespace = True Postulate == Postulate = True Module == Module = True _ == _ = False -- CAREFUL: this instance is used in SExpable Decoration. If you change -- it then you need to fix the SExpable implementation in order not to -- break the IDE mode. public export Show Decoration where show Typ = "type" show Function = "function" show Data = "data" show Keyword = "keyword" show Bound = "bound" show Namespace = "namespace" show Postulate = "postulate" show Module = "module" TTC Decoration where toBuf b Typ = tag 0 toBuf b Function = tag 1 toBuf b Data = tag 2 toBuf b Keyword = tag 3 toBuf b Bound = tag 4 toBuf b Namespace = tag 5 toBuf b Postulate = tag 6 toBuf b Module = tag 7 fromBuf b = case !getTag of 0 => pure Typ 1 => pure Function 2 => pure Data 3 => pure Keyword 4 => pure Bound 5 => pure Namespace 6 => pure Postulate 7 => pure Module _ => corrupt "Decoration" public export record Metadata where constructor MkMetadata -- Mapping from source annotation (location, typically) to -- the LHS defined at that location. Also record the outer environment -- length, since we don't want to case split on these. lhsApps : List (NonEmptyFC, (Nat, ClosedTerm)) -- Mapping from annotation to the name defined with that annotation, -- and its type (so, giving the ability to get the types of locally -- defined names) -- The type is abstracted over the whole environment; the Nat gives -- the number of names which were in the environment at the time. names : List (NonEmptyFC, (Name, Nat, ClosedTerm)) -- Mapping from annotation to the name that's declared there and -- its type; the Nat is as above tydecls : List (NonEmptyFC, (Name, Nat, ClosedTerm)) -- Current lhs, if applicable, and a mapping from hole names to the -- lhs they're under. This is for expression search, to ensure that -- recursive calls have a smaller value as an argument. -- Also use this to get the name of the function being defined (i.e. -- to know what the recursive call is, if applicable) currentLHS : Maybe ClosedTerm holeLHS : List (Name, ClosedTerm) nameLocMap : PosMap (NonEmptyFC, Name) sourceIdent : OriginDesc -- Semantic Highlighting -- Posmap of known semantic decorations semanticHighlighting : PosMap ASemanticDecoration -- Posmap of aliases (in `with` clauses the LHS disapear during -- elaboration after making sure that they match their parents' semanticAliases : PosMap (NonEmptyFC, NonEmptyFC) semanticDefaults : PosMap ASemanticDecoration Show Metadata where show (MkMetadata apps names tydecls currentLHS holeLHS nameLocMap fname semanticHighlighting semanticAliases semanticDefaults) = "Metadata:\n" ++ " lhsApps: " ++ show apps ++ "\n" ++ " names: " ++ show names ++ "\n" ++ " type declarations: " ++ show tydecls ++ "\n" ++ " current LHS: " ++ show currentLHS ++ "\n" ++ " holes: " ++ show holeLHS ++ "\n" ++ " nameLocMap: " ++ show nameLocMap ++ "\n" ++ " sourceIdent: " ++ show fname ++ " semanticHighlighting: " ++ show semanticHighlighting ++ " semanticAliases: " ++ show semanticAliases ++ " semanticDefaults: " ++ show semanticDefaults export initMetadata : OriginDesc -> Metadata initMetadata finfo = MkMetadata { lhsApps = [] , names = [] , tydecls = [] , currentLHS = Nothing , holeLHS = [] , nameLocMap = empty , sourceIdent = finfo , semanticHighlighting = empty , semanticAliases = empty , semanticDefaults = empty } -- A label for metadata in the global state export data MD : Type where TTC Metadata where toBuf b m = do toBuf b (lhsApps m) toBuf b (names m) toBuf b (tydecls m) toBuf b (holeLHS m) toBuf b (nameLocMap m) toBuf b (sourceIdent m) toBuf b (semanticHighlighting m) toBuf b (semanticAliases m) toBuf b (semanticDefaults m) fromBuf b = do apps <- fromBuf b ns <- fromBuf b tys <- fromBuf b hlhs <- fromBuf b dlocs <- fromBuf b fname <- fromBuf b semhl <- fromBuf b semal <- fromBuf b semdef <- fromBuf b pure (MkMetadata apps ns tys Nothing hlhs dlocs fname semhl semal semdef) export addLHS : {vars : _} -> {auto c : Ref Ctxt Defs} -> {auto m : Ref MD Metadata} -> FC -> Nat -> Env Term vars -> Term vars -> Core () addLHS loc outerenvlen env tm = do meta <- get MD tm' <- toFullNames (bindEnv loc (toPat env) tm) -- Put the lhs on the metadata if it's not empty whenJust (isNonEmptyFC loc) $ \ neloc => put MD $ record { lhsApps $= ((neloc, outerenvlen, tm') ::) } meta where toPat : Env Term vs -> Env Term vs toPat (Lam fc c p ty :: bs) = PVar fc c p ty :: toPat bs toPat (b :: bs) = b :: toPat bs toPat [] = [] -- For giving local variable names types, just substitute the name -- rather than storing the whole environment, otherwise we'll repeatedly -- store the environment and it'll get big. -- We'll need to rethink a bit if we want interactive editing to show -- the whole environment - perhaps store each environment just once -- along with its source span? -- In any case, one could always look at the other names to get their -- types directly! substEnv : {vars : _} -> FC -> Env Term vars -> (tm : Term vars) -> ClosedTerm substEnv loc [] tm = tm substEnv {vars = x :: _} loc (b :: env) tm = substEnv loc env (subst (Ref loc Bound x) tm) export addNameType : {vars : _} -> {auto c : Ref Ctxt Defs} -> {auto m : Ref MD Metadata} -> FC -> Name -> Env Term vars -> Term vars -> Core () addNameType loc n env tm = do meta <- get MD n' <- getFullName n -- Add the name to the metadata if the file context is not empty whenJust (isNonEmptyFC loc) $ \ neloc => do put MD $ record { names $= ((neloc, (n', 0, substEnv loc env tm)) ::) } meta log "metadata.names" 7 $ show n' ++ " at line " ++ show (1 + startLine neloc) export addTyDecl : {vars : _} -> {auto c : Ref Ctxt Defs} -> {auto m : Ref MD Metadata} -> FC -> Name -> Env Term vars -> Term vars -> Core () addTyDecl loc n env tm = do meta <- get MD n' <- getFullName n -- Add the type declaration to the metadata if the file context is not empty whenJust (isNonEmptyFC loc) $ \ neloc => put MD $ record { tydecls $= ( (neloc, (n', length env, bindEnv loc env tm)) ::) } meta export addNameLoc : {auto m : Ref MD Metadata} -> {auto c : Ref Ctxt Defs} -> FC -> Name -> Core () addNameLoc loc n = do meta <- get MD n' <- getFullName n whenJust (isNonEmptyFC loc) $ \neloc => put MD $ record { nameLocMap $= insert (neloc, n') } meta export setHoleLHS : {auto m : Ref MD Metadata} -> ClosedTerm -> Core () setHoleLHS tm = do meta <- get MD put MD (record { currentLHS = Just tm } meta) export clearHoleLHS : {auto m : Ref MD Metadata} -> Core () clearHoleLHS = do meta <- get MD put MD (record { currentLHS = Nothing } meta) export withCurrentLHS : {auto c : Ref Ctxt Defs} -> {auto m : Ref MD Metadata} -> Name -> Core () withCurrentLHS n = do meta <- get MD n' <- getFullName n maybe (pure ()) (\lhs => put MD (record { holeLHS $= ((n', lhs) ::) } meta)) (currentLHS meta) findEntryWith : (NonEmptyFC -> a -> Bool) -> List (NonEmptyFC, a) -> Maybe (NonEmptyFC, a) findEntryWith = find . uncurry export findLHSAt : {auto m : Ref MD Metadata} -> (NonEmptyFC -> ClosedTerm -> Bool) -> Core (Maybe (NonEmptyFC, Nat, ClosedTerm)) findLHSAt p = do meta <- get MD pure (findEntryWith (\ loc, tm => p loc (snd tm)) (lhsApps meta)) export findTypeAt : {auto m : Ref MD Metadata} -> (NonEmptyFC -> (Name, Nat, ClosedTerm) -> Bool) -> Core (Maybe (Name, Nat, ClosedTerm)) findTypeAt p = do meta <- get MD pure (map snd (findEntryWith p (names meta))) export findTyDeclAt : {auto m : Ref MD Metadata} -> (NonEmptyFC -> (Name, Nat, ClosedTerm) -> Bool) -> Core (Maybe (NonEmptyFC, Name, Nat, ClosedTerm)) findTyDeclAt p = do meta <- get MD pure (findEntryWith p (tydecls meta)) export findHoleLHS : {auto m : Ref MD Metadata} -> Name -> Core (Maybe ClosedTerm) findHoleLHS hn = do meta <- get MD pure (lookupBy (\x, y => dropNS x == dropNS y) hn (holeLHS meta)) export addSemanticDefault : {auto m : Ref MD Metadata} -> ASemanticDecoration -> Core () addSemanticDefault asem = do meta <- get MD put MD $ { semanticDefaults $= insert asem } meta export addSemanticAlias : {auto m : Ref MD Metadata} -> NonEmptyFC -> NonEmptyFC -> Core () addSemanticAlias from to = do meta <- get MD put MD $ { semanticAliases $= insert (from, to) } meta export addSemanticDecorations : {auto m : Ref MD Metadata} -> {auto c : Ref Ctxt Defs} -> SemanticDecorations -> Core () addSemanticDecorations decors = do meta <- get MD defs <- get Ctxt let posmap = meta.semanticHighlighting let (newDecors,droppedDecors) = span ( (meta.sourceIdent ==) . Builtin.fst . Builtin.fst ) decors unless (isNil droppedDecors) $ log "ide-mode.highlight" 19 $ "ignored adding decorations to " ++ show meta.sourceIdent ++ ": " ++ show droppedDecors put MD $ record {semanticHighlighting = (fromList newDecors) `union` posmap} meta -- Normalise all the types of the names, since they might have had holes -- when added and the holes won't necessarily get saved normaliseTypes : {auto m : Ref MD Metadata} -> {auto c : Ref Ctxt Defs} -> Core () normaliseTypes = do meta <- get MD defs <- get Ctxt ns' <- traverse (nfType defs) (names meta) put MD (record { names = ns' } meta) where nfType : Defs -> (NonEmptyFC, (Name, Nat, ClosedTerm)) -> Core (NonEmptyFC, (Name, Nat, ClosedTerm)) nfType defs (loc, (n, len, ty)) = pure (loc, (n, len, !(normaliseArgHoles defs [] ty))) record TTMFile where constructor MkTTMFile version : Int metadata : Metadata TTC TTMFile where toBuf b file = do toBuf b "TTM" toBuf b (version file) toBuf b (metadata file) fromBuf b = do hdr <- fromBuf b when (hdr /= "TTM") $ corrupt "TTM header" ver <- fromBuf b checkTTCVersion "" ver ttcVersion -- maybe change the interface to get the filename md <- fromBuf b pure (MkTTMFile ver md) HasNames Metadata where full gam md = pure $ record { lhsApps = !(traverse fullLHS $ md.lhsApps) , names = !(traverse fullTy $ md.names) , tydecls = !(traverse fullTy $ md.tydecls) , currentLHS = Nothing , holeLHS = !(traverse fullHLHS $ md.holeLHS) , nameLocMap = fromList !(traverse fullDecls (toList $ md.nameLocMap)) } md where fullLHS : (NonEmptyFC, (Nat, ClosedTerm)) -> Core (NonEmptyFC, (Nat, ClosedTerm)) fullLHS (fc, (i, tm)) = pure (fc, (i, !(full gam tm))) fullTy : (NonEmptyFC, (Name, Nat, ClosedTerm)) -> Core (NonEmptyFC, (Name, Nat, ClosedTerm)) fullTy (fc, (n, i, tm)) = pure (fc, (!(full gam n), i, !(full gam tm))) fullHLHS : (Name, ClosedTerm) -> Core (Name, ClosedTerm) fullHLHS (n, tm) = pure (!(full gam n), !(full gam tm)) fullDecls : (NonEmptyFC, Name) -> Core (NonEmptyFC, Name) fullDecls (fc, n) = pure (fc, !(full gam n)) resolved gam (MkMetadata lhs ns tys clhs hlhs dlocs fname semhl semal semdef) = pure $ MkMetadata !(traverse resolvedLHS lhs) !(traverse resolvedTy ns) !(traverse resolvedTy tys) Nothing !(traverse resolvedHLHS hlhs) (fromList !(traverse resolvedDecls (toList dlocs))) fname semhl semal semdef where resolvedLHS : (NonEmptyFC, (Nat, ClosedTerm)) -> Core (NonEmptyFC, (Nat, ClosedTerm)) resolvedLHS (fc, (i, tm)) = pure (fc, (i, !(resolved gam tm))) resolvedTy : (NonEmptyFC, (Name, Nat, ClosedTerm)) -> Core (NonEmptyFC, (Name, Nat, ClosedTerm)) resolvedTy (fc, (n, i, tm)) = pure (fc, (!(resolved gam n), i, !(resolved gam tm))) resolvedHLHS : (Name, ClosedTerm) -> Core (Name, ClosedTerm) resolvedHLHS (n, tm) = pure (!(resolved gam n), !(resolved gam tm)) resolvedDecls : (NonEmptyFC, Name) -> Core (NonEmptyFC, Name) resolvedDecls (fc, n) = pure (fc, !(resolved gam n)) export writeToTTM : {auto c : Ref Ctxt Defs} -> {auto m : Ref MD Metadata} -> (fname : String) -> Core () writeToTTM fname = do normaliseTypes buf <- initBinary meta <- get MD defs <- get Ctxt toBuf buf (MkTTMFile ttcVersion !(full (gamma defs) meta)) Right ok <- coreLift $ writeToFile fname !(get Bin) | Left err => throw (InternalError (fname ++ ": " ++ show err)) pure () export readFromTTM : {auto m : Ref MD Metadata} -> (fname : String) -> Core () readFromTTM fname = do Right buf <- coreLift $ readFromFile fname | Left err => throw (InternalError (fname ++ ": " ++ show err)) bin <- newRef Bin buf ttm <- fromBuf bin put MD (metadata ttm) ||| Read Metadata from given file export readMetadata : (fname : String) -> Core Metadata readMetadata fname = do Right buf <- coreLift $ readFromFile fname | Left err => throw (InternalError (fname ++ ": " ++ show err)) bin <- newRef Bin buf MkTTMFile _ md <- fromBuf bin pure md ||| Dump content of a .ttm file in human-readable format export dumpTTM : (filename : String) -> Core () dumpTTM fname = do md <- readMetadata fname coreLift $ putStrLn $ show md
For any two vectors $a$ and $b$ and any scalar $u$, $b + ua = a + ub$ if and only if $a = b$ or $u = 1$.
variable {p : Prop} variable {q : Prop} section hrm -- theorems involving only `→` can be proved w lambda -- `theorem` command intrduces new theorem - basically a version of `def` command (kernel sees it the same) theorem t1 : p → q → p := fun hp : p => fun hq : q => hp #print t1 -- this is like definition of constant function, but using args of `Prop` rather than `Type` -- intuitively, it assumes `p` and `q` are true, & uses first hypothesis (trivially) to establish conclusion `p` is true -- `theorem` - basically a version of `def` command (kernel sees it the same) -- but there's a few pragmatic diffs: -- in normal circumstances - not necessary to unfold def of a theorem -- lean tags proofs as irreducible - hint to not unfold -- lean also able to process & check proofs in parallel (since assissing correctness of proof does not require knowing details of another) /- I THINK THIS IS THE IMPORTANT PART -/ -- lambda abstractions `hp : p` and `hq : q` can be viewed as temporary assumptions in proof of `t2` -- lean allows us to specify type of final term `hp` with `show` statement -- adding this extra info can improve clarity of a proof and help detect errors. -- `show` does nothing more than annotate the type -- internally, all presentations of `t2` produce same term theorem t2 : p → q → p := fun hp : p => fun hq : q => show p from hp #print t2 -- can move lambda abs variables to left of the colon: theorem t3 (hp : p) (hq : q) : p := hp #print t3 -- p → q → p -- then apply theorem t4 as func application axiom hp : p theorem t4 : q → p := t1 hp -- here `axiom` declaration postulates existence of element of given type (& may compromise logical consistency) -- ie can use to postulate empty type `False` has an element axiom unsound : False -- Everything follows from false theorem ex : 1 = 0 := False.elim unsound -- thus declaring an axiom `hp : p` is tantamount to declaring that `p` is true as witnessed by `hp` -- applying theorem `t4 : p → q → p` to fact that `hp : p` that `p` is ture yields `t1 hp : q → p` -- type of t1,2,3,4 is now `∀ {p q : Prop}, p → q → p` -- can read this as, "for every pair of props `p q`, we hv `p → q → p`" -- ie can move all parameters to right of colon theorem t5 : ∀ {p q : Prop}, p → q → p := fun {p q : Prop} (hp : p) (hq : q) => hp -- (if p and q has been delcared as variables, lean can generalize) variable {p q : Prop} theorem t6 : p → q → p := fun (hp : p) (hq : q) => hp -- THEN by props-as-types correspondence, we can declare the assumption `hp` that `p` holds, as another variable -- lean detects it uses `hp` and automatically adds `hp : p` as premise variable {p q : Prop} variable (hp : p) theorem t7 : q → p := fun (hq : q) => hp #print t7 end hrm /- generalizing t -/ -- applies to all variables section bruv theorem t0 (p q : Prop) (hp : p) (hq : q) : p := hp variable (p q r s : Prop) #check t0 p q -- p → q → p #check t0 r s -- r → s → r #check t0 (r → s) (s → r) -- (r → s) → (s → r) → r → s variable (h : r → s) -- variable `h` of type `r → s` can be views as hypothesis or premise that `r → s` holds #check t0 (r → s) (s → r) h -- (s → r) → r → s /- this is composition func from chapter 2 but using props instead of types-/ variable (p q r s : Prop) theorem t01 (h₁ : q → r) (h₂ : p → q) : p → r := fun h₃ : p => show r from h₁ (h₂ h₃) -- t01 says fun of h₁ and h₂ defined above composes idk end bruv
library(tidyr) library(dplyr) library(plyr) library(reshape) library(ggplot2) setwd(".") ############################ # Read the dataCollapsed ############################ dataCollapsed = read.csv("./dataCollapsed.csv", stringsAsFactors = TRUE) # dataCollapsed = na.omit(dataCollapsed) data = read.csv("./data.csv", stringsAsFactors = TRUE) ############################ # Reshape the dataCollapsed ############################ ##### RQ1 venues <- data %>% gather("venue", "value", c("conference", "journal", "workshop", "bookChapter"), na.rm = TRUE, convert = TRUE) %>% dplyr::filter(grepl("x",value)) %>% dplyr::rename(ID = X) %>% select(ID, venue) venues$venue <- as.factor(venues$venue) researchTypes <- data %>% gather("researchType", "value", c("validation", "evaluation", "solutionProposal", "experience"), na.rm = FALSE, convert = TRUE) %>% dplyr::filter(grepl("x",value)) %>% dplyr::rename(ID = X) %>% select(ID, researchType) researchTypes$researchType <- as.factor(researchTypes$researchType) contributionTypes <- data %>% gather("contributionType", "value", c("model", "method", "metric", "tool", "openItems"), na.rm = FALSE, convert = TRUE) %>% dplyr::filter(grepl("x",value)) %>% dplyr::rename(ID = X) %>% select(ID, contributionType) contributionTypes$contributionType <- as.factor(contributionTypes$contributionType) ##### RQ2 robotTypesApproach <- dataCollapsed %>% gather("robotTypeApproach", "value", c("terrestrialApproach", "aerialApproach", "spatialApproach", "genericApproach"), na.rm = FALSE, convert = TRUE) %>% dplyr::filter(grepl("x",value)) %>% select(ID, robotTypeApproach) robotTypesApproach$robotTypeApproach <- as.factor(robotTypesApproach$robotTypeApproach) multiRobotBoolApproach <- ifelse(dataCollapsed$multiRobotApproach=="x",TRUE,FALSE) multiRobotApproach <- cbind(dataCollapsed, multiRobotBoolApproach) %>% select(ID, multiRobotBoolApproach) colnames(multiRobotApproach)[colnames(multiRobotApproach)=="multiRobotBoolApproach"] <- "multiRobotApproach" years <- dataCollapsed %>% select(ID, year) ##### RQ3 languages <- dataCollapsed %>% gather("language", "value", c("dsl", "uml"), na.rm = FALSE, convert = TRUE) %>% dplyr::filter(grepl("x",value)) %>% select(ID, language) languages$language <- as.factor(languages$language) automationTypes <- dataCollapsed %>% gather("automation", "value", c("transformation", "codeGeneration", "modelsRuntime", "analysis"), na.rm = FALSE, convert = TRUE) %>% dplyr::filter(grepl("x",value)) %>% select(ID, automation) automationTypes$automation <- as.factor(automationTypes$automation) aspects <- dataCollapsed %>% gather("aspect", "value", c("behaviour", "navigation", "structure"), na.rm = FALSE, convert = TRUE) %>% dplyr::filter(grepl("x",value)) %>% select(ID, aspect) aspects$aspect <- as.factor(aspects$aspect) ##### RQ4.1 validationTypes <- dataCollapsed %>% gather("validationType", "value", c("experiment", "caseStudy", "example", "realProject", "simulation"), na.rm = FALSE, convert = TRUE) %>% dplyr::filter(grepl("x",value)) %>% select(ID, validationType) validationTypes$validationType <- as.factor(validationTypes$validationType) ##### RQ4.2 robotTypesEval <- dataCollapsed %>% gather("robotTypeEval", "value", c("terrestrialEval", "aerialEval", "aquaticEval", "spatialEval", "genericEval"), na.rm = FALSE, convert = TRUE) %>% dplyr::filter(grepl("x",value)) %>% select(ID, robotTypeEval) robotTypesEval$robotTypeEval <- as.factor(robotTypesEval$robotTypeEval) multiRobotBoolEval <- ifelse(dataCollapsed$multiRobotEval=="x",TRUE,FALSE) multiRobotEval <- cbind(dataCollapsed, multiRobotBoolEval) %>% select(ID, multiRobotBoolEval) colnames(multiRobotEval)[colnames(multiRobotEval)=="multiRobotBoolEval"] <- "multiRobotEval" ############################ # It's plotting time! ############################ plot <- function(var, fileName, labels, width, height, leftMargin) { filePath <- paste("./output/", fileName, ".pdf", sep="") pdf(filePath, width=width, height=height) par(mar=c(3, leftMargin, 1, 1)) par(mfrow=c(1, 1)) par(las=1) var <- as.factor(var) levels(var) <- labels dataToPlot <- table(var) dataToPlot <- dataToPlot[order(dataToPlot, decreasing=FALSE)] plot <- barplot(dataToPlot, main="", cex.main=1, xlim=c(0, nrow(data) + 5), cex=1.5, cex.names=1.5, las=1, horiz=TRUE) text(x=as.numeric(dataToPlot) + 3, y = plot, label = dataToPlot, cex = 1.5, col = "black") dev.off() } # RQ1 plot(venues$venue, "RQ1_venues", c("Book chapter", "Conference", "Journal", "Workshop"), 10, 5, 13) plot(researchTypes$researchType, "RQ1_researchTypes", c( "Evaluation research", "Experience paper", "Solution proposal", "Validation research"), 10, 5, 13) plot(contributionTypes$contributionType, "RQ1_contributionTypes", c("Method", "Metric", "Model", "Open items", "Tool"), 10, 5, 13) # RQ2 plot(robotTypesApproach$robotTypeApproach, "RQ2_robotTypesApproach", c("Aerial robots", "Generic robots", "Space robots", "Terrestrial robots", "Aquatic robots"), 10, 5, 13) plot(multiRobotApproach$multiRobotApproach, "RQ2_multiRobotApproach", c("Single robot", "Multiple robots"), 10, 5, 13) # RQ3 umlDialects <- dataCollapsed$umlDialect[which(dataCollapsed$umlDialect != "")] umlDialects <- droplevels(umlDialects) plot(languages$language, "RQ3_1_languages", c("DSL", "UML"), 10, 5, 13) plot(umlDialects, "RQ3_1_umlDialects", levels(umlDialects), 10, 5, 13) plot(automationTypes$automation, "RQ3_1_automationTypes", c("Analysis", "Code generation", "Models at runtime", "Transformation"), 10, 5, 13) plot(aspects$aspect, "RQ3_2_aspects", c("Behaviour", "Navigation", "Structure"), 10, 5, 13) # RQ4.1 plot(validationTypes$validationType, "RQ4_1_validationTypes", c( "Case study", "Example", "Experiment", "Real project", "Simulation"), 10, 5, 13) # RQ4.2 plot(robotTypesEval$robotTypeEval, "RQ4_2_robotTypesEval", c("Aerial robots", "Aquatic robots", "Generic robots", "Space robots", "Terrestrial robots"), 10, 5, 13) plot(multiRobotEval$multiRobotEval, "RQ4_2_multiRobotEval", c("Single robot", "Multiple robots"), 10, 5, 13) # RQ5 lwb <- dataCollapsed$languageWorkbench[which(dataCollapsed$languageWorkbench != "")] lwb <- droplevels(lwb) plot(lwb, "RQ5_lwbs", levels(lwb), 10, 5, 13) # Horizontal analysis pdf("./output/horizontals.pdf", width=6, height=4) par(mar=c(5, 5, 5, 5)) par(mfrow=c(1, 1)) par(las=1) plotBubbles <- function(var1, var2, var1Label, var2Label, var1Labels, var2Labels, plotTitle) { currentData <- merge(var1, var2, by="ID", all = T) currentData <- na.omit(currentData) var1Name <- names(currentData)[2] var2Name <- names(currentData)[3] counts <- count(currentData, c(var1Name, var2Name)) # print(counts) if(var1Label == "" && var2Label == "") { var1Label = var1Name var2Label = var2Name } if(plotTitle != "") { plotTitle = paste(var1Name, "___", var2Name) } plot <- ggplot(counts, aes(counts[,2], counts[,1], color=freq, alpha = 0.7)) + geom_point(aes(size = freq)) + theme_bw() + scale_color_gradient2(low="white", high="gray13", name="freq") + scale_size_continuous(range=c(0, 30)) + geom_text(aes(label = freq), color="black") + theme(legend.position = "none") + # labs(x=var2Name, y=var1Name) + # ggtitle(paste(var1Name, "___", var2Name)) labs(x=var2Label, y=var1Label) + ggtitle(plotTitle) if(var1Labels != "" && var2Labels != "") { plot <- plot + scale_y_discrete(labels= var1Labels) plot <- plot + scale_x_discrete(labels= var2Labels) } print(plot) } plotBubbles(contributionTypes, venues, "", "", "", "", "") plotBubbles(researchTypes, venues, "", "", "", "", "") plotBubbles(robotTypesEval, venues, "", "", "", "", "") plotBubbles(multiRobotEval, venues, "", "", "", "", "") plotBubbles(multiRobotApproach, venues, "", "", "", "", "") plotBubbles(languages, venues, "", "", "", "", "") plotBubbles(automationTypes, venues, "", "", "", "", "") plotBubbles(aspects, venues, "", "", "", "", "") plotBubbles(researchTypes, contributionTypes, "Research type (RQ1)", "Contribution type (RQ1)", c( "Evaluation research", "Experience paper", "Solution proposal", "Validation research"), c("Method", "Metric", "Model", "Open items", "Tool"), "") plotBubbles(robotTypesEval, contributionTypes, "", "", "", "", "") plotBubbles(multiRobotEval, contributionTypes, "", "", "", "", "") plotBubbles(languages, contributionTypes, "Type of modelling language (RQ3)", "Contribution type (RQ1)", c("DSL", "UML"), c("Method", "Metric", "Model", "Open items", "Tool"), "") plotBubbles(automationTypes, contributionTypes, "", "", "", "", "") plotBubbles(aspects, contributionTypes, "", "", "", "", "") plotBubbles(robotTypesEval, researchTypes, "", "", "", "", "") plotBubbles(multiRobotEval, researchTypes, "", "", "", "", "") plotBubbles(languages, researchTypes, "", "", "", "", "") plotBubbles(automationTypes, researchTypes, "", "", "", "", "") plotBubbles(aspects, researchTypes, "", "", "", "", "") plotBubbles(multiRobotEval, robotTypesEval, "Cardinality of robots (RQ4)", "Robot type (RQ4)", c("Single robot", "Multiple robots"), c("Aerial robots", "Aquatic robots", "Generic robots", "Space robots", "Terrestrial robots"), "") plotBubbles(multiRobotApproach, robotTypesApproach, "Cardinality of robots (RQ4)", "Robot type (RQ4)", c("Single robot", "Multiple robots"), c("Aerial robots", "Generic robots", "Space robots", "Terrestrial robots"), "") plotBubbles(languages, robotTypesEval, "", "", "", "", "") plotBubbles(automationTypes, robotTypesEval, "", "", "", "", "") plotBubbles(aspects, robotTypesEval, "", "", "", "", "") plotBubbles(multiRobotApproach, robotTypesApproach, "", "", "", "", "") plotBubbles(languages, robotTypesApproach, "", "", "", "", "") plotBubbles(automationTypes, robotTypesApproach, "", "", "", "", "") plotBubbles(aspects, robotTypesApproach, "", "", "", "", "") plotBubbles(languages, multiRobotApproach, "", "", "", "", "") plotBubbles(automationTypes, multiRobotApproach, "", "", "", "", "") plotBubbles(aspects, multiRobotApproach, "", "", "", "", "") plotBubbles(years, multiRobotApproach, "", "", "", "", "") plotBubbles(automationTypes, languages, "", "", "", "", "") plotBubbles(aspects, languages, "Engineered aspect (RQ3)", "Modelling language (RQ3)", c("Behaviour", "Navigation", "Structure"), c("DSL", "UML"), "") plotBubbles(aspects, automationTypes, "Engineered aspect (RQ3)", "Automation (RQ3)", c("Behaviour", "Navigation", "Structure"), c("Analysis", "Code generation", "Models at runtime", "Transformation"), "") dev.off()
module Collections.BSTree.Set import Collections.BSTree.Map as M import Collections.BSTree.Set.Core import Collections.BSTree.Set.Quantifiers import Collections.Util.Bnd import Data.Nat import Data.Nat.Order.Strict import Decidable.Order.Strict import public Collections.BSTree.Set.Core ------------------ -- CONSTRUCTION -- ------------------ ||| The empty tree. public export empty : {0 sto : kTy -> kTy -> Type} -> {auto pre : StrictPreorder kTy sto} -> {auto tot : StrictOrdered kTy sto} -> BSTree sto {pre} {tot} empty = M.empty ||| A tree with a single element. public export singleton : {0 sto : kTy -> kTy -> Type} -> {auto pre : StrictPreorder kTy sto} -> {auto tot : StrictOrdered kTy sto} -> (k : kTy) -> BSTree sto {pre} {tot} singleton k = M.singleton k () --------------- -- INSERTION -- --------------- ||| Insert an element in a tree. If the tree already contains an element equal to the given value, ||| it is replaced with the new value. export insert : {0 sto : kTy -> kTy -> Type} -> {pre : StrictPreorder kTy sto} -> {tot : StrictOrdered kTy sto} -> (k : kTy) -> BSTree sto {pre} {tot} -> BSTree sto {pre} {tot} insert k t = M.insert k () t -------------- -- QUERYING -- -------------- ||| Is the tree empty? export null : BSTree sto {pre} {tot} -> Bool null = M.null ||| The number of elements in the tree. export size : BSTree sto {pre} {tot} -> Nat size = M.size ||| Is the element in the tree? export member : {0 sto : kTy -> kTy -> Type} -> {pre : StrictPreorder kTy sto} -> {tot : StrictOrdered kTy sto} -> (k : kTy) -> BSTree sto {pre} {tot} -> Bool member = M.member ----------------------- -- DELETION / UPDATE -- ----------------------- ||| Delete an element from a tree. When the element is not in the tree, the original tree is ||| returned. export delete : {0 sto : kTy -> kTy -> Type} -> {pre : StrictPreorder kTy sto} -> {tot : StrictOrdered kTy sto} -> (k : kTy) -> BSTree sto {pre} {tot} -> BSTree sto {pre} {tot} delete = M.delete
Inductive even : nat -> Prop := |EvenO : even 0 |EvenSS : forall n : nat, even n -> even(S(S n)). Theorem even_0 : even 0. Proof. apply EvenO. Qed. Theorem even_4 : even 4. Proof. apply EvenSS. apply EvenSS. apply EvenO. Qed. Theorem even_4_1 : even 4. Proof. constructor. constructor. constructor. Qed. (* Hint Resolve EvenO. Hint Resolve EvenSS. *) Hint Constructors even. Theorem even_4_2 : even 4. Proof. auto. Qed.
[STATEMENT] lemma iTrigger_iSince_conv: "(P t'. t' \<T> t I. Q t) = ((\<box> t I. Q t) \<or> (Q t'. t' \<S> t I. (Q t \<and> P t)))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (P t'. t' \<T> t I. Q t) = ((\<box> t I. Q t) \<or> (Q t'. t' \<S> t I. Q t \<and> P t)) [PROOF STEP] by (fastforce simp: iTrigger_iWeakSince_conv iWeakSince_iSince_conv)
State Before: α : Type u_1 β : Type ?u.728649 γ : Type ?u.728652 δ : Type ?u.728655 ι : Type ?u.728658 R : Type ?u.728661 R' : Type ?u.728664 m0 : MeasurableSpace α inst✝² : MeasurableSpace β inst✝¹ : MeasurableSpace γ μ✝ μ₁ μ₂ μ₃ ν ν' ν₁ ν₂ : Measure α s s' t : Set α μ : Measure α inst✝ : SigmaFinite μ x : α n : ℕ ⊢ spanningSetsIndex μ x = n ↔ x ∈ disjointed (spanningSets μ) n State After: no goals Tactic: convert Set.ext_iff.1 (preimage_spanningSetsIndex_singleton μ n) x
(* Author: Tobias Nipkow, Max Haslbeck *) subsection "The Variables in an Expression" theory Vars imports Com begin text\<open>We need to collect the variables in both arithmetic and boolean expressions. For a change we do not introduce two functions, e.g.\ \<open>avars\<close> and \<open>bvars\<close>, but we overload the name \<open>vars\<close> via a \emph{type class}, a device that originated with Haskell:\<close> class vars = fixes vars :: "'a \<Rightarrow> vname set" text\<open>This defines a type class ``vars'' with a single function of (coincidentally) the same name. Then we define two separated instances of the class, one for @{typ aexp} and one for @{typ bexp}:\<close> instantiation aexp :: vars begin fun vars_aexp :: "aexp \<Rightarrow> vname set" where "vars (N n) = {}" | "vars (V x) = {x}" | "vars (Plus a\<^sub>1 a\<^sub>2) = vars a\<^sub>1 \<union> vars a\<^sub>2" | "vars (Times a\<^sub>1 a\<^sub>2) = vars a\<^sub>1 \<union> vars a\<^sub>2" | "vars (Div a\<^sub>1 a\<^sub>2) = vars a\<^sub>1 \<union> vars a\<^sub>2" instance .. end value "vars (Plus (V ''x'') (V ''y''))" instantiation bexp :: vars begin fun vars_bexp :: "bexp \<Rightarrow> vname set" where "vars (Bc v) = {}" | "vars (Not b) = vars b" | "vars (And b\<^sub>1 b\<^sub>2) = vars b\<^sub>1 \<union> vars b\<^sub>2" | "vars (Less a\<^sub>1 a\<^sub>2) = vars a\<^sub>1 \<union> vars a\<^sub>2" instance .. end value "vars (Less (Plus (V ''z'') (V ''y'')) (V ''x''))" abbreviation eq_on :: "('a \<Rightarrow> 'b) \<Rightarrow> ('a \<Rightarrow> 'b) \<Rightarrow> 'a set \<Rightarrow> bool" ("(_ =/ _/ on _)" [50,0,50] 50) where "f = g on X == \<forall> x \<in> X. f x = g x" lemma aval_eq_if_eq_on_vars[simp]: "s\<^sub>1 = s\<^sub>2 on vars a \<Longrightarrow> aval a s\<^sub>1 = aval a s\<^sub>2" apply(induction a) apply simp_all done lemma bval_eq_if_eq_on_vars: "s\<^sub>1 = s\<^sub>2 on vars b \<Longrightarrow> bval b s\<^sub>1 = bval b s\<^sub>2" proof(induction b) case (Less a1 a2) hence "aval a1 s\<^sub>1 = aval a1 s\<^sub>2" and "aval a2 s\<^sub>1 = aval a2 s\<^sub>2" by simp_all thus ?case by simp qed simp_all fun lvars :: "com \<Rightarrow> vname set" where "lvars SKIP = {}" | "lvars (x::=e) = {x}" | "lvars (c1;;c2) = lvars c1 \<union> lvars c2" | "lvars (IF b THEN c1 ELSE c2) = lvars c1 \<union> lvars c2" | "lvars (WHILE b DO c) = lvars c" fun rvars :: "com \<Rightarrow> vname set" where "rvars SKIP = {}" | "rvars (x::=e) = vars e" | "rvars (c1;;c2) = rvars c1 \<union> rvars c2" | "rvars (IF b THEN c1 ELSE c2) = vars b \<union> rvars c1 \<union> rvars c2" | "rvars (WHILE b DO c) = vars b \<union> rvars c" instantiation com :: vars begin definition "vars_com c = lvars c \<union> rvars c" instance .. end lemma vars_com_simps[simp]: "vars SKIP = {}" "vars (x::=e) = {x} \<union> vars e" "vars (c1;;c2) = vars c1 \<union> vars c2" "vars (IF b THEN c1 ELSE c2) = vars b \<union> vars c1 \<union> vars c2" "vars (WHILE b DO c) = vars b \<union> vars c" by(auto simp: vars_com_def) end
// Copyright 2017 Rodeo FX. All rights reserved. #include "rdoCustomResource.h" #include <boost/algorithm/string.hpp> #include <boost/filesystem.hpp> #include <pxr/base/plug/plugin.h> #include <pxr/base/tf/fileUtils.h> #include <pxr/base/tf/token.h> #include <pxr/usd/sdf/layer.h> #include <string> #include <unordered_map> #include <fstream> #include <sstream> PXR_NAMESPACE_USING_DIRECTIVE std::unordered_map<std::string, const char*> resource; // Split the given path and return the vector of directories. std::vector<std::string> splitPath(const boost::filesystem::path &src) { std::vector<std::string> elements; for (const auto &p : src) { elements.push_back(p.c_str()); } return elements; } void setResource(const char* filename, const char* contents) { std::vector<std::string> pathVect = splitPath(filename); while (!pathVect.empty()) { std::string joined = boost::algorithm::join(pathVect, "/"); resource[joined] = contents; pathVect.erase(pathVect.begin()); } } const char* getResource(const char* filename) { std::vector<std::string> pathVect = splitPath(filename); while (!pathVect.empty()) { std::string joined = boost::algorithm::join(pathVect, "/"); auto it = resource.find(joined); if (it != resource.end()) { return it->second; } pathVect.erase(pathVect.begin()); } return nullptr; } // USD overrides extern "C" TfToken _GetShaderPath(char const* shader) { return TfToken(shader); } extern "C" std::istream* _GetFileStream(const char* filename) { // Try to search in the saved resources first. const char* data = getResource(filename); if (data) { return new std::istringstream(data); } return new std::ifstream(filename); } extern "C" SdfLayerRefPtr _GetGeneratedSchema(const PlugPluginPtr &plugin) { // Look for generatedSchema in Resources. const std::string filename = TfStringCatPaths( plugin->GetResourcePath(), "generatedSchema.usda"); const char* data = getResource(filename.c_str()); if (data) { SdfLayerRefPtr layer = SdfLayer::CreateAnonymous(filename); if (layer->ImportFromString(data)) { return layer; } } return TfIsFile(filename) ? SdfLayer::OpenAsAnonymous(filename) : TfNullPtr; }
State Before: α : Type u_3 β : Type u_2 ι : Type ?u.1474570 mα : MeasurableSpace α mβ : MeasurableSpace β κ η : { x // x ∈ kernel α β } s : Set α hs : MeasurableSet s inst✝³ : DecidablePred fun x => x ∈ s E : Type u_1 inst✝² : NormedAddCommGroup E inst✝¹ : NormedSpace ℝ E inst✝ : CompleteSpace E a : α g : β → E t : Set β ⊢ (∫ (b : β) in t, g b ∂↑(piecewise hs κ η) a) = if a ∈ s then ∫ (b : β) in t, g b ∂↑κ a else ∫ (b : β) in t, g b ∂↑η a State After: α : Type u_3 β : Type u_2 ι : Type ?u.1474570 mα : MeasurableSpace α mβ : MeasurableSpace β κ η : { x // x ∈ kernel α β } s : Set α hs : MeasurableSet s inst✝³ : DecidablePred fun x => x ∈ s E : Type u_1 inst✝² : NormedAddCommGroup E inst✝¹ : NormedSpace ℝ E inst✝ : CompleteSpace E a : α g : β → E t : Set β ⊢ (∫ (b : β) in t, g b ∂if a ∈ s then ↑κ a else ↑η a) = if a ∈ s then ∫ (b : β) in t, g b ∂↑κ a else ∫ (b : β) in t, g b ∂↑η a Tactic: simp_rw [piecewise_apply] State Before: α : Type u_3 β : Type u_2 ι : Type ?u.1474570 mα : MeasurableSpace α mβ : MeasurableSpace β κ η : { x // x ∈ kernel α β } s : Set α hs : MeasurableSet s inst✝³ : DecidablePred fun x => x ∈ s E : Type u_1 inst✝² : NormedAddCommGroup E inst✝¹ : NormedSpace ℝ E inst✝ : CompleteSpace E a : α g : β → E t : Set β ⊢ (∫ (b : β) in t, g b ∂if a ∈ s then ↑κ a else ↑η a) = if a ∈ s then ∫ (b : β) in t, g b ∂↑κ a else ∫ (b : β) in t, g b ∂↑η a State After: no goals Tactic: split_ifs <;> rfl
(** * Hoare2: Hoare Logic, Part II *) Require Import Coq.Bool.Bool. Require Import Coq.Arith.Arith. Require Import Coq.Arith.EqNat. Require Import Coq.omega.Omega. Require Import SfLib. Require Import Maps. Require Import Imp. Require Import Hoare. (* ################################################################# *) (** * Decorated Programs *) (** The beauty of Hoare Logic is that it is _compositional_: the structure of proofs exactly follows the structure of programs. This suggests that we can record the essential ideas of a proof informally (leaving out some low-level calculational details) by decorating a program with appropriate assertions on each of its commands. Such a _decorated program_ carries with it an (informal) proof of its own correctness. For example, here is a complete decorated program: *) (** {{ True }} ->> {{ m = m }} X ::= m;; {{ X = m }} ->> {{ X = m /\ p = p }} Z ::= p; {{ X = m /\ Z = p }} ->> {{ Z - X = p - m }} WHILE X <> 0 DO {{ Z - X = p - m /\ X <> 0 }} ->> {{ (Z - 1) - (X - 1) = p - m }} Z ::= Z - 1;; {{ Z - (X - 1) = p - m }} X ::= X - 1 {{ Z - X = p - m }} END; {{ Z - X = p - m /\ ~ (X <> 0) }} ->> {{ Z = p - m }} *) (** Concretely, a decorated program consists of the program text interleaved with assertions (either a single assertion or possibly two assertions separated by an implication). To check that a decorated program represents a valid proof, we check that each individual command is _locally consistent_ with its nearby assertions in the following sense: *) (** - [SKIP] is locally consistent if its precondition and postcondition are the same: {{ P }} SKIP {{ P }} *) (** - The sequential composition of [c1] and [c2] is locally consistent (with respect to assertions [P] and [R]) if [c1] is locally consistent (with respect to [P] and [Q]) and [c2] is locally consistent (with respect to [Q] and [R]): {{ P }} c1;; {{ Q }} c2 {{ R }} *) (** - An assignment is locally consistent if its precondition is the appropriate substitution of its postcondition: {{ P [X |-> a] }} X ::= a {{ P }} *) (** - A conditional is locally consistent (with respect to assertions [P] and [Q]) if the assertions at the top of its "then" and "else" branches are exactly [P /\ b] and [P /\ ~b] and if its "then" branch is locally consistent (with respect to [P /\ b] and [Q]) and its "else" branch is locally consistent (with respect to [P /\ ~b] and [Q]): {{ P }} IFB b THEN {{ P /\ b }} c1 {{ Q }} ELSE {{ P /\ ~b }} c2 {{ Q }} FI {{ Q }} *) (** - A while loop with precondition [P] is locally consistent if its postcondition is [P /\ ~b], if the pre- and postconditions of its body are exactly [P /\ b] and [P], and if its body is locally consistent: {{ P }} WHILE b DO {{ P /\ b }} c1 {{ P }} END {{ P /\ ~b }} *) (** - A pair of assertions separated by [->>] is locally consistent if the first implies the second (in all states): {{ P }} ->> {{ P' }} This corresponds to the application of [hoare_consequence] and is the only place in a decorated program where checking if decorations are correct is not fully mechanical and syntactic, but rather may involve logical and/or arithmetic reasoning. *) (** The above essentially describes a procedure for _verifying_ the correctness of a given proof involves checking that every single command is locally consistent with the accompanying assertions. If we are instead interested in _finding_ a proof for a given specification, we need to discover the right assertions. This can be done in an almost mechanical way, with the exception of finding loop invariants, which is the subject of the next section. In the remainder of this section we explain in detail how to construct decorations for several simple programs that don't involve non-trivial loop invariants. *) (* ================================================================= *) (** ** Example: Swapping Using Addition and Subtraction *) (** Here is a program that swaps the values of two variables using addition and subtraction (instead of by assigning to a temporary variable). X ::= X + Y;; Y ::= X - Y;; X ::= X - Y We can prove using decorations that this program is correct -- i.e., it always swaps the values of variables [X] and [Y]. *) (** (1) {{ X = m /\ Y = n }} ->> (2) {{ (X + Y) - ((X + Y) - Y) = n /\ (X + Y) - Y = m }} X ::= X + Y;; (3) {{ X - (X - Y) = n /\ X - Y = m }} Y ::= X - Y;; (4) {{ X - Y = n /\ Y = m }} X ::= X - Y (5) {{ X = n /\ Y = m }} *) (** These decorations can be constructed as follows: - We begin with the undecorated program (the unnumbered lines). - We then add the specification -- i.e., the outer precondition (1) and postcondition (5). In the precondition we use auxiliary variables (parameters) [m] and [n] to remember the initial values of variables [X] and respectively [Y], so that we can refer to them in the postcondition (5). - We work backwards mechanically, starting from (5) and proceeding until we get to (2). At each step, we obtain the precondition of the assignment from its postcondition by substituting the assigned variable with the right-hand-side of the assignment. For instance, we obtain (4) by substituting [X] with [X - Y] in (5), and (3) by substituting [Y] with [X - Y] in (4). - Finally, we verify that (1) logically implies (2) -- i.e., that the step from (1) to (2) is a valid use of the law of consequence. For this we substitute [X] by [m] and [Y] by [n] and calculate as follows: (m + n) - ((m + n) - n) = n /\ (m + n) - n = m (m + n) - m = n /\ m = m n = n /\ m = m Note that, since we are working with natural numbers, not fixed-width machine integers, we don't need to worry about the possibility of arithmetic overflow anywhere in this argument. This makes life quite a bit simpler! *) (* ================================================================= *) (** ** Example: Simple Conditionals *) (** Here is a simple decorated program using conditionals: (1) {{True}} IFB X <= Y THEN (2) {{True /\ X <= Y}} ->> (3) {{(Y - X) + X = Y \/ (Y - X) + Y = X}} Z ::= Y - X (4) {{Z + X = Y \/ Z + Y = X}} ELSE (5) {{True /\ ~(X <= Y) }} ->> (6) {{(X - Y) + X = Y \/ (X - Y) + Y = X}} Z ::= X - Y (7) {{Z + X = Y \/ Z + Y = X}} FI (8) {{Z + X = Y \/ Z + Y = X}} These decorations were constructed as follows: - We start with the outer precondition (1) and postcondition (8). - We follow the format dictated by the [hoare_if] rule and copy the postcondition (8) to (4) and (7). We conjoin the precondition (1) with the guard of the conditional to obtain (2). We conjoin (1) with the negated guard of the conditional to obtain (5). - In order to use the assignment rule and obtain (3), we substitute [Z] by [Y - X] in (4). To obtain (6) we substitute [Z] by [X - Y] in (7). - Finally, we verify that (2) implies (3) and (5) implies (6). Both of these implications crucially depend on the ordering of [X] and [Y] obtained from the guard. For instance, knowing that [X <= Y] ensures that subtracting [X] from [Y] and then adding back [X] produces [Y], as required by the first disjunct of (3). Similarly, knowing that [~ (X <= Y)] ensures that subtracting [Y] from [X] and then adding back [Y] produces [X], as needed by the second disjunct of (6). Note that [n - m + m = n] does _not_ hold for arbitrary natural numbers [n] and [m] (for example, [3 - 5 + 5 = 5]). *) (** **** Exercise: 2 stars (if_minus_plus_reloaded) *) (** Fill in valid decorations for the following program: {{ True }} IFB X <= Y THEN {{ }} ->> {{ }} Z ::= Y - X {{ }} ELSE {{ }} ->> {{ }} Y ::= X + Z {{ }} FI {{ Y = X + Z }} *) (** [] *) (* ================================================================= *) (** ** Example: Reduce to Zero *) (** Here is a [WHILE] loop that is so simple it needs no invariant (i.e., the invariant [True] will do the job). (1) {{ True }} WHILE X <> 0 DO (2) {{ True /\ X <> 0 }} ->> (3) {{ True }} X ::= X - 1 (4) {{ True }} END (5) {{ True /\ X = 0 }} ->> (6) {{ X = 0 }} The decorations can be constructed as follows: - Start with the outer precondition (1) and postcondition (6). - Following the format dictated by the [hoare_while] rule, we copy (1) to (4). We conjoin (1) with the guard to obtain (2) and with the negation of the guard to obtain (5). Note that, because the outer postcondition (6) does not syntactically match (5), we need a trivial use of the consequence rule from (5) to (6). - Assertion (3) is the same as (4), because [X] does not appear in [4], so the substitution in the assignment rule is trivial. - Finally, the implication between (2) and (3) is also trivial. *) (** From this informal proof, it is easy to read off a formal proof using the Coq versions of the Hoare rules. Note that we do _not_ unfold the definition of [hoare_triple] anywhere in this proof -- the idea is to use the Hoare rules as a "self-contained" logic for reasoning about programs. *) Definition reduce_to_zero' : com := WHILE BNot (BEq (AId X) (ANum 0)) DO X ::= AMinus (AId X) (ANum 1) END. Theorem reduce_to_zero_correct' : {{fun st => True}} reduce_to_zero' {{fun st => st X = 0}}. Proof. unfold reduce_to_zero'. (* First we need to transform the postcondition so that hoare_while will apply. *) eapply hoare_consequence_post. apply hoare_while. - (* Loop body preserves invariant *) (* Need to massage precondition before [hoare_asgn] applies *) eapply hoare_consequence_pre. apply hoare_asgn. (* Proving trivial implication (2) ->> (3) *) intros st [HT Hbp]. unfold assn_sub. apply I. - (* Invariant and negated guard imply postcondition *) intros st [Inv GuardFalse]. unfold bassn in GuardFalse. simpl in GuardFalse. (* SearchAbout helps to find the right lemmas *) SearchAbout [not true]. rewrite not_true_iff_false in GuardFalse. SearchAbout [negb false]. rewrite negb_false_iff in GuardFalse. SearchAbout [beq_nat true]. apply beq_nat_true in GuardFalse. apply GuardFalse. Qed. (* ================================================================= *) (** ** Example: Division *) (** The following Imp program calculates the integer quotient and remainder of two numbers [m] and [n] that are arbitrary constants in the program. X ::= m;; Y ::= 0;; WHILE n <= X DO X ::= X - n;; Y ::= Y + 1 END; In we replace [m] and [n] by concrete numbers and execute the program, it will terminate with the variable [X] set to the remainder when [m] is divided by [n] and [Y] set to the quotient. *) (** In order to give a specification to this program we need to remember that dividing [m] by [n] produces a reminder [X] and a quotient [Y] such that [n * Y + X = m /\ X < n]. It turns out that we get lucky with this program and don't have to think very hard about the loop invariant: the invariant is just the first conjunct [n * Y + X = m], and we can use this to decorate the program. (1) {{ True }} ->> (2) {{ n * 0 + m = m }} X ::= m;; (3) {{ n * 0 + X = m }} Y ::= 0;; (4) {{ n * Y + X = m }} WHILE n <= X DO (5) {{ n * Y + X = m /\ n <= X }} ->> (6) {{ n * (Y + 1) + (X - n) = m }} X ::= X - n;; (7) {{ n * (Y + 1) + X = m }} Y ::= Y + 1 (8) {{ n * Y + X = m }} END (9) {{ n * Y + X = m /\ X < n }} Assertions (4), (5), (8), and (9) are derived mechanically from the invariant and the loop's guard. Assertions (8), (7), and (6) are derived using the assignment rule going backwards from (8) to (6). Assertions (4), (3), and (2) are again backwards applications of the assignment rule. Now that we've decorated the program it only remains to check that the two uses of the consequence rule are correct -- i.e., that (1) implies (2) and that (5) implies (6). This is indeed the case, so we have a valid decorated program. *) (* ################################################################# *) (** * Finding Loop Invariants *) (** Once the outermost precondition and postcondition are chosen, the only creative part in verifying programs using Hoare Logic is finding the right loop invariants. The reason this is difficult is the same as the reason that inductive mathematical proofs are: strengthening the loop invariant (or the induction hypothesis) means that you have a stronger assumption to work with when trying to establish the postcondition of the loop body (or complete the induction step of the proof), but it also means that the loop body postcondition itself (or the statement being proved inductively) is stronger and thus harder to prove! This section shows how to approach the challenge of finding loop invariants through a series of examples and exercises. *) (* ================================================================= *) (** ** Example: Slow Subtraction *) (** The following program subtracts the value of [X] from the value of [Y] by repeatedly decrementing both [X] and [Y]. We want to verify its correctness with respect to the following specification: {{ X = m /\ Y = n }} WHILE X <> 0 DO Y ::= Y - 1;; X ::= X - 1 END {{ Y = n - m }} To verify this program, we need to find an invariant [I] for the loop. As a first step we can leave [I] as an unknown and build a _skeleton_ for the proof by applying (backward) the rules for local consistency. This process leads to the following skeleton: (1) {{ X = m /\ Y = n }} ->> (a) (2) {{ I }} WHILE X <> 0 DO (3) {{ I /\ X <> 0 }} ->> (c) (4) {{ I [X |-> X-1] [Y |-> Y-1] }} Y ::= Y - 1;; (5) {{ I [X |-> X-1] }} X ::= X - 1 (6) {{ I }} END (7) {{ I /\ ~ (X <> 0) }} ->> (b) (8) {{ Y = n - m }} By examining this skeleton, we can see that any valid [I] will have to respect three conditions: - (a) it must be weak enough to be implied by the loop's precondition, i.e., (1) must imply (2); - (b) it must be strong enough to imply the loop's postcondition, i.e., (7) must imply (8); - (c) it must be preserved by one iteration of the loop, i.e., (3) must imply (4). *) (** These conditions are actually independent of the particular program and specification we are considering. Indeed, every loop invariant has to satisfy them. One way to find an invariant that simultaneously satisfies these three conditions is by using an iterative process: start with a "candidate" invariant (e.g., a guess or a heuristic choice) and check the three conditions above; if any of the checks fails, try to use the information that we get from the failure to produce another -- hopefully better -- candidate invariant, and repeat the process. For instance, in the reduce-to-zero example above, we saw that, for a very simple loop, choosing [True] as an invariant did the job. So let's try instantiating [I] with [True] in the skeleton above see what we get... (1) {{ X = m /\ Y = n }} ->> (a - OK) (2) {{ True }} WHILE X <> 0 DO (3) {{ True /\ X <> 0 }} ->> (c - OK) (4) {{ True }} Y ::= Y - 1;; (5) {{ True }} X ::= X - 1 (6) {{ True }} END (7) {{ True /\ X = 0 }} ->> (b - WRONG!) (8) {{ Y = n - m }} While conditions (a) and (c) are trivially satisfied, condition (b) is wrong, i.e., it is not the case that (7) [True /\ X = 0] implies (8) [Y = n - m]. In fact, the two assertions are completely unrelated, so it is very easy to find a counterexample to the implication (say, [Y = X = m = 0] and [n = 1]). If we want (b) to hold, we need to strengthen the invariant so that it implies the postcondition (8). One simple way to do this is to let the invariant _be_ the postcondition. So let's return to our skeleton, instantiate [I] with [Y = n - m], and check conditions (a) to (c) again. (1) {{ X = m /\ Y = n }} ->> (a - WRONG!) (2) {{ Y = n - m }} WHILE X <> 0 DO (3) {{ Y = n - m /\ X <> 0 }} ->> (c - WRONG!) (4) {{ Y - 1 = n - m }} Y ::= Y - 1;; (5) {{ Y = n - m }} X ::= X - 1 (6) {{ Y = n - m }} END (7) {{ Y = n - m /\ X = 0 }} ->> (b - OK) (8) {{ Y = n - m }} This time, condition (b) holds trivially, but (a) and (c) are broken. Condition (a) requires that (1) [X = m /\ Y = n] implies (2) [Y = n - m]. If we substitute [Y] by [n] we have to show that [n = n - m] for arbitrary [m] and [n], which is not the case (for instance, when [m = n = 1]). Condition (c) requires that [n - m - 1 = n - m], which fails, for instance, for [n = 1] and [m = 0]. So, although [Y = n - m] holds at the end of the loop, it does not hold from the start, and it doesn't hold on each iteration; it is not a correct invariant. This failure is not very surprising: the variable [Y] changes during the loop, while [m] and [n] are constant, so the assertion we chose didn't have much chance of being an invariant! To do better, we need to generalize (8) to some statement that is equivalent to (8) when [X] is [0], since this will be the case when the loop terminates, and that "fills the gap" in some appropriate way when [X] is nonzero. Looking at how the loop works, we can observe that [X] and [Y] are decremented together until [X] reaches [0]. So, if [X = 2] and [Y = 5] initially, after one iteration of the loop we obtain [X = 1] and [Y = 4]; after two iterations [X = 0] and [Y = 3]; and then the loop stops. Notice that the difference between [Y] and [X] stays constant between iterations: initially, [Y = n] and [X = m], and the difference is always [n - m]. So let's try instantiating [I] in the skeleton above with [Y - X = n - m]. (1) {{ X = m /\ Y = n }} ->> (a - OK) (2) {{ Y - X = n - m }} WHILE X <> 0 DO (3) {{ Y - X = n - m /\ X <> 0 }} ->> (c - OK) (4) {{ (Y - 1) - (X - 1) = n - m }} Y ::= Y - 1;; (5) {{ Y - (X - 1) = n - m }} X ::= X - 1 (6) {{ Y - X = n - m }} END (7) {{ Y - X = n - m /\ X = 0 }} ->> (b - OK) (8) {{ Y = n - m }} Success! Conditions (a), (b) and (c) all hold now. (To verify (c), we need to check that, under the assumption that [X <> 0], we have [Y - X = (Y - 1) - (X - 1)]; this holds for all natural numbers [X] and [Y].) *) (* ================================================================= *) (** ** Exercise: Slow Assignment *) (** **** Exercise: 2 stars (slow_assignment) *) (** A roundabout way of assigning a number currently stored in [X] to the variable [Y] is to start [Y] at [0], then decrement [X] until it hits [0], incrementing [Y] at each step. Here is a program that implements this idea: {{ X = m }} Y ::= 0;; WHILE X <> 0 DO X ::= X - 1;; Y ::= Y + 1 END {{ Y = m }} Write an informal decorated program showing that this procedure is correct. *) (* FILL IN HERE *) (** [] *) (* ================================================================= *) (** ** Exercise: Slow Addition *) (** **** Exercise: 3 stars, optional (add_slowly_decoration) *) (** The following program adds the variable X into the variable Z by repeatedly decrementing X and incrementing Z. WHILE X <> 0 DO Z ::= Z + 1;; X ::= X - 1 END Following the pattern of the [subtract_slowly] example above, pick a precondition and postcondition that give an appropriate specification of [add_slowly]; then (informally) decorate the program accordingly. *) (* FILL IN HERE *) (** [] *) (* ================================================================= *) (** ** Example: Parity *) (** Here is a cute little program for computing the parity of the value initially stored in [X] (due to Daniel Cristofani). {{ X = m }} WHILE 2 <= X DO X ::= X - 2 END {{ X = parity m }} The mathematical [parity] function used in the specification is defined in Coq as follows: *) Fixpoint parity x := match x with | 0 => 0 | 1 => 1 | S (S x') => parity x' end. (** The postcondition does not hold at the beginning of the loop, since [m = parity m] does not hold for an arbitrary [m], so we cannot use that as an invariant. To find an invariant that works, let's think a bit about what this loop does. On each iteration it decrements [X] by [2], which preserves the parity of [X]. So the parity of [X] does not change, i.e., it is invariant. The initial value of [X] is [m], so the parity of [X] is always equal to the parity of [m]. Using [parity X = parity m] as an invariant we obtain the following decorated program: {{ X = m }} ->> (a - OK) {{ parity X = parity m }} WHILE 2 <= X DO {{ parity X = parity m /\ 2 <= X }} ->> (c - OK) {{ parity (X-2) = parity m }} X ::= X - 2 {{ parity X = parity m }} END {{ parity X = parity m /\ X < 2 }} ->> (b - OK) {{ X = parity m }} With this invariant, conditions (a), (b), and (c) are all satisfied. For verifying (b), we observe that, when [X < 2], we have [parity X = X] (we can easily see this in the definition of [parity]). For verifying (c), we observe that, when [2 <= X], we have [parity X = parity (X-2)]. *) (** **** Exercise: 3 stars, optional (parity_formal) *) (** Translate this proof to Coq. Refer to the reduce-to-zero example for ideas. You may find the following two lemmas useful: *) Lemma parity_ge_2 : forall x, 2 <= x -> parity (x - 2) = parity x. Proof. induction x; intro. reflexivity. destruct x. inversion H. inversion H1. simpl. rewrite <- minus_n_O. reflexivity. Qed. Lemma parity_lt_2 : forall x, ~ 2 <= x -> parity (x) = x. Proof. intros. induction x. reflexivity. destruct x. reflexivity. exfalso. apply H. omega. Qed. Theorem parity_correct : forall m, {{ fun st => st X = m }} WHILE BLe (ANum 2) (AId X) DO X ::= AMinus (AId X) (ANum 2) END {{ fun st => st X = parity m }}. Proof. (* FILL IN HERE *) Admitted. (** [] *) (* ================================================================= *) (** ** Example: Finding Square Roots *) (** The following program computes the square root of [X] by naive iteration: {{ X=m }} Z ::= 0;; WHILE (Z+1)*(Z+1) <= X DO Z ::= Z+1 END {{ Z*Z<=m /\ m<(Z+1)*(Z+1) }} *) (** As above, we can try to use the postcondition as a candidate invariant, obtaining the following decorated program: (1) {{ X=m }} ->> (a - second conjunct of (2) WRONG!) (2) {{ 0*0 <= m /\ m<1*1 }} Z ::= 0;; (3) {{ Z*Z <= m /\ m<(Z+1)*(Z+1) }} WHILE (Z+1)*(Z+1) <= X DO (4) {{ Z*Z<=m /\ (Z+1)*(Z+1)<=X }} ->> (c - WRONG!) (5) {{ (Z+1)*(Z+1)<=m /\ m<(Z+2)*(Z+2) }} Z ::= Z+1 (6) {{ Z*Z<=m /\ m<(Z+1)*(Z+1) }} END (7) {{ Z*Z<=m /\ m<(Z+1)*(Z+1) /\ X<(Z+1)*(Z+1) }} ->> (b - OK) (8) {{ Z*Z<=m /\ m<(Z+1)*(Z+1) }} This didn't work very well: conditions (a) and (c) both failed. Looking at condition (c), we see that the second conjunct of (4) is almost the same as the first conjunct of (5), except that (4) mentions [X] while (5) mentions [m]. But note that [X] is never assigned in this program, so we should always have [X=m], but we didn't propagate this information from (1) into the loop invariant. Also, looking at the second conjunct of (8), it seems quite hopeless as an invariant; fortunately and we don't even need it, since we can obtain it from the negation of the guard -- the third conjunct in (7) -- again under the assumption that [X=m]. So we now try [X=m /\ Z*Z <= m] as the loop invariant: {{ X=m }} ->> (a - OK) {{ X=m /\ 0*0 <= m }} Z ::= 0; {{ X=m /\ Z*Z <= m }} WHILE (Z+1)*(Z+1) <= X DO {{ X=m /\ Z*Z<=m /\ (Z+1)*(Z+1)<=X }} ->> (c - OK) {{ X=m /\ (Z+1)*(Z+1)<=m }} Z ::= Z+1 {{ X=m /\ Z*Z<=m }} END {{ X=m /\ Z*Z<=m /\ X<(Z+1)*(Z+1) }} ->> (b - OK) {{ Z*Z<=m /\ m<(Z+1)*(Z+1) }} This works, since conditions (a), (b), and (c) are now all trivially satisfied. Very often, even if a variable is used in a loop in a read-only fashion (i.e., it is referred to by the program or by the specification and it is not changed by the loop), it is necessary to add the fact that it doesn't change to the loop invariant. *) (* ================================================================= *) (** ** Example: Squaring *) (** Here is a program that squares [X] by repeated addition: {{ X = m }} Y ::= 0;; Z ::= 0;; WHILE Y <> X DO Z ::= Z + X;; Y ::= Y + 1 END {{ Z = m*m }} *) (** The first thing to note is that the loop reads [X] but doesn't change its value. As we saw in the previous example, it is a good idea in such cases to add [X = m] to the invariant. The other thing that we know is often useful in the invariant is the postcondition, so let's add that too, leading to the invariant candidate [Z = m * m /\ X = m]. {{ X = m }} ->> (a - WRONG) {{ 0 = m*m /\ X = m }} Y ::= 0;; {{ 0 = m*m /\ X = m }} Z ::= 0;; {{ Z = m*m /\ X = m }} WHILE Y <> X DO {{ Z = Y*m /\ X = m /\ Y <> X }} ->> (c - WRONG) {{ Z+X = m*m /\ X = m }} Z ::= Z + X;; {{ Z = m*m /\ X = m }} Y ::= Y + 1 {{ Z = m*m /\ X = m }} END {{ Z = m*m /\ X = m /\ Y = X }} ->> (b - OK) {{ Z = m*m }} Conditions (a) and (c) fail because of the [Z = m*m] part. While [Z] starts at [0] and works itself up to [m*m], we can't expect [Z] to be [m*m] from the start. If we look at how [Z] progesses in the loop, after the 1st iteration [Z = m], after the 2nd iteration [Z = 2*m], and at the end [Z = m*m]. Since the variable [Y] tracks how many times we go through the loop, this leads us to derive a new invariant candidate: [Z = Y*m /\ X = m]. {{ X = m }} ->> (a - OK) {{ 0 = 0*m /\ X = m }} Y ::= 0;; {{ 0 = Y*m /\ X = m }} Z ::= 0;; {{ Z = Y*m /\ X = m }} WHILE Y <> X DO {{ Z = Y*m /\ X = m /\ Y <> X }} ->> (c - OK) {{ Z+X = (Y+1)*m /\ X = m }} Z ::= Z + X; {{ Z = (Y+1)*m /\ X = m }} Y ::= Y + 1 {{ Z = Y*m /\ X = m }} END {{ Z = Y*m /\ X = m /\ Y = X }} ->> (b - OK) {{ Z = m*m }} This new invariant makes the proof go through: all three conditions are easy to check. It is worth comparing the postcondition [Z = m*m] and the [Z = Y*m] conjunct of the invariant. It is often the case that one has to replace auxiliary variabes (parameters) with variables -- or with expressions involving both variables and parameters, like [m - Y] -- when going from postconditions to invariants. *) (* ================================================================= *) (** ** Exercise: Factorial *) (** **** Exercise: 3 stars (factorial) *) (** Recall that [n!] denotes the factorial of [n] (i.e., [n! = 1*2*...*n]). Here is an Imp program that calculates the factorial of the number initially stored in the variable [X] and puts it in the variable [Y]: {{ X = m }} Y ::= 1 ;; WHILE X <> 0 DO Y ::= Y * X ;; X ::= X - 1 END {{ Y = m! }} Fill in the blanks in following decorated program: {{ X = m }} ->> {{ }} Y ::= 1;; {{ }} WHILE X <> 0 DO {{ }} ->> {{ }} Y ::= Y * X;; {{ }} X ::= X - 1 {{ }} END {{ }} ->> {{ Y = m! }} *) (** [] *) (* ================================================================= *) (** ** Exercise: Min *) (** **** Exercise: 3 stars (Min_Hoare) *) (** Fill in valid decorations for the following program. For the [=>] steps in your annotations, you may rely (silently) on the following facts about min Lemma lemma1 : forall x y, (x=0 \/ y=0) -> min x y = 0. Lemma lemma2 : forall x y, min (x-1) (y-1) = (min x y) - 1. plus standard high-school algebra, as always. {{ True }} ->> {{ }} X ::= a;; {{ }} Y ::= b;; {{ }} Z ::= 0;; {{ }} WHILE (X <> 0 /\ Y <> 0) DO {{ }} ->> {{ }} X := X - 1;; {{ }} Y := Y - 1;; {{ }} Z := Z + 1 {{ }} END {{ }} ->> {{ Z = min a b }} *) (** [] *) (** **** Exercise: 3 stars (two_loops) *) (** Here is a very inefficient way of adding 3 numbers: X ::= 0;; Y ::= 0;; Z ::= c;; WHILE X <> a DO X ::= X + 1;; Z ::= Z + 1 END;; WHILE Y <> b DO Y ::= Y + 1;; Z ::= Z + 1 END Show that it does what it should by filling in the blanks in the following decorated program. {{ True }} ->> {{ }} X ::= 0;; {{ }} Y ::= 0;; {{ }} Z ::= c;; {{ }} WHILE X <> a DO {{ }} ->> {{ }} X ::= X + 1;; {{ }} Z ::= Z + 1 {{ }} END;; {{ }} ->> {{ }} WHILE Y <> b DO {{ }} ->> {{ }} Y ::= Y + 1;; {{ }} Z ::= Z + 1 {{ }} END {{ }} ->> {{ Z = a + b + c }} *) (** [] *) (* ================================================================= *) (** ** Exercise: Power Series *) (** **** Exercise: 4 stars, optional (dpow2_down) *) (** Here is a program that computes the series: [1 + 2 + 2^2 + ... + 2^m = 2^(m+1) - 1] X ::= 0;; Y ::= 1;; Z ::= 1;; WHILE X <> m DO Z ::= 2 * Z;; Y ::= Y + Z;; X ::= X + 1 END Write a decorated program for this. *) (* FILL IN HERE *) (* ################################################################# *) (** * Weakest Preconditions (Optional) *) (** Some Hoare triples are more interesting than others. For example, {{ False }} X ::= Y + 1 {{ X <= 5 }} is _not_ very interesting: although it is perfectly valid, it tells us nothing useful. Since the precondition isn't satisfied by any state, it doesn't describe any situations where we can use the command [X ::= Y + 1] to achieve the postcondition [X <= 5]. By contrast, {{ Y <= 4 /\ Z = 0 }} X ::= Y + 1 {{ X <= 5 }} is useful: it tells us that, if we can somehow create a situation in which we know that [Y <= 4 /\ Z = 0], then running this command will produce a state satisfying the postcondition. However, this triple is still not as useful as it could be, because the [Z = 0] clause in the precondition actually has nothing to do with the postcondition [X <= 5]. The _most_ useful triple (for this command and postcondition) is this one: {{ Y <= 4 }} X ::= Y + 1 {{ X <= 5 }} In other words, [Y <= 4] is the _weakest_ valid precondition of the command [X ::= Y + 1] for the postcondition [X <= 5]. *) (** In general, we say that "[P] is the weakest precondition of command [c] for postcondition [Q]" if [{{P}} c {{Q}}] and if, whenever [P'] is an assertion such that [{{P'}} c {{Q}}], it is the case that [P' st] implies [P st] for all states [st]. *) Definition is_wp P c Q := {{P}} c {{Q}} /\ forall P', {{P'}} c {{Q}} -> (P' ->> P). (** That is, [P] is the weakest precondition of [c] for [Q] if (a) [P] _is_ a precondition for [Q] and [c], and (b) [P] is the _weakest_ (easiest to satisfy) assertion that guarantees that [Q] will hold after executing [c]. *) (** **** Exercise: 1 star, optional (wp) *) (** What are the weakest preconditions of the following commands for the following postconditions? 1) {{ ? }} SKIP {{ X = 5 }} 2) {{ ? }} X ::= Y + Z {{ X = 5 }} 3) {{ ? }} X ::= Y {{ X = Y }} 4) {{ ? }} IFB X == 0 THEN Y ::= Z + 1 ELSE Y ::= W + 2 FI {{ Y = 5 }} 5) {{ ? }} X ::= 5 {{ X = 0 }} 6) {{ ? }} WHILE True DO X ::= 0 END {{ X = 0 }} *) (* FILL IN HERE *) (** [] *) (** **** Exercise: 3 stars, advanced, optional (is_wp_formal) *) (** Prove formally, using the definition of [hoare_triple], that [Y <= 4] is indeed the weakest precondition of [X ::= Y + 1] with respect to postcondition [X <= 5]. *) Theorem is_wp_example : is_wp (fun st => st Y <= 4) (X ::= APlus (AId Y) (ANum 1)) (fun st => st X <= 5). Proof. (* FILL IN HERE *) Admitted. (** [] *) (** **** Exercise: 2 stars, advanced, optional (hoare_asgn_weakest) *) (** Show that the precondition in the rule [hoare_asgn] is in fact the weakest precondition. *) Theorem hoare_asgn_weakest : forall Q X a, is_wp (Q [X |-> a]) (X ::= a) Q. Proof. (* FILL IN HERE *) Admitted. (** [] *) (** **** Exercise: 2 stars, advanced, optional (hoare_havoc_weakest) *) (** Show that your [havoc_pre] rule from the [himp_hoare] exercise in the [Hoare] chapter returns the weakest precondition. *) Module Himp2. Import Himp. Lemma hoare_havoc_weakest : forall (P Q : Assertion) (X : id), {{ P }} HAVOC X {{ Q }} -> P ->> havoc_pre X Q. Proof. (* FILL IN HERE *) Admitted. End Himp2. (** [] *) (* ################################################################# *) (** * Formal Decorated Programs (Optional) *) (** Our informal conventions for decorated programs amount to a way of displaying Hoare triples, in which commands are annotated with enough embedded assertions that checking the validity of a triple is reduced to simple logical and algebraic calculations showing that some assertions imply others. In this section, we show that this informal presentation style can actually be made completely formal and indeed that checking the validity of decorated programs can mostly be automated. *) (* ================================================================= *) (** ** Syntax *) (** The first thing we need to do is to formalize a variant of the syntax of commands with embedded assertions. We call the new commands _decorated commands_, or [dcom]s. *) Inductive dcom : Type := | DCSkip : Assertion -> dcom | DCSeq : dcom -> dcom -> dcom | DCAsgn : id -> aexp -> Assertion -> dcom | DCIf : bexp -> Assertion -> dcom -> Assertion -> dcom -> Assertion-> dcom | DCWhile : bexp -> Assertion -> dcom -> Assertion -> dcom | DCPre : Assertion -> dcom -> dcom | DCPost : dcom -> Assertion -> dcom. Notation "'SKIP' {{ P }}" := (DCSkip P) (at level 10) : dcom_scope. Notation "l '::=' a {{ P }}" := (DCAsgn l a P) (at level 60, a at next level) : dcom_scope. Notation "'WHILE' b 'DO' {{ Pbody }} d 'END' {{ Ppost }}" := (DCWhile b Pbody d Ppost) (at level 80, right associativity) : dcom_scope. Notation "'IFB' b 'THEN' {{ P }} d 'ELSE' {{ P' }} d' 'FI' {{ Q }}" := (DCIf b P d P' d' Q) (at level 80, right associativity) : dcom_scope. Notation "'->>' {{ P }} d" := (DCPre P d) (at level 90, right associativity) : dcom_scope. Notation "{{ P }} d" := (DCPre P d) (at level 90) : dcom_scope. Notation "d '->>' {{ P }}" := (DCPost d P) (at level 80, right associativity) : dcom_scope. Notation " d ;; d' " := (DCSeq d d') (at level 80, right associativity) : dcom_scope. Delimit Scope dcom_scope with dcom. (** To avoid clashing with the existing [Notation] definitions for ordinary [com]mands, we introduce these notations in a special scope called [dcom_scope], and we wrap examples with the declaration [% dcom] to signal that we want the notations to be interpreted in this scope. Careful readers will note that we've defined two notations for the [DCPre] constructor, one with and one without a [->>]. The "without" version is intended to be used to supply the initial precondition at the very top of the program. *) Example dec_while : dcom := ( {{ fun st => True }} WHILE (BNot (BEq (AId X) (ANum 0))) DO {{ fun st => True /\ st X <> 0}} X ::= (AMinus (AId X) (ANum 1)) {{ fun _ => True }} END {{ fun st => True /\ st X = 0}} ->> {{ fun st => st X = 0 }} ) % dcom. (** It is easy to go from a [dcom] to a [com] by erasing all annotations. *) Fixpoint extract (d:dcom) : com := match d with | DCSkip _ => SKIP | DCSeq d1 d2 => (extract d1 ;; extract d2) | DCAsgn X a _ => X ::= a | DCIf b _ d1 _ d2 _ => IFB b THEN extract d1 ELSE extract d2 FI | DCWhile b _ d _ => WHILE b DO extract d END | DCPre _ d => extract d | DCPost d _ => extract d end. (** The choice of exactly where to put assertions in the definition of [dcom] is a bit subtle. The simplest thing to do would be to annotate every [dcom] with a precondition and postcondition. But this would result in very verbose programs with a lot of repeated annotations: for example, a program like [SKIP;SKIP] would have to be annotated as {{P}} ({{P}} SKIP {{P}}) ;; ({{P}} SKIP {{P}}) {{P}}, with pre- and post-conditions on each [SKIP], plus identical pre- and post-conditions on the semicolon! Instead, the rule we've followed is this: - The _post_-condition expected by each [dcom] [d] is embedded in [d]. - The _pre_-condition is supplied by the context. *) (** In other words, the invariant of the representation is that a [dcom] [d] together with a precondition [P] determines a Hoare triple [{{P}} (extract d) {{post d}}], where [post] is defined as follows: *) Fixpoint post (d:dcom) : Assertion := match d with | DCSkip P => P | DCSeq d1 d2 => post d2 | DCAsgn X a Q => Q | DCIf _ _ d1 _ d2 Q => Q | DCWhile b Pbody c Ppost => Ppost | DCPre _ d => post d | DCPost c Q => Q end. (** Similarly, we can extract the "initial precondition" from a decorated program. *) Fixpoint pre (d:dcom) : Assertion := match d with | DCSkip P => fun st => True | DCSeq c1 c2 => pre c1 | DCAsgn X a Q => fun st => True | DCIf _ _ t _ e _ => fun st => True | DCWhile b Pbody c Ppost => fun st => True | DCPre P c => P | DCPost c Q => pre c end. (** This function is not doing anything sophisticated like calculating a weakest precondition; it just recursively searches for an explicit annotation at the very beginning of the program, returning default answers for programs that lack an explicit precondition (like a bare assignment or [SKIP]). *) (** Using [pre] and [post], and assuming that we adopt the convention of always supplying an explicit precondition annotation at the very beginning of our decorated programs, we can express what it means for a decorated program to be correct as follows: *) Definition dec_correct (d:dcom) := {{pre d}} (extract d) {{post d}}. (** To check whether this Hoare triple is _valid_, we need a way to extract the "proof obligations" from a decorated program. These obligations are often called _verification conditions_, because they are the facts that must be verified to see that the decorations are logically consistent and thus add up to a complete proof of correctness. *) (* ================================================================= *) (** ** Extracting Verification Conditions *) (** The function [verification_conditions] takes a [dcom] [d] together with a precondition [P] and returns a _proposition_ that, if it can be proved, implies that the triple [{{P}} (extract d) {{post d}}] is valid. *) (** It does this by walking over [d] and generating a big conjunction including all the "local checks" that we listed when we described the informal rules for decorated programs. (Strictly speaking, we need to massage the informal rules a little bit to add some uses of the rule of consequence, but the correspondence should be clear.) *) Fixpoint verification_conditions (P : Assertion) (d:dcom) : Prop := match d with | DCSkip Q => (P ->> Q) | DCSeq d1 d2 => verification_conditions P d1 /\ verification_conditions (post d1) d2 | DCAsgn X a Q => (P ->> Q [X |-> a]) | DCIf b P1 d1 P2 d2 Q => ((fun st => P st /\ bassn b st) ->> P1) /\ ((fun st => P st /\ ~ (bassn b st)) ->> P2) /\ (Q <<->> post d1) /\ (Q <<->> post d2) /\ verification_conditions P1 d1 /\ verification_conditions P2 d2 | DCWhile b Pbody d Ppost => (* post d is the loop invariant and the initial precondition *) (P ->> post d) /\ (Pbody <<->> (fun st => post d st /\ bassn b st)) /\ (Ppost <<->> (fun st => post d st /\ ~(bassn b st))) /\ verification_conditions Pbody d | DCPre P' d => (P ->> P') /\ verification_conditions P' d | DCPost d Q => verification_conditions P d /\ (post d ->> Q) end. (** And now the key theorem, stating that [verification_conditions] does its job correctly. Not surprisingly, we need to use each of the Hoare Logic rules at some point in the proof. *) Theorem verification_correct : forall d P, verification_conditions P d -> {{P}} (extract d) {{post d}}. Proof. induction d; intros P H; simpl in *. - (* Skip *) eapply hoare_consequence_pre. apply hoare_skip. assumption. - (* Seq *) inversion H as [H1 H2]. clear H. eapply hoare_seq. apply IHd2. apply H2. apply IHd1. apply H1. - (* Asgn *) eapply hoare_consequence_pre. apply hoare_asgn. assumption. - (* If *) inversion H as [HPre1 [HPre2 [[Hd11 Hd12] [[Hd21 Hd22] [HThen HElse]]]]]. clear H. apply IHd1 in HThen. clear IHd1. apply IHd2 in HElse. clear IHd2. apply hoare_if. eapply hoare_consequence_pre; eauto. eapply hoare_consequence_post; eauto. eapply hoare_consequence_pre; eauto. eapply hoare_consequence_post; eauto. - (* While *) inversion H as [Hpre [[Hbody1 Hbody2] [[Hpost1 Hpost2] Hd]]]; subst; clear H. eapply hoare_consequence_pre; eauto. eapply hoare_consequence_post; eauto. apply hoare_while. eapply hoare_consequence_pre; eauto. - (* Pre *) inversion H as [HP Hd]; clear H. eapply hoare_consequence_pre. apply IHd. apply Hd. assumption. - (* Post *) inversion H as [Hd HQ]; clear H. eapply hoare_consequence_post. apply IHd. apply Hd. assumption. Qed. (** (If you expand the proof, you'll see that it uses an unfamiliar idiom: [simpl in *]. We have used [...in...] variants of several tactics before, to apply them to values in the context rather than the goal. The syntax [tactic in *] extends this idea, applying [tactic] in the goal and every hypothesis in the context.) *) (* ================================================================= *) (** ** Automation *) (** The propositions generated by [verification_conditions] are fairly big, and they contain many conjuncts that are essentially trivial. *) Eval simpl in (verification_conditions (fun st => True) dec_while). (** ==> (((fun _ : state => True) ->> (fun _ : state => True)) /\ ((fun _ : state => True) ->> (fun _ : state => True)) /\ (fun st : state => True /\ bassn (BNot (BEq (AId X) (ANum 0))) st) = (fun st : state => True /\ bassn (BNot (BEq (AId X) (ANum 0))) st) /\ (fun st : state => True /\ ~ bassn (BNot (BEq (AId X) (ANum 0))) st) = (fun st : state => True /\ ~ bassn (BNot (BEq (AId X) (ANum 0))) st) /\ (fun st : state => True /\ bassn (BNot (BEq (AId X) (ANum 0))) st) ->> (fun _ : state => True) [X |-> AMinus (AId X) (ANum 1)]) /\ (fun st : state => True /\ ~ bassn (BNot (BEq (AId X) (ANum 0))) st) ->> (fun st : state => st X = 0) *) (** In principle, we could work with such propositions using just the tactics we have so far, but we can make things much smoother with a bit of automation. We first define a custom [verify] tactic that uses [split] repeatedly to turn all the conjunctions into separate subgoals and then uses [omega] and [eauto] (a handy general-purpose automation tactic that we'll discuss in detail later) to deal with as many of them as possible. *) Tactic Notation "verify" := apply verification_correct; repeat split; simpl; unfold assert_implies; unfold bassn in *; unfold beval in *; unfold aeval in *; unfold assn_sub; intros; repeat rewrite t_update_eq; repeat (rewrite t_update_neq; [| (intro X; inversion X)]); simpl in *; repeat match goal with [H : _ /\ _ |- _] => destruct H end; repeat rewrite not_true_iff_false in *; repeat rewrite not_false_iff_true in *; repeat rewrite negb_true_iff in *; repeat rewrite negb_false_iff in *; repeat rewrite beq_nat_true_iff in *; repeat rewrite beq_nat_false_iff in *; repeat rewrite leb_iff in *; repeat rewrite leb_iff_conv in *; try subst; repeat match goal with [st : state |- _] => match goal with [H : st _ = _ |- _] => rewrite -> H in *; clear H | [H : _ = st _ |- _] => rewrite <- H in *; clear H end end; try eauto; try omega. (** What's left after [verify] does its thing is "just the interesting parts" of checking that the decorations are correct. For very simple examples [verify] immediately solves the goal (provided that the annotations are correct). *) Theorem dec_while_correct : dec_correct dec_while. Proof. verify. Qed. (** Another example (formalizing a decorated program we've seen before): *) Example subtract_slowly_dec (m:nat) (p:nat) : dcom := ( {{ fun st => st X = m /\ st Z = p }} ->> {{ fun st => st Z - st X = p - m }} WHILE BNot (BEq (AId X) (ANum 0)) DO {{ fun st => st Z - st X = p - m /\ st X <> 0 }} ->> {{ fun st => (st Z - 1) - (st X - 1) = p - m }} Z ::= AMinus (AId Z) (ANum 1) {{ fun st => st Z - (st X - 1) = p - m }} ;; X ::= AMinus (AId X) (ANum 1) {{ fun st => st Z - st X = p - m }} END {{ fun st => st Z - st X = p - m /\ st X = 0 }} ->> {{ fun st => st Z = p - m }} ) % dcom. Theorem subtract_slowly_dec_correct : forall m p, dec_correct (subtract_slowly_dec m p). Proof. intros m p. verify. (* this grinds for a bit! *) Qed. (** **** Exercise: 3 stars, advanced (slow_assignment_dec) *) (** In the [slow_assignment] exercise above, we saw a roundabout way of assigning a number currently stored in [X] to the variable [Y]: start [Y] at [0], then decrement [X] until it hits [0], incrementing [Y] at each step. Write a formal version of this decorated program and prove it correct. *) Example slow_assignment_dec (m:nat) : dcom := (* FILL IN HERE *) admit. Theorem slow_assignment_dec_correct : forall m, dec_correct (slow_assignment_dec m). Proof. (* FILL IN HERE *) Admitted. (** [] *) (** **** Exercise: 4 stars, advanced (factorial_dec) *) (** Remember the factorial function we worked with before: *) Fixpoint real_fact (n:nat) : nat := match n with | O => 1 | S n' => n * (real_fact n') end. (** Following the pattern of [subtract_slowly_dec], write a decorated program [factorial_dec] that implements the factorial function and prove it correct as [factorial_dec_correct]. *) (* FILL IN HERE *) (** [] *) (* ================================================================= *) (** ** Examples *) (** In this section, we use the automation developed above to verify formal decorated programs corresponding to most of the informal ones we have seen. *) (* ----------------------------------------------------------------- *) (** *** Swapping Using Addition and Subtraction *) Definition swap : com := X ::= APlus (AId X) (AId Y);; Y ::= AMinus (AId X) (AId Y);; X ::= AMinus (AId X) (AId Y). Definition swap_dec m n : dcom := ({{ fun st => st X = m /\ st Y = n}} ->> {{ fun st => (st X + st Y) - ((st X + st Y) - st Y) = n /\ (st X + st Y) - st Y = m }} X ::= APlus (AId X) (AId Y) {{ fun st => st X - (st X - st Y) = n /\ st X - st Y = m }};; Y ::= AMinus (AId X) (AId Y) {{ fun st => st X - st Y = n /\ st Y = m }};; X ::= AMinus (AId X) (AId Y) {{ fun st => st X = n /\ st Y = m}})%dcom. Theorem swap_correct : forall m n, dec_correct (swap_dec m n). Proof. intros; verify. Qed. (* ----------------------------------------------------------------- *) (** *** Simple Conditionals *) Definition if_minus_plus_com := IFB (BLe (AId X) (AId Y)) THEN (Z ::= AMinus (AId Y) (AId X)) ELSE (Y ::= APlus (AId X) (AId Z)) FI. Definition if_minus_plus_dec := ({{fun st => True}} IFB (BLe (AId X) (AId Y)) THEN {{ fun st => True /\ st X <= st Y }} ->> {{ fun st => st Y = st X + (st Y - st X) }} Z ::= AMinus (AId Y) (AId X) {{ fun st => st Y = st X + st Z }} ELSE {{ fun st => True /\ ~(st X <= st Y) }} ->> {{ fun st => st X + st Z = st X + st Z }} Y ::= APlus (AId X) (AId Z) {{ fun st => st Y = st X + st Z }} FI {{fun st => st Y = st X + st Z}})%dcom. Theorem if_minus_plus_correct : dec_correct if_minus_plus_dec. Proof. intros; verify. Qed. Definition if_minus_dec := ( {{fun st => True}} IFB (BLe (AId X) (AId Y)) THEN {{fun st => True /\ st X <= st Y }} ->> {{fun st => (st Y - st X) + st X = st Y \/ (st Y - st X) + st Y = st X}} Z ::= AMinus (AId Y) (AId X) {{fun st => st Z + st X = st Y \/ st Z + st Y = st X}} ELSE {{fun st => True /\ ~(st X <= st Y) }} ->> {{fun st => (st X - st Y) + st X = st Y \/ (st X - st Y) + st Y = st X}} Z ::= AMinus (AId X) (AId Y) {{fun st => st Z + st X = st Y \/ st Z + st Y = st X}} FI {{fun st => st Z + st X = st Y \/ st Z + st Y = st X}})%dcom. Theorem if_minus_correct : dec_correct if_minus_dec. Proof. verify. Qed. (* ----------------------------------------------------------------- *) (** *** Division *) Definition div_mod_dec (a b : nat) : dcom := ( {{ fun st => True }} ->> {{ fun st => b * 0 + a = a }} X ::= ANum a {{ fun st => b * 0 + st X = a }};; Y ::= ANum 0 {{ fun st => b * st Y + st X = a }};; WHILE (BLe (ANum b) (AId X)) DO {{ fun st => b * st Y + st X = a /\ b <= st X }} ->> {{ fun st => b * (st Y + 1) + (st X - b) = a }} X ::= AMinus (AId X) (ANum b) {{ fun st => b * (st Y + 1) + st X = a }};; Y ::= APlus (AId Y) (ANum 1) {{ fun st => b * st Y + st X = a }} END {{ fun st => b * st Y + st X = a /\ ~(b <= st X) }} ->> {{ fun st => b * st Y + st X = a /\ (st X < b) }} )%dcom. Theorem div_mod_dec_correct : forall a b, dec_correct (div_mod_dec a b). Proof. intros a b. verify. rewrite mult_plus_distr_l. omega. Qed. (* ----------------------------------------------------------------- *) (** *** Parity *) Definition find_parity : com := WHILE (BLe (ANum 2) (AId X)) DO X ::= AMinus (AId X) (ANum 2) END. (** There are actually several ways to phrase the loop invariant for this program. Here is one natural one, which leads to a rather long proof: *) Inductive ev : nat -> Prop := | ev_0 : ev O | ev_SS : forall n:nat, ev n -> ev (S (S n)). Definition find_parity_dec m : dcom := ({{ fun st => st X = m}} ->> {{ fun st => st X <= m /\ ev (m - st X) }} WHILE (BLe (ANum 2) (AId X)) DO {{ fun st => (st X <= m /\ ev (m - st X)) /\ 2 <= st X }} ->> {{ fun st => st X - 2 <= m /\ (ev (m - (st X - 2))) }} X ::= AMinus (AId X) (ANum 2) {{ fun st => st X <= m /\ ev (m - st X) }} END {{ fun st => (st X <= m /\ ev (m - st X)) /\ st X < 2 }} ->> {{ fun st => st X=0 <-> ev m }})%dcom. Lemma l1 : forall m n p, p <= n -> n <= m -> m - (n - p) = m - n + p. Proof. intros. omega. Qed. Lemma l2 : forall m, ev m -> ev (m + 2). Proof. intros. rewrite plus_comm. simpl. constructor. assumption. Qed. Lemma l3' : forall m, ev m -> ~ev (S m). Proof. induction m; intros H1 H2. inversion H2. apply IHm. inversion H2; subst; assumption. assumption. Qed. Lemma l3 : forall m, 1 <= m -> ev m -> ev (m - 1) -> False. Proof. intros. apply l2 in H1. assert (G : m - 1 + 2 = S m). clear H0 H1. omega. rewrite G in H1. apply l3' in H0. apply H0. assumption. Qed. Theorem find_parity_correct : forall m, dec_correct (find_parity_dec m). Proof. intro m. verify; (* simplification too aggressive ... reverting a bit *) fold (leb 2 (st X)) in *; try rewrite leb_iff in *; try rewrite leb_iff_conv in *; eauto; try omega. - (* invariant holds initially *) rewrite minus_diag. constructor. - (* invariant preserved *) rewrite l1; try assumption. apply l2; assumption. - (* invariant strong enough to imply conclusion (-> direction) *) rewrite <- minus_n_O in H2. assumption. - (* invariant strong enough to imply conclusion (<- direction) *) destruct (st X) as [| [| n]]. (* by H1 X can only be 0 or 1 *) + (* st X = 0 *) reflexivity. + (* st X = 1 *) apply l3 in H; try assumption. inversion H. + (* st X = 2 *) clear H0 H2. (* omega confused otherwise *) omega. Qed. (** Here is a more intuitive way of writing the invariant: *) Definition find_parity_dec' m : dcom := ({{ fun st => st X = m}} ->> {{ fun st => ev (st X) <-> ev m }} WHILE (BLe (ANum 2) (AId X)) DO {{ fun st => (ev (st X) <-> ev m) /\ 2 <= st X }} ->> {{ fun st => (ev (st X - 2) <-> ev m) }} X ::= AMinus (AId X) (ANum 2) {{ fun st => (ev (st X) <-> ev m) }} END {{ fun st => (ev (st X) <-> ev m) /\ ~(2 <= st X) }} ->> {{ fun st => st X=0 <-> ev m }})%dcom. Lemma l4 : forall m, 2 <= m -> (ev (m - 2) <-> ev m). Proof. induction m; intros. split; intro; constructor. destruct m. inversion H. inversion H1. simpl in *. rewrite <- minus_n_O in *. split; intro. constructor. assumption. inversion H0. assumption. Qed. Theorem find_parity_correct' : forall m, dec_correct (find_parity_dec' m). Proof. intros m. verify; (* simplification too aggressive ... reverting a bit *) fold (leb 2 (st X)) in *; try rewrite leb_iff in *; try rewrite leb_iff_conv in *; intuition; eauto; try omega. - (* invariant preserved (part 1) *) rewrite l4 in H0; eauto. - (* invariant preserved (part 2) *) rewrite l4; eauto. - (* invariant strong enough to imply conclusion (-> direction) *) apply H0. constructor. - (* invariant strong enough to imply conclusion (<- direction) *) destruct (st X) as [| [| n]]. (* by H1 X can only be 0 or 1 *) + (* st X = 0 *) reflexivity. + (* st X = 1 *) inversion H. + (* st X = 2 *) clear H0 H H3. (* omega confused otherwise *) omega. Qed. (** Here is the simplest invariant we've found for this program: *) Definition parity_dec m : dcom := ({{ fun st => st X = m}} ->> {{ fun st => parity (st X) = parity m }} WHILE (BLe (ANum 2) (AId X)) DO {{ fun st => parity (st X) = parity m /\ 2 <= st X }} ->> {{ fun st => parity (st X - 2) = parity m }} X ::= AMinus (AId X) (ANum 2) {{ fun st => parity (st X) = parity m }} END {{ fun st => parity (st X) = parity m /\ ~(2 <= st X) }} ->> {{ fun st => st X = parity m }})%dcom. Theorem parity_dec_correct : forall m, dec_correct (parity_dec m). Proof. intros. verify; (* simplification too aggressive ... reverting a bit *) fold (leb 2 (st X)) in *; try rewrite leb_iff in *; try rewrite leb_iff_conv in *; eauto; try omega. - (* invariant preserved *) rewrite <- H. apply parity_ge_2. assumption. - (* invariant strong enough *) rewrite <- H. symmetry. apply parity_lt_2. assumption. Qed. (* ----------------------------------------------------------------- *) (** *** Square Roots *) Definition sqrt_dec m : dcom := ( {{ fun st => st X = m }} ->> {{ fun st => st X = m /\ 0*0 <= m }} Z ::= ANum 0 {{ fun st => st X = m /\ st Z*st Z <= m }};; WHILE BLe (AMult (APlus (AId Z) (ANum 1)) (APlus (AId Z) (ANum 1))) (AId X) DO {{ fun st => (st X = m /\ st Z*st Z<=m) /\ (st Z + 1)*(st Z + 1) <= st X }} ->> {{ fun st => st X = m /\ (st Z+1)*(st Z+1)<=m }} Z ::= APlus (AId Z) (ANum 1) {{ fun st => st X = m /\ st Z*st Z<=m }} END {{ fun st => (st X = m /\ st Z*st Z<=m) /\ ~((st Z + 1)*(st Z + 1) <= st X) }} ->> {{ fun st => st Z*st Z<=m /\ m<(st Z+1)*(st Z+1) }})%dcom. Theorem sqrt_correct : forall m, dec_correct (sqrt_dec m). Proof. intro m. verify. Qed. (* ----------------------------------------------------------------- *) (** *** Squaring *) (** Again, there are several ways of annotating the squaring program. The simplest variant we've found, [square_simpler_dec], is given last. *) Definition square_dec (m : nat) : dcom := ( {{ fun st => st X = m }} Y ::= AId X {{ fun st => st X = m /\ st Y = m }};; Z ::= ANum 0 {{ fun st => st X = m /\ st Y = m /\ st Z = 0}};; {{ fun st => st Z + st X * st Y = m * m }} WHILE BNot (BEq (AId Y) (ANum 0)) DO {{ fun st => st Z + st X * st Y = m * m /\ st Y <> 0 }} ->> {{ fun st => (st Z + st X) + st X * (st Y - 1) = m * m }} Z ::= APlus (AId Z) (AId X) {{ fun st => st Z + st X * (st Y - 1) = m * m }};; Y ::= AMinus (AId Y) (ANum 1) {{ fun st => st Z + st X * st Y = m * m }} END {{ fun st => st Z + st X * st Y = m * m /\ st Y = 0 }} ->> {{ fun st => st Z = m * m }} )%dcom. Theorem square_dec_correct : forall m, dec_correct (square_dec m). Proof. intro n. verify. - (* invariant preserved *) destruct (st Y) as [| y']. apply False_ind. apply H0. reflexivity. simpl. rewrite <- minus_n_O. assert (G : forall n m, n * S m = n + n * m). { clear. intros. induction n. reflexivity. simpl. rewrite IHn. omega. } rewrite <- H. rewrite G. rewrite plus_assoc. reflexivity. Qed. Definition square_dec' (n : nat) : dcom := ( {{ fun st => True }} X ::= ANum n {{ fun st => st X = n }};; Y ::= AId X {{ fun st => st X = n /\ st Y = n }};; Z ::= ANum 0 {{ fun st => st X = n /\ st Y = n /\ st Z = 0 }};; {{ fun st => st Z = st X * (st X - st Y) /\ st X = n /\ st Y <= st X }} WHILE BNot (BEq (AId Y) (ANum 0)) DO {{ fun st => (st Z = st X * (st X - st Y) /\ st X = n /\ st Y <= st X) /\ st Y <> 0 }} Z ::= APlus (AId Z) (AId X) {{ fun st => st Z = st X * (st X - (st Y - 1)) /\ st X = n /\ st Y <= st X }};; Y ::= AMinus (AId Y) (ANum 1) {{ fun st => st Z = st X * (st X - st Y) /\ st X = n /\ st Y <= st X }} END {{ fun st => (st Z = st X * (st X - st Y) /\ st X = n /\ st Y <= st X) /\ st Y = 0 }} ->> {{ fun st => st Z = n * n }} )%dcom. Theorem square_dec'_correct : forall n, dec_correct (square_dec' n). Proof. intro n. verify. - (* invariant holds initially *) rewrite minus_diag. omega. - (* invariant preserved *) subst. rewrite mult_minus_distr_l. repeat rewrite mult_minus_distr_l. rewrite mult_1_r. assert (G : forall n m p, m <= n -> p <= m -> n - (m - p) = n - m + p). intros. omega. rewrite G. reflexivity. apply mult_le_compat_l. assumption. destruct (st Y). apply False_ind. apply H0. reflexivity. clear. rewrite mult_succ_r. rewrite plus_comm. apply le_plus_l. - (* invarint + negation of guard imply desired postcondition *) rewrite <- minus_n_O. reflexivity. Qed. Definition square_simpler_dec (m : nat) : dcom := ( {{ fun st => st X = m }} ->> {{ fun st => 0 = 0*m /\ st X = m }} Y ::= ANum 0 {{ fun st => 0 = (st Y)*m /\ st X = m }};; Z ::= ANum 0 {{ fun st => st Z = (st Y)*m /\ st X = m }};; {{ fun st => st Z = (st Y)*m /\ st X = m }} WHILE BNot (BEq (AId Y) (AId X)) DO {{ fun st => (st Z = (st Y)*m /\ st X = m) /\ st Y <> st X }} ->> {{ fun st => st Z + st X = ((st Y) + 1)*m /\ st X = m }} Z ::= APlus (AId Z) (AId X) {{ fun st => st Z = ((st Y) + 1)*m /\ st X = m }};; Y ::= APlus (AId Y) (ANum 1) {{ fun st => st Z = (st Y)*m /\ st X = m }} END {{ fun st => (st Z = (st Y)*m /\ st X = m) /\ st Y = st X }} ->> {{ fun st => st Z = m*m }} )%dcom. Theorem square_simpler_dec_correct : forall m, dec_correct (square_simpler_dec m). Proof. intro m. verify. rewrite mult_plus_distr_r. simpl. rewrite <- plus_n_O. reflexivity. Qed. (* ----------------------------------------------------------------- *) (** *** Two loops *) Definition two_loops_dec (a b c : nat) := ( {{ fun st => True }} ->> {{ fun st => c = 0 + c /\ 0 = 0 }} X ::= ANum 0 {{ fun st => c = st X + c /\ 0 = 0 }};; Y ::= ANum 0 {{ fun st => c = st X + c /\ st Y = 0 }};; Z ::= ANum c {{ fun st => st Z = st X + c /\ st Y = 0 }};; WHILE BNot (BEq (AId X) (ANum a)) DO {{ fun st => (st Z = st X + c /\ st Y = 0) /\ st X <> a }} ->> {{ fun st => st Z + 1 = st X + 1 + c /\ st Y = 0 }} X ::= APlus (AId X) (ANum 1) {{ fun st => st Z + 1 = st X + c /\ st Y = 0 }};; Z ::= APlus (AId Z) (ANum 1) {{ fun st => st Z = st X + c /\ st Y = 0 }} END {{ fun st => (st Z = st X + c /\ st Y = 0) /\ st X = a }} ->> {{ fun st => st Z = a + st Y + c }};; WHILE BNot (BEq (AId Y) (ANum b)) DO {{ fun st => st Z = a + st Y + c /\ st Y <> b }} ->> {{ fun st => st Z + 1 = a + st Y + 1 + c }} Y ::= APlus (AId Y) (ANum 1) {{ fun st => st Z + 1 = a + st Y + c }};; Z ::= APlus (AId Z) (ANum 1) {{ fun st => st Z = a + st Y + c }} END {{ fun st => (st Z = a + st Y + c) /\ st Y = b }} ->> {{ fun st => st Z = a + b + c }} )%dcom. Theorem two_loops_correct : forall a b c, dec_correct (two_loops_dec a b c). Proof. intros a b c. verify. Qed. (* ----------------------------------------------------------------- *) (** *** Power series *) Fixpoint pow2 n := match n with | 0 => 1 | S n' => 2 * (pow2 n') end. Definition dpow2_down n := ( {{ fun st => True }} ->> {{ fun st => 1 = (pow2 (0 + 1))-1 /\ 1 = pow2 0 }} X ::= ANum 0 {{ fun st => 1 = (pow2 (0 + 1))-1 /\ 1 = pow2 (st X) }};; Y ::= ANum 1 {{ fun st => st Y = (pow2 (st X + 1))-1 /\ 1 = pow2 (st X) }};; Z ::= ANum 1 {{ fun st => st Y = (pow2 (st X + 1))-1 /\ st Z = pow2 (st X) }};; WHILE BNot (BEq (AId X) (ANum n)) DO {{ fun st => (st Y = (pow2 (st X + 1))-1 /\ st Z = pow2 (st X)) /\ st X <> n }} ->> {{ fun st => st Y + 2 * st Z = (pow2 (st X + 2))-1 /\ 2 * st Z = pow2 (st X + 1) }} Z ::= AMult (ANum 2) (AId Z) {{ fun st => st Y + st Z = (pow2 (st X + 2))-1 /\ st Z = pow2 (st X + 1) }};; Y ::= APlus (AId Y) (AId Z) {{ fun st => st Y = (pow2 (st X + 2))-1 /\ st Z = pow2 (st X + 1) }};; X ::= APlus (AId X) (ANum 1) {{ fun st => st Y = (pow2 (st X + 1))-1 /\ st Z = pow2 (st X) }} END {{ fun st => (st Y = (pow2 (st X + 1))-1 /\ st Z = pow2 (st X)) /\ st X = n }} ->> {{ fun st => st Y = pow2 (n+1) - 1 }} )%dcom. Lemma pow2_plus_1 : forall n, pow2 (n+1) = pow2 n + pow2 n. Proof. induction n; simpl. reflexivity. omega. Qed. Lemma pow2_le_1 : forall n, pow2 n >= 1. Proof. induction n. simpl. constructor. simpl. omega. Qed. Theorem dpow2_down_correct : forall n, dec_correct (dpow2_down n). Proof. intro m. verify. - (* 1 *) rewrite pow2_plus_1. rewrite <- H0. reflexivity. - (* 2 *) rewrite <- plus_n_O. rewrite <- pow2_plus_1. remember (st X) as n. replace (pow2 (n + 1) - 1 + pow2 (n + 1)) with (pow2 (n + 1) + pow2 (n + 1) - 1) by omega. rewrite <- pow2_plus_1. replace (n + 1 + 1) with (n + 2) by omega. reflexivity. - (* 3 *) rewrite <- plus_n_O. rewrite <- pow2_plus_1. reflexivity. - (* 4 *) replace (st X + 1 + 1) with (st X + 2) by omega. reflexivity. Qed. (** $Date: 2016-05-26 16:17:19 -0400 (Thu, 26 May 2016) $ *)
make_fgl_Lazard := proc(d) global a,m,ma,am; local T,u,x,y,q,i,k,Fm,sol; T := table(); T["degree"] := d; Order := d+2; T["log_m"] := unapply(x + add(m[i]*x^(i+1),i=1..d-1),x); T["exp_m"] := unapply( convert( solve(x = series(T["log_m"](y) + sin(y)^(d+1),y=0,d+1),y), polynom,x ), x ); T["sum_m"] := unapply( subs(u=1,expand(convert(series(T["exp_m"](T["log_m"](u*x)+T["log_m"](u*y)),u=0,d+1),polynom,u))), x,y ): Fm := T["sum_m"](x,y); am[1] := m[1]; for k from 2 to d-1 do q := igcd_alt([seq(binomial(k+1,i),i=1..k)])[2]; am[k] := -add(q[i]*coeff(coeff(Fm,x,i),y,k+1-i),i=1..k); od: sol := solve({seq(a[i]=am[i],i=1..d-1)},{seq(m[i],i=1..d-1)}): for i from 1 to d-1 do ma[i] := subs(sol,m[i]); od: T["log_a"] := unapply(collect(expand(eval(subs(m = ma,T["log_m"](x)))),x),x); T["exp_a"] := unapply(collect(expand(eval(subs(m = ma,T["exp_m"](x)))),x),x); T["sum_a"] := unapply(collect(expand(eval(subs(m = ma,T["sum_m"](x,y)))),{x,y}),x,y); return eval(T); end:
Require Import CompCert.Events. Require Import CompCert.Smallstep. Require Import CompCert.Behaviors. Require Import Common.Definitions. Require Import Common.Util. Require Import Common.Linking. Require Import Common.Memory. Require Import Common.Traces. Require Import Common.CompCertExtensions. Require Import Intermediate.Machine. Require Import Intermediate.GlobalEnv. Require Import Lib.Extra. Require Import Lib.Monads. Require Import Intermediate.CS. Import CS. From mathcomp Require ssreflect ssrfun ssrbool eqtype. Set Bullet Behavior "Strict Subproofs". Module CS. Import Intermediate. (* A similar result is used above. Here is a weaker formulation. *) Lemma initial_state_stack_state0 p s : initial_state p s -> stack_state_of s = Traces.stack_state0. Proof. intros Hini. unfold initial_state, initial_machine_state in Hini. destruct (prog_main p) as [mainP |]; simpl in Hini. - destruct (prepare_procedures p (prepare_initial_memory p)) as [[mem dummy] entrypoints]. destruct (EntryPoint.get Component.main mainP entrypoints). + subst. reflexivity. + subst. reflexivity. - subst. reflexivity. Qed. Lemma comes_from_initial_state_mergeable_sym : forall s iface1 iface2, Linking.mergeable_interfaces iface1 iface2 -> comes_from_initial_state s (unionm iface1 iface2) -> comes_from_initial_state s (unionm iface2 iface1). Proof. intros s iface1 iface2 [[_ Hdisjoint] _] Hfrom_initial. rewrite <- (unionmC Hdisjoint). exact Hfrom_initial. Qed. (* RB: NOTE: Consider possible alternatives on [CS.comes_from_initial_state] complemented instead by, say, [PS.step] based on what we usually have in the context, making for more direct routes. *) Lemma comes_from_initial_state_step_trans p s t s' : CS.comes_from_initial_state s (prog_interface p) -> CS.step (prepare_global_env p) s t s' -> CS.comes_from_initial_state s' (prog_interface p). Admitted. (* Grade 2. *) (* RB: TODO: These domain lemmas should now be renamed to reflect their operation on linked programs. *) Section ProgramLink. Variables p c : program. Hypothesis Hwfp : well_formed_program p. Hypothesis Hwfc : well_formed_program c. Hypothesis Hmergeable_ifaces : mergeable_interfaces (prog_interface p) (prog_interface c). Hypothesis Hprog_is_closed : closed_program (program_link p c). Import ssreflect. (* RB: NOTE: Check with existing results (though currently unused). *) Lemma star_stack_cons_domm {s frame gps mem regs pc t} : initial_state (program_link p c) s -> Star (sem (program_link p c)) s t (frame :: gps, mem, regs, pc) -> Pointer.component frame \in domm (prog_interface p) \/ Pointer.component frame \in domm (prog_interface c). Proof. intros Hini Hstar. assert (H : Pointer.component frame \in domm (prog_interface (program_link p c))). { eapply CS.comes_from_initial_state_stack_cons_domm. destruct (cprog_main_existence Hprog_is_closed) as [i [_ [? _]]]. exists (program_link p c), i, s, t. split; first (destruct Hmergeable_ifaces; now apply linking_well_formedness). repeat split; eauto. } move: H. simpl. rewrite domm_union. now apply /fsetUP. Qed. End ProgramLink. End CS.
(* Copyright (C) 2017 M.A.L. Marques This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. *) (* type: work_gga_x *) a1 := 199.81: a2 := 4.3476: c1 := 0.8524: c2 := 1.2264: # This is Eq. (40) of the paper. f0 := s -> c1*(1 - exp(-a1*s^2)) + c2*(1 - exp(-a2*s^4)): f := x -> f0(X2S*x):
{-# OPTIONS --cubical --safe #-} open import Cubical.Core.Everything open import Cubical.Foundations.Everything open import Agda.Primitive using (lzero) module Cubical.Data.DescendingList.Strict.Properties (A : Type₀) (_>_ : A → A → Type₀) where open import Cubical.Data.DescendingList.Strict A _>_ open import Cubical.HITs.ListedFiniteSet renaming (_∈_ to _∈ʰ_) import Cubical.Data.Empty as Empty open Empty using (⊥-elim) open import Cubical.Relation.Nullary.DecidableEq open import Cubical.Relation.Nullary using (Dec; Discrete) renaming (¬_ to Type¬_) unsort : SDL → LFSet A unsort [] = [] unsort (cons x xs x>xs) = x ∷ unsort xs module _ where open import Cubical.Relation.Nullary data Tri (A B C : Set) : Set where tri-< : A → ¬ B → ¬ C → Tri A B C tri-≡ : ¬ A → B → ¬ C → Tri A B C tri-> : ¬ A → ¬ B → C → Tri A B C module IsoToLFSet (A-discrete : Discrete A) (>-isProp : ∀ {x y} → isProp (x > y)) (tri : ∀ x y → Tri (y > x) (x ≡ y) (x > y)) (>-trans : ∀ {x y z} → x > y → y > z → x > z) (>-irreflexive : ∀ {x} → Type¬ x > x) where Tri' : A → A → Set Tri' x y = Tri (y > x) (x ≡ y) (x > y) open import Cubical.Foundations.Logic open import Cubical.HITs.PropositionalTruncation -- Membership is defined via `LFSet`. -- This computes just as well as a direct inductive definition, -- and additionally lets us use the extra `comm` and `dup` paths to prove -- things about membership. _∈ˡ_ : A → SDL → hProp lzero a ∈ˡ l = a ∈ʰ unsort l Memˡ : SDL → A → hProp lzero Memˡ l a = a ∈ˡ l Memʰ : LFSet A → A → hProp lzero Memʰ l a = a ∈ʰ l >ᴴ-trans : ∀ x y zs → x > y → y >ᴴ zs → x >ᴴ zs >ᴴ-trans x y [] x>y y>zs = >ᴴ[] >ᴴ-trans x y (cons z zs _) x>y (>ᴴcons y>z) = >ᴴcons (>-trans x>y y>z) ≡ₚ-sym : ∀ {A : Set} {x y : A} → [ x ≡ₚ y ] → [ y ≡ₚ x ] ≡ₚ-sym p = recPropTrunc squash (λ p → ∣ sym p ∣) p >-all : ∀ x l → x >ᴴ l → ∀ a → [ a ∈ˡ l ] → x > a >-all x (cons y zs y>zs) (>ᴴcons x>y) a a∈l = ⊔-elim (a ≡ₚ y) (a ∈ˡ zs) (λ _ → (x > a) , >-isProp {x} {a}) (λ a≡ₚy → substₚ (λ q → x > q , >-isProp) (≡ₚ-sym a≡ₚy) x>y) (λ a∈zs → >-all x zs (>ᴴ-trans x y zs x>y y>zs) a a∈zs) a∈l >-absent : ∀ x l → x >ᴴ l → [ ¬ (x ∈ˡ l) ] >-absent x l x>l x∈l = ⊥-elim (>-irreflexive (>-all x l x>l x x∈l)) >ᴴ-isProp : ∀ x xs → isProp (x >ᴴ xs) >ᴴ-isProp x _ >ᴴ[] >ᴴ[] = refl >ᴴ-isProp x _ (>ᴴcons p) (>ᴴcons q) = cong >ᴴcons (>-isProp p q) SDL-isSet : isSet SDL SDL-isSet = isSetDL.isSetDL A _>_ >-isProp A-discrete where open import Cubical.Data.DescendingList.Properties insert : A → SDL → SDL >ᴴinsert : {x y : A} {u : SDL} → y >ᴴ u → (y > x) → y >ᴴ insert x u insert x [] = cons x [] >ᴴ[] insert x (cons y zs good) with tri x y insert x (cons y zs good) | tri-< x<y _ _ = cons y (insert x zs) (>ᴴinsert good x<y) insert x (cons y zs good) | tri-≡ _ x≡y _ = cons y zs good insert x (cons y zs good) | tri-> _ _ x>y = cons x (cons y zs good) (>ᴴcons x>y) >ᴴinsert >ᴴ[] y>x = >ᴴcons y>x >ᴴinsert {x} (>ᴴcons {y} y>ys) y>x with tri x y >ᴴinsert {x} {y} (>ᴴcons {z} z>zs) y>x | tri-< _ _ e = >ᴴcons z>zs >ᴴinsert {x} (>ᴴcons {y} y>ys) y>x | tri-≡ _ _ e = >ᴴcons y>ys >ᴴinsert {x} (>ᴴcons {y} y>ys) y>x | tri-> _ _ _ = >ᴴcons y>x insert-correct : ∀ x ys → unsort (insert x ys) ≡ (x ∷ unsort ys) insert-correct x [] = refl insert-correct x (cons y zs y>zs) with tri x y ... | tri-< _ _ _ = y ∷ unsort (insert x zs) ≡⟨ (λ i → y ∷ (insert-correct x zs i)) ⟩ y ∷ x ∷ unsort zs ≡⟨ comm _ _ _ ⟩ x ∷ y ∷ unsort zs ∎ ... | tri-≡ _ x≡y _ = sym (dup y (unsort zs)) ∙ (λ i → (x≡y (~ i)) ∷ y ∷ unsort zs) ... | tri-> _ _ _ = refl insert-correct₂ : ∀ x y zs → unsort (insert x (insert y zs)) ≡ (x ∷ y ∷ unsort zs) insert-correct₂ x y zs = insert-correct x (insert y zs) ∙ cong (λ q → x ∷ q) (insert-correct y zs) abstract -- for some reason, making [exclude] non-abstract makes -- typechecking noticeably slower exclude : A → (A → hProp lzero) → (A → hProp lzero) exclude x h a = ¬ a ≡ₚ x ⊓ h a >-excluded : ∀ x xs → x >ᴴ xs → exclude x (Memʰ (x ∷ unsort xs)) ≡ Memˡ xs >-excluded x xs x>xs = funExt (λ a → ⇔toPath (to a) (from a)) where import Cubical.Data.Prod as D import Cubical.Data.Sum as D from : ∀ a → [ a ∈ˡ xs ] → [ ¬ a ≡ₚ x ⊓ (a ≡ₚ x ⊔ a ∈ˡ xs) ] from a a∈xs = (recPropTrunc (snd ⊥) a≢x) D., inr a∈xs where a≢x : Type¬ (a ≡ x) a≢x = λ a≡x → (>-absent x xs x>xs (transport (λ i → [ a≡x i ∈ˡ xs ]) a∈xs )) to : ∀ a → [ ¬ a ≡ₚ x ⊓ (a ≡ₚ x ⊔ a ∈ˡ xs) ] → [ a ∈ˡ xs ] to a (a≢x D., x) = recPropTrunc (snd (a ∈ˡ xs)) (λ { (D.inl a≡x) → ⊥-elim (a≢x a≡x); (D.inr x) → x }) x cons-eq : ∀ x xs x>xs y ys y>ys → x ≡ y → xs ≡ ys → cons x xs x>xs ≡ cons y ys y>ys cons-eq x xs x>xs y ys y>ys x≡y xs≡ys i = cons (x≡y i) (xs≡ys i) (>ᴴ-isProp (x≡y i) (xs≡ys i) (transp (λ j → (x≡y (i ∧ j)) >ᴴ (xs≡ys) (i ∧ j)) (~ i) x>xs) (transp (λ j → (x≡y (i ∨ ~ j)) >ᴴ (xs≡ys) (i ∨ ~ j)) i y>ys) i) Memˡ-inj-cons : ∀ x xs x>xs y ys y>ys → x ≡ y → Memˡ (cons x xs x>xs) ≡ Memˡ (cons y ys y>ys) → Memˡ xs ≡ Memˡ ys Memˡ-inj-cons x xs x>xs y ys y>ys x≡y e = Memˡ xs ≡⟨ sym (>-excluded x xs x>xs) ⟩ exclude x (Memʰ (x ∷ unsort xs)) ≡⟨ (λ i → exclude (x≡y i) (e i)) ⟩ exclude y (Memʰ (y ∷ unsort ys)) ≡⟨ (>-excluded y ys y>ys) ⟩ Memˡ ys ∎ Memˡ-inj : ∀ l₁ l₂ → Memˡ l₁ ≡ Memˡ l₂ → l₁ ≡ l₂ Memˡ-inj [] [] eq = refl Memˡ-inj [] (cons y ys y>ys) eq = ⊥-elim (transport (λ i → [ eq (~ i) y ]) (inl ∣ refl ∣)) Memˡ-inj (cons y ys y>ys) [] eq = ⊥-elim (transport (λ i → [ eq i y ]) (inl ∣ refl ∣)) Memˡ-inj (cons x xs x>xs) (cons y ys y>ys) e = ⊔-elim (x ≡ₚ y) (x ∈ʰ unsort ys) (λ _ → ((cons x xs x>xs) ≡ (cons y ys y>ys)) , SDL-isSet _ _) (recPropTrunc (SDL-isSet _ _) with-x≡y) (⊥-elim ∘ x∉ys) (transport (λ i → [ e i x ]) (inl ∣ refl ∣)) where xxs = cons x xs x>xs x∉ys : [ ¬ x ∈ˡ ys ] x∉ys x∈ys = ⊥-elim (>-irreflexive y>y) where y>x : y > x y>x = (>-all y ys y>ys x x∈ys) y∈xxs : [ y ∈ˡ (cons x xs x>xs) ] y∈xxs = (transport (λ i → [ e (~ i) y ]) (inl ∣ refl ∣)) y>y : y > y y>y = >-all y xxs (>ᴴcons y>x) y y∈xxs with-x≡y : x ≡ y → (cons x xs x>xs) ≡ (cons y ys y>ys) with-x≡y x≡y = cons-eq x xs x>xs y ys y>ys x≡y r where r : xs ≡ ys r = Memˡ-inj _ _ (Memˡ-inj-cons x xs x>xs y ys y>ys x≡y e) unsort-inj : ∀ x y → unsort x ≡ unsort y → x ≡ y unsort-inj x y e = Memˡ-inj x y λ i a → a ∈ʰ (e i) insert-swap : (x y : A) (zs : SDL) → insert x (insert y zs) ≡ insert y (insert x zs) insert-swap x y zs = unsort-inj (insert x (insert y zs)) (insert y (insert x zs)) (unsort (insert x (insert y zs)) ≡⟨ (λ i → insert-correct₂ x y zs i) ⟩ x ∷ y ∷ unsort zs ≡⟨ (λ i → comm x y (unsort zs) i) ⟩ y ∷ x ∷ unsort zs ≡⟨ (λ i → insert-correct₂ y x zs (~ i)) ⟩ unsort (insert y (insert x zs)) ∎) insert-dup : (x : A) (ys : SDL) → insert x (insert x ys) ≡ insert x ys insert-dup x ys = unsort-inj (insert x (insert x ys)) (insert x ys) ( unsort (insert x (insert x ys)) ≡⟨ (λ i → insert-correct₂ x x ys i) ⟩ x ∷ x ∷ unsort ys ≡⟨ dup x (unsort ys) ⟩ x ∷ unsort ys ≡⟨ (λ i → insert-correct x ys (~ i)) ⟩ unsort (insert x ys) ∎ ) sort : LFSet A → SDL sort = LFSetRec.f [] insert insert-swap insert-dup SDL-isSet unsort∘sort : ∀ x → unsort (sort x) ≡ x unsort∘sort = LFPropElim.f (λ x → unsort (sort x) ≡ x) refl (λ x {ys} ys-hyp → insert-correct x (sort ys) ∙ cong (λ q → x ∷ q) ys-hyp) (λ xs → trunc (unsort (sort xs)) xs) sort∘unsort : ∀ x → sort (unsort x) ≡ x sort∘unsort x = unsort-inj (sort (unsort x)) x (unsort∘sort (unsort x)) SDL-LFSet-iso : Iso SDL (LFSet A) SDL-LFSet-iso = (iso unsort sort unsort∘sort sort∘unsort) SDL≡LFSet : SDL ≡ LFSet A SDL≡LFSet = ua (isoToEquiv SDL-LFSet-iso)