-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathCIC3.lean
More file actions
78 lines (67 loc) · 2.08 KB
/
Copy pathCIC3.lean
File metadata and controls
78 lines (67 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/-
We can actually build an expression that the result type of an expression is part of the expression itself. So an ill-typed term cannot even be constructed/type chekced.
-/
inductive Ty where
| nat
| bool
deriving Repr, DecidableEq
abbrev Ty.denote : Ty → Type
| .nat => Nat
| .bool => Bool
inductive Expr : Ty → Type where
| nat : Nat → Expr .nat
| bool : Bool → Expr .bool
| add : Expr .nat → Expr .nat → Expr .nat
| le : Expr .nat → Expr .nat → Expr .bool
| ite : Expr .bool → Expr t → Expr t → Expr t
deriving Repr
def eval : Expr t → Ty.denote t
| .nat n => n
| .bool b => b
| .add e₁ e₂ => eval e₁ + eval e₂
| .le e₁ e₂ => decide (eval e₁ <= eval e₂)
| .ite c e₁ e₂ => if eval c then eval e₁ else eval e₂
def ex : Expr .nat :=
.ite (.le (.nat 3) (.nat 5))
(.add (.nat 10) (.nat 20))
(.nat 0)
#eval eval ex -- 30
-- def bad : Expr .nat := .add (.bool true) (.nat 3)
-- def bad2 : Expr .nat := .ite (.bool true) (.nat 1) (.bool false)
/-
We can also write transformations that preserve typing by construction.
-/
def constFold : Expr t → Expr t
| .nat n => .nat n
| .bool b => .bool b
| .add e₁ e₂ =>
let e₁' := constFold e₁
let e₂' := constFold e₂
match e₁', e₂' with
| .nat n₁, .nat n₂ => .nat (n₁ + n₂)
| _, _ => .add e₁' e₂'
| .le e₁ e₂ =>
let e₁' := constFold e₁
let e₂' := constFold e₂
match e₁', e₂' with
| .nat n₁, .nat n₂ => .bool (decide (n₁ <= n₂))
| _, _ => .le e₁' e₂'
| .ite c e₁ e₂ =>
let c' := constFold c
let e₁' := constFold e₁
let e₂' := constFold e₂
match c' with
| .bool true => e₁'
| .bool false => e₂'
| _ => .ite c' e₁' e₂'
def ex2 : Expr .nat :=
.add (.nat 7)
(.ite (.le (.nat 2) (.nat 1))
(.nat 100)
(.add (.nat 20) (.nat 15)))
#eval ex2
#eval constFold ex2
#eval eval ex2
#eval eval (constFold ex2)
example : constFold ex2 = .nat 42 := rfl
example : eval ex2 = 42 := rfl