@@ -5,7 +5,7 @@ appear on the lhs of the rule, but solving `hf` fully determines it.
5
5
6
6
theorem List.foldl_subtype (p : α → Prop ) (l : List (Subtype p)) (f : β → Subtype p → β)
7
7
(g : β → α → β) (b : β)
8
- { hf : ∀ b x h, f b ⟨x, h⟩ = g b x} :
8
+ ( hf : ∀ b x h, f b ⟨x, h⟩ = g b x) :
9
9
l.foldl f b = (l.map (·.val)).foldl g b := by
10
10
induction l generalizing b with
11
11
| nil => simp
@@ -18,3 +18,34 @@ example (l : List Nat) :
18
18
example (l : List Nat) :
19
19
l.attach.foldl (fun acc ⟨t, _⟩ => max acc t) 0 = l.foldl (fun acc t => max acc t) 0 := by
20
20
simp [List.foldl_subtype]
21
+
22
+
23
+ theorem foldr_to_sum (l : List Nat) (f : Nat → Nat → Nat) (g : Nat → Nat)
24
+ (h : ∀ acc x, f x acc = g x + acc) :
25
+ l.foldr f 0 = Nat.sum (l.map g) := by
26
+ rw [Nat.sum, List.foldr_map]
27
+ congr
28
+ funext x acc
29
+ apply h
30
+
31
+ -- this works:
32
+ example (l : List Nat) :
33
+ l.foldr (fun x a => x*x + a) 0 = Nat.sum (l.map (fun x => x * x)) := by
34
+ simp [foldr_to_sum]
35
+
36
+ -- this does not, so such a pattern is still quite fragile
37
+
38
+ /-- error: simp made no progress -/
39
+ #guard_msgs in
40
+ example (l : List Nat) :
41
+ l.foldr (fun x a => a + x*x) 0 = Nat.sum (l.map (fun x => x * x)) := by
42
+ simp [foldr_to_sum]
43
+
44
+ -- but with stronger simp normal forms, it would work:
45
+
46
+ @[simp]
47
+ theorem add_eq_add_cancel (a x y : Nat) : (a + x = y + a) ↔ (x = y) := by omega
48
+
49
+ example (l : List Nat) :
50
+ l.foldr (fun x a => a + x*x) 0 = Nat.sum (l.map (fun x => x * x)) := by
51
+ simp [foldr_to_sum]
0 commit comments