Skip to content

Instantly share code, notes, and snippets.

@tangentstorm
Last active January 9, 2016 20:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tangentstorm/4ccb13968414437da36b to your computer and use it in GitHub Desktop.
Save tangentstorm/4ccb13968414437da36b to your computer and use it in GitHub Desktop.
theory SumOfRange
imports Main
begin
fun sum :: "nat list ⇒ nat" where
"sum xs = foldl (op+) 0 xs"
fun egnar :: "nat ⇒ nat list" where
"egnar x = (if x ≤ 0 then [] else x # egnar (x-1))"
fun range :: "nat ⇒ nat list" where
"range x = rev (egnar x)"
fun sr :: "nat ⇒ nat" where
"sr n = (if n≤0 then 0 else n + (sr (n-1)))"
theorem sum_range_0 [simp]: "sum (range 0) = 0"
by auto
theorem sum_range [simp]: "n > 0 ⟹ sum (range n) = n + sum (range (n-1))"
by (induction n; auto)
theorem srsimp [simp]: "n > 0 ⟹ sum (range n) = sr n"
by (induction n; auto)
theorem sr2 [simp]: "n > 0 ⟹ 2 * (sr n) = n * (n + 1)"
by (induction n; auto)
theorem "n > 0 ⟹ sum (range n) = (n * (n+1)) div 2"
proof -
let ?x = "sum (range n)"
have "n>0 ⟹ ?x = sr n" by (simp only: srsimp)
hence "n>0 ⟹ 2 * ?x = 2 * sr n" by auto
hence "n>0 ⟹ 2 * ?x = n * (n + 1)" by (simp only: sr2)
hence "n>0 ⟹ ?x = n * (n + 1) div 2" by auto
thus ?thesis by auto
qed
end
@larsrh
Copy link

larsrh commented Jan 9, 2016

Simpler proof:

theorem
  assumes "n > 0"
  shows "sum (range n) = (n * (n+1)) div 2" (is "?x = _")
proof -
  have  "?x =     sr n"          using assms by (simp only: srsimp)
  hence "2 * ?x = 2 * sr n"      by auto
  hence "2 * ?x = n * (n + 1)"   using assms by (simp only: sr2)
  thus ?thesis by auto
qed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment