theory week10B_demo 
imports "~~/src/HOL/Hoare/HeapSyntax" 
begin


primrec
  fac :: "nat \<Rightarrow> nat"
where
  "fac 0 = 1"
| "fac (Suc n) = (Suc n) * fac n"


lemma "VARS B { True } B := 2 { B = 2 }"
  apply vcg_simp
  done

lemma 
  " VARS (x::nat) y r 
    {True} 
    IF x>y THEN r:=x ELSE r:=y FI
    { (r=x\<or> r=y) \<and> r\<ge>x \<and> r\<ge>y} "
  apply vcg_simp
  done


lemma mult_by_add:
  "VARS (A::int) B 
   { A = 0 \<and> B = 0 }
    WHILE A \<noteq> a
    INV { B = A * b } DO 
      B := B + b; 
      A := A + 1
    OD
    {B = a * b }"
  apply vcg_simp
  apply (simp add: left_distrib)
done

lemma factorial_sound:
  "VARS A B
  { A = n}
  B := 1;
  WHILE A \<noteq> 0 INV { fac n = B * fac A } DO
    B := B * A;
    A := A - 1
  OD
  { B = fac n }"
  apply vcg_simp
  apply (case_tac A, simp_all)
done

  

-- "Arrays"
  

lemma zero_search: 
 "VARS I L 
 { True }
  I := 0;
  WHILE I < length L \<and> L!I \<noteq> key 
  INV { \<forall>j < I. L!j \<noteq> key } DO
    I := I+1 
  OD
  { (I < length L \<longrightarrow> L!I = key) \<and>
    (I = length L \<longrightarrow> key \<notin> set L) }"
  apply vcg_simp
   apply (intro allI impI)
   apply (case_tac "j<I")
    apply clarsimp
   apply (subgoal_tac "j=I", simp) 
   apply simp
  apply clarsimp
  apply (clarsimp simp: in_set_conv_nth)
(* or: apply (drule all_nth_imp_all_set, assumption) *)
  apply auto
done 

-- Pointers


lemma element_search:
 "VARS nxt p
  { List nxt p Ps \<and> X \<in> set Ps }
  WHILE p \<noteq> Null \<and> p \<noteq> Ref X
  INV { \<exists>ps. List nxt p ps \<and> X \<in> set ps }
  DO p := p^.nxt OD
  { p = Ref X }"
  apply vcg_simp
    apply blast
   apply clarsimp
  apply clarsimp
  done



lemma "VARS tl p q pp qq
  {List tl p Ps \<and> List tl q Qs \<and> set Ps \<inter> set Qs = {} \<and> size Qs \<le> size Ps}
  pp := p;
  WHILE q \<noteq> Null
  INV {\<exists>as bs qs.
    distinct as \<and> Path tl p as pp \<and> List tl pp bs \<and> List tl q qs \<and>
    set bs \<inter> set qs = {} \<and> set as \<inter> (set bs \<union> set qs) = {} \<and>
    size qs \<le> size bs \<and> splice Ps Qs = as @ splice bs qs}
  DO qq := q^.tl; q^.tl := pp^.tl; pp^.tl := q; pp := q^.tl; q := qq OD
  {List tl p (splice Ps Qs)}"
apply vcg_simp
  apply(rule_tac x = "[]" in exI)
  apply fastsimp
 apply clarsimp
 apply(rename_tac y bs qqs)
 apply(case_tac bs) apply simp
 apply clarsimp
 apply(rename_tac x bbs)
 apply(rule_tac x = "as @ [x,y]" in exI)
 apply simp
 apply(rule_tac x = "bbs" in exI)
 apply simp
 apply(rule_tac x = "qqs" in exI)
 apply simp
apply (fastsimp simp:List_app)
done


   
end