🦆

Lean 入門 (7)

に公開

Lean 入門 (6) の続きです。Theorem Proving in Lean 4 を写経しつつ読みます。

9. Structures and Records

こんな感じで、コンストラクタやアクセサを定義出来ます。mk 以外のキーワードでもコンストラクタは作れるので、DSL ぽい使い方もできたりするかな?

そして継承も出来ます。

structure Point (α : Type u) where
  mk ::
  x : α
  y : α

#eval Point.x (Point.mk 10 20)

structure ColorPoint (α : Type u) extends Point α where
  c : Color

10. Type Classes

関数型言語という意味ではこちらの型クラスの方が重要です。型クラスは静的型付け言語でダックタイピング的なことをする仕組みです。

ダックタイピングとは、ダックタイピングは、主にPythonやRubyなどの動的型付け言語で使われるスタイルです。「アヒルのように歩き、アヒルのように鳴くなら、それはアヒルだ」というアナロジーで、オブジェクトの実際の型ではなく、持っているメソッドや属性で判断します。

def quack(animal):
    animal.quack()  # quackメソッドがあればOK、型は問わない

quack(Duck())    # OK
quack(Goose())   # GooseにquackがあればOK(型が違うけど)

Lean でも、例えば add : α → α → α と、型 α に何らかの加法が定義されていれば、それを用いて共通機能を実装したくなります。

class Add (α : Type) where  -- Add クラスのインスタンスは add を持つ
  add : α → α → α

instance : Add Nat where  -- Nat は Nat.add に関して、Add クラス
  add := Nat.add

def double [Add α] (x : α) : α :=  -- add を使って、様々な型 α に double を提供
  Add.add x x

色々な型クラスがあります。Inhabited: 空ではなく、デフォルト値 default : α が存在することを示します。なお、いい感じに default を型情報から自動作成する仕組みの inferInstance というのもあります。(実は、Add Nat とかも推論してくれる。)

class Inhabited (α : Type u) where
  default : α

instance [Inhabited α] [Inhabited β] : Inhabited (α × β) where
  default := (default, default)

instance [Inhabited β] : Inhabited (α → β) where
  default := fun _ => default

def foo : Inhabited (Nat × Nat) :=
  inferInstance

def foo : Add Nat := inferInstance

ToString は文字列表現 toString : {α : Type u} → [ToString α] → α → String を持ってることを示します。

structure Person where
  name : String
  age  : Nat

instance : ToString Person where
  toString p := p.name ++ "@" ++ toString p.age

OfNat は自然数から変換できることを示します。(あと、toString で便利な記法があるみたい。)

structure Rational where
  num : Int
  den : Nat
  inv : den ≠ 0

instance : OfNat Rational n where
  ofNat := { num := n, den := 1, inv := by decide }

instance : ToString Rational where
  toString r := s!"{r.num}/{r.den}"

#eval (2 : Rational)  -- 2/1

Decidable は命題が決定可能 (真か偽に場合分け可能) であることを表します。なお、open Classic すると、全ての命題が決定可能になってしまいます。

決定可能であれば、if-then-else 式が使えます。また、decide タクティックが使えます。

class inductive Decidable (p : Prop) where
  | isFalse (h : ¬p) : Decidable p
  | isTrue  (h : p)  : Decidable p

def step (a b x : Nat) : Nat :=
  if x < a ∨ x > b then 0 else 1

example : 10 < 5 ∨ 1 > 0 := by
  decide

Coercionとは、プログラミング言語において、ある型の値を別の型に自動的に変換する仕組みのことです。下記は、Bool 値を Prop に自動変換します。

instance : Coe Bool Prop where
  coe b := b = true

#eval if true then 5 else 3

instance (p : Prop) [Decidable p] : CoeDep Prop p Bool where
  coe := decide p

あと、記法が便利になったりします。半群を下記のように定義します。要素のなす集合は S.carrier です。

structure Semigroup where
  carrier : Type u
  mul : carrier → carrier → carrier
  mul_assoc (a b c : carrier) : mul (mul a b) c = mul a (mul b c)

structure Semigroup where
  carrier : Type u
  mul : carrier → carrier → carrier
  mul_assoc (a b c : carrier) : mul (mul a b) c = mul a (mul b c)

ここで、CoeSort を定義しておくと、S.carrier と書かずに、S と書くだけで済んで便利になります。

instance : CoeSort Semigroup (Type u) where
  coe s := s.carrier

example (S : Semigroup) (a b c : S) : (a * b) * c = a * (b * c) :=
  Semigroup.mul_assoc _ a b c

11. The Conversion Tactic Mode

conv はゴールの一部だけに着目して書き換えを行えます。conv モードから抜けるには tactic => で抜けられます。
今回の場合は、congr の代わりに arg 2 とすればいきなり、b * c の操作に入れました。

example (a b c : Nat) : a * (b * c) = a * (c * b) := by
  -- ⊢ a * (b * c) = a * (c * b)
  conv =>
    lhs -- 左辺に注目 ; | a * (b * c)
    congr -- * で、a, (b*c) に証明課題を分割 | a
    . rfl -- a については rfl で解決したので | b * c
    . rw [Nat.mul_comm] -- rw で書き換えて | c * b

example (a b c : Nat) : a * (b * c) = a * (c * b) := by
  conv in b * c =>
    rw [Nat.mul_comm]

example (a b c : Nat) : a * (b * c) = a * (c * b) := by
  conv =>
    pattern b * c
    rw [Nat.mul_comm]

12. Axioms and Computation

ここは理論的(というか数学基礎論的?)な話がいくつかあります。

12.2. Propositional Extensionality

まず、命題外延性を公理として使うことも出来ます。

axiom propext {a b : Prop} : (a ↔ b) → a = b

同値なら良いじゃん、と思いたくなりますが、構成主義の「証明=プログラム」の哲学は相性が悪いので、標準には組み込まれていません。(どう不味いことが起きるのかは、詳しくは専門書読んで下さい。)

12.3. Function Extensionality

関数外延性は下記の様なものです。

funext.{u, v}
  {α : Sort u} {β : α → Sort v}
  {f g : (x : α) → β x}
  (h : ∀ (x : α), f x = g x) :
  f = g

これも普通に数学で使ってるように思います。が、Diaconescuの定理というのがあるらしく、いくつかの外延性を認めると排中律が証明出来てしまい、構成的な理論としては不具合があります。詳しくは 12.6 を見てください。

12.4. Quotients

また、同値関係 r : α → α → Prop の同値類 Quot r というのもあります。これは Lean のライブラリとして提供されています。

  • Quot: A と \sim に対して A/\sim を得る
  • Quot.mk: a\in A と \sim に対して、[a] \in A/\sim を得る
  • Quot.ind: \forall a\in A, P [a] \;\Longrightarrow\; \forall [q]\in A/\sim,\, P [q]。
  • Quot.lift f: A \to B とするとき、\forall a,b\in A,\, a\sim b \Longrightarrow f(a)=f(b) ならば、\tilde{f}:X/\sim\to B を作れる。
axiom Quot : {α : Sort u} → (α → α → Prop) → Sort u

axiom Quot.mk : {α : Sort u} → (r : α → α → Prop) → α → Quot r

axiom Quot.ind :
    ∀ {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop},
      (∀ a, β (Quot.mk r a)) → (q : Quot r) → β q

axiom Quot.lift :
    {α : Sort u} → {r : α → α → Prop} → {β : Sort u} → (f : α → β)
    → (∀ a b, r a b → f a = f b) → Quot r → β

まず同値関係 mod7Rel を定義します。すると、Nat を mod7Rel で割った同値類が Quot mod7Rel として得られます。

def mod7Rel (x y : Nat) : Prop :=
  x % 7 = y % 7

-- the quotient type
#check (Quot mod7Rel : Type)  -- Quot mod7Rel : Type
Quot mod7Rel : Type

-- the class of numbers equivalent to 4
#check (Quot.mk mod7Rel 4 : Quot mod7Rel)  -- mk mod7Rel 4 : Quot mod7Rel

def f (x : Nat) : Bool :=
  x % 7 = 0

theorem f_respects (a b : Nat) (h : mod7Rel a b) : f a = f b := by
  simp [mod7Rel] at *  -- h : a % 7 = b % 7
  simp [f] at *  -- ⊢ a % 7 = 0 ↔ b % 7 = 0
  rw [h]

#check (Quot.lift f f_respects : Quot mod7Rel → Bool)
-- Quot.lift f f_respects : Quot mod7Rel → Bool

-- the computation principle
example (a : Nat) : Quot.lift f f_respects (Quot.mk mod7Rel a) = f a :=
  rfl

Quot r 型の間の等式は、Quot.sound を apply することで、r の式に戻すことが出来ます。

axiom Quot.sound :
      ∀ {α : Type u} {r : α → α → Prop} {a b : α},
        r a b → Quot.mk r a = Quot.mk r b

さて、Quot で使ってる r は同値関係と言いつつ、同値関係の公理を要求していません。なので、通常は同値関係を要求した Quotient 型を使うことが推奨されています。

項目 Quot r Quotient s
関係の要件 任意の関係(同値でなくても自動で閉包) 同値関係の証明が必要(Setoidインスタンス)
安全性 低(誤った関係でも構築可能) 高(同値性が保証される)
便利関数 基本のみ(lift, ind, soundなど) Mathlibでlift₂, map, map₂など豊富
計算規則 強い(lift (mk a) = f a が定義的) 同じ
推奨度 低レベルで使う場合 通常こちらを使う

Setoid 型クラスは、型 α を同値関係 r で割ったもので、r が同値関係の公理 (反射律 refl・対称律 symm・推移律 trans) を満たす証明 iseqv : {α : Sort u} → (α → α → Prop) → Prop を要求します。

Setoid の要素の間の等価性は = ではなく ≈ (\approx) を使います。

class Setoid (α : Sort u) where
  r : α → α → Prop
  iseqv : Equivalence r

instance {α : Sort u} [Setoid α] : HasEquiv α :=
  ⟨Setoid.r⟩

namespace Setoid

variable {α : Sort u} [Setoid α]

theorem refl (a : α) : a ≈ a :=
  iseqv.refl a

theorem symm {a b : α} (hab : a ≈ b) : b ≈ a :=
  iseqv.symm hab

theorem trans {a b c : α} (hab : a ≈ b) (hbc : b ≈ c) : a ≈ c :=
  iseqv.trans hab hbc

end Setoid

def Quotient {α : Sort u} (s : Setoid α) :=
  @Quot α Setoid.r

なお、もっと便利な Mathlib の Quotient 型の話は、最後にします。

12.5. Choice

これも数学の定理の証明では多用する操作です。「空集合じゃないなら、要素を1つ取ってこれるよね?」というやつです。あるいは「pを満たすxが存在するなら、その x を一つ取ります」とか。勿論、構成的数学ではダメですが、通常の数学では普通に使いますし、使い方は 12.6 で示します。

axiom choice {α : Sort u} : Nonempty α → α

noncomputable def choose (h : ∃ x, p x) : α :=
  (indefiniteDescription p h).val

noncomputable def indefiniteDescription {α : Sort u}
    (p : α → Prop) (h : ∃ x, p x) : {x // p x} :=
  choice <| let ⟨x, px⟩ := h; ⟨⟨x, px⟩⟩

theorem choose_spec (h : ∃ x, p x) : p (choose h) :=
  (indefiniteDescription p h).property

12.6. The Law of the Excluded Middle

古典論理の排中律です。open Classical すれば、排中律が使えるようになりますが。また、Classical.choice, propext, funext から排中律を導出する話がテキストには書かれています。

Classical.em : ∀ (p : Prop), p ∨ ¬p

この辺のテクニックを使うと、空でない集合 \alpha と単射な関数 f : \alpha\to\beta に対して、ある g : \beta\to\alpha が存在して、g\circ f=\text{id} であることが示せたりします。

open Classical

noncomputable def linv [Inhabited α] (f : α → β) : β → α :=
  fun b : β => if ex : (∃ a : α, f a = b) then choose ex else default

theorem linv_comp_self {f : α → β} [Inhabited α]
                       (inj : ∀ {a b}, f a = f b → a = b)
                       : linv f ∘ f = id :=
  funext fun a =>
    have ex  : ∃ a₁ : α, f a₁ = f a := ⟨a, rfl⟩
    have feq : f (choose ex) = f a  := choose_spec ex
    calc linv f (f a)
      _ = choose ex := rfl
      _ = a         := inj feq

以上で、このテキストは終わりです。これである程度の Lean での証明テクニックは身についたかと思います。あとは具体的なライブラリの使い方に慣れる必要がありそうです。

Mathlib の Quotient 型の話

さて、Mathlib にも Quotient 型もあります。ライブラリが充実してる様です。という訳で、Mathlib の Quotient を使ってみます。

Mathlib を使う準備

$ lake new TPiL-New math
$ cd TPiL-New
$ lake update
$ lake exe cache get

なお、"〚", "〛", "≈", "ℕ", "⊢", "a₁" は \llb, \rrb, \approx, \nat, \vdash, "a_1` で入力します。

import Mathlib.Data.Quot  -- lift₂ などが使えるようになる
import Mathlib.Data.Nat.ModEq  -- % の性質が便利(オプション)

@[simp] def mod7Rel (x y : Nat) : Prop := x % 7 = y % 7

-- 同値関係の証明(Mathlib に似た証明が既にあるが、手動で)
-- 同値関係の証明
instance mod7Setoid : Setoid Nat where
  r := mod7Rel
  iseqv := {
    refl  := by intro n; simp [mod7Rel]
    symm  := by 
      intro a b h
      simp only [mod7Rel]
      simp only [mod7Rel] at h
      exact h.symm
    trans := by 
      intro a b c h1 h2
      simp only [mod7Rel]
      simp only [mod7Rel] at h1 h2
      rw [h1, h2]
  }

-- Quotient type の定義(推奨:Setoid を使う)
abbrev Mod7 := Quotient mod7Setoid

-- notation で見やすくする(オプション)
notation "〚" n "〛" => Quotient.mk' n   -- mk' は Setoid 用のコンストラクタ

-- 例: 同値な数は quotient で等しい
example : 〚10〛 = 〚17〛 := by
apply Quotient.sound
rfl  -- 10 % 7 = 3, 17 % 7 = 3

-- Nat.add_mod
-- ⊢ ∀ (a b n : ℕ), (a + b) % n = (a % n + b % n) % n

def addModProof : ∀ (a₁ b₁ a₂ b₂ : Nat), a₁ ≈ a₂ → b₁ ≈ b₂ → 
    〚 a₁ + b₁〛= 〚 a₂ + b₂〛  := by
  intros a₁ a₂ b₁ b₂ h1 h2
  apply Quotient.sound
  change _ % 7 = _ % 7
  change _ % 7 = _ % 7 at *
  conv =>
    lhs; rw [Nat.add_mod]
  conv =>
    rhs; rw [Nat.add_mod]
  rw [h1, h2]

-- 加算を lift(Mathlib の lift₂ が便利!)
def addMod : Mod7 → Mod7 → Mod7 :=
  Quotient.lift₂ (fun x y => 〚 x + y 〛 ) addModProof

infixl:65 "+++" => addMod

-- 例: 代表元が変わっても結果は同じ(外延的)
example : 〚10〛 +++ 〚17〛 = 〚 6〛 := by
  apply Quotient.sound  -- ⊢ 10 + 17 ≈ 6
  rfl

-- 可換性
example (a b : Mod7) : a +++ b = b +++ a := by
  --unfold addMod
  -- ⊢ a+++b = b+++a
  induction a using Quotient.ind
  induction b using Quotient.ind
  rename_i a' b'  -- ⊢ ⟦a'⟧+++⟦b'⟧ = ⟦b'⟧+++⟦a'⟧
  change 〚 a' + b' 〛 = 〚 b' + a' 〛  -- ⊢ 〚a' + b'〛 = 〚b' + a'〛
  apply Quotient.sound  -- ⊢ a' + b' ≈ b' + a'
  simp +arith; rfl

Discussion