Skip to content

Instantly share code, notes, and snippets.

@klaeufer
Last active December 31, 2024 21:41
Show Gist options
  • Save klaeufer/8e2c4a492b4cee0b5b740e8160290618 to your computer and use it in GitHub Desktop.
Save klaeufer/8e2c4a492b4cee0b5b740e8160290618 to your computer and use it in GitHub Desktop.
Lean 4: simple experiments with List
import Mathlib.Data.List.Basic
section
-- BEGIN
-- https://lean-lang.org/blog/2024-1-11-recursive-definitions-in-lean/
-- TODO make tail-recursive?
def my_reverse {α : Type u} (xs : List α) : List α :=
match xs with
| [] => []
| x :: rest => my_reverse rest ++ [x]
def reverse_spec {α : Type u} (xs : List α) : Prop :=
my_reverse xs = xs.reverse
theorem my_reverse_satisfies_spec : reverse_spec xs := by
induction xs with
| nil => simp [my_reverse, reverse_spec]
| cons y ys ih =>
rw [reverse_spec]
rw [my_reverse]
rw [List.reverse_cons]
rw [ih]
def reverse_length_spec {α : Type u} (xs : List α) : Prop :=
xs.length = (my_reverse xs).length
example : reverse_length_spec xs := by
induction xs with
| nil => exact List.length_nil
| cons y ys ih =>
rw [reverse_length_spec]
rw [my_reverse]
rw [List.length_append]
rw [List.length_cons]
rw [ih]
rw [List.length_cons]
rw [List.length_nil]
#check my_reverse
#check reverse_spec
#check my_reverse_satisfies_spec
#check reverse_length_spec
#eval my_reverse [1, 2, 3]
#eval my_reverse ["hello", "world"]
#check (my_reverse [List, Array]).length
-- END
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment