miscelleaneous

Random Lean experiments

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 62
  63. 63
  64. 64
  65. 65
  66. 66
  67. 67
  68. 68
  69. 69
  70. 70
  71. 71
  72. 72
  73. 73
  74. 74
import Std.Tactic.Do
import Mathlib

variable [LinearOrder α] (A : Array α)

def BubbleSort := Id.run do
  let N := A.size
  let mut A := A.toVector
  for i in List.range (N - 1) do
    for hj : j in List.range (N - i - 1) do
      have := List.mem_range.mp hj
      if A[j + 1] < A[j] then
        A := A.swap j (j + 1)
  return A.toArray

def ICan'tBelieveItCanSort := Id.run do
  let N := A.size
  let mut A := A.toVector
  for hi : i in [:N] do
    for hj : j in [:N] do
      if A[i] < A[j] then
        A := A.swap i j
  return A.toArray

#guard let A := #[69, 420, 1, 1, 13, 1, 65536]
  ICan'tBelieveItCanSort A = A.qsort

open Std.Do

theorem perm : ICan'tBelieveItCanSort.{0} A |>.Perm A := by
  generalize h : ICan'tBelieveItCanSort A = x
  suffices Multiset.ofList x.toList = A.toList by
    exact { toList := Multiset.coe_eq_coe.mp this }
  apply Id.of_wp_run_eq h
  mvcgen
  case inv1 | inv2 => exact _, A' => Multiset.ofList A.toList = A'.toList
  all_goals try grind
  case vc1.step.isTrue =>
    expose_names
    simp_all only [Multiset.coe_eq_coe]
    exact h_5.trans <| .symm <| Vector.perm_iff_toList_perm.mp <| Vector.swap_perm (by grind) (by grind)

theorem sorted : ICan'tBelieveItCanSort.{0} A |>.Pairwise (·  ·) := by
  generalize h : ICan'tBelieveItCanSort A = x
  apply Id.of_wp_run_eq h
  mvcgen <;> expose_names
  case inv1 => exact xs, A' => A'.take xs.pos |>.toArray.Pairwise (·  ·)
  case inv2 =>
    exact xs, A' => (A'.take cur |>.toArray.Pairwise (·  ·))   i (_ : i < xs.pos), A'[i]'(by
      have : xs.prefix.length + xs.suffix.length = N := by simp [ List.length_append, xs.property]
      grind
      )  A'[cur]'(by grind)
  case vc1.step.isTrue =>
    simp_all
    constructor
    · rw [Array.pairwise_iff_getElem] at h_5 
      intro i j hi hj hij
      simp
      grind
    · grind
  case vc2.step.isFalse => constructor <;> grind
  case vc3.step.pre => grind
  case vc4.step.post.success =>
    simp_all
    rw [Array.pairwise_iff_getElem] at h_3 
    grind
  case vc5.a.pre => grind
  case vc6.a.post.success =>
    simp_all
    rwa [show r.toArray = r.toArray.extract 0 N by grind]

theorem ICan'tBelieveICanProveItCanSort : (ICan'tBelieveItCanSort.{0} A |>.Perm A)
     (ICan'tBelieveItCanSort.{0} A |>.Pairwise (·  ·)) :=
  perm A, sorted A