src/HOL/Imperative_HOL/Heap_Monad.thy
author bulwahn
Wed Mar 31 16:44:41 2010 +0200 (2010-03-31)
changeset 36057 ca6610908ae9
parent 35423 6ef9525a5727
child 36078 59f6773a7d1d
permissions -rw-r--r--
adding MREC induction rule in Imperative HOL
     1 (*  Title:      HOL/Library/Heap_Monad.thy
     2     Author:     John Matthews, Galois Connections; Alexander Krauss, Lukas Bulwahn & Florian Haftmann, TU Muenchen
     3 *)
     4 
     5 header {* A monad with a polymorphic heap *}
     6 
     7 theory Heap_Monad
     8 imports Heap
     9 begin
    10 
    11 subsection {* The monad *}
    12 
    13 subsubsection {* Monad combinators *}
    14 
    15 datatype exception = Exn
    16 
    17 text {* Monadic heap actions either produce values
    18   and transform the heap, or fail *}
    19 datatype 'a Heap = Heap "heap \<Rightarrow> ('a + exception) \<times> heap"
    20 
    21 primrec
    22   execute :: "'a Heap \<Rightarrow> heap \<Rightarrow> ('a + exception) \<times> heap" where
    23   "execute (Heap f) = f"
    24 lemmas [code del] = execute.simps
    25 
    26 lemma Heap_execute [simp]:
    27   "Heap (execute f) = f" by (cases f) simp_all
    28 
    29 lemma Heap_eqI:
    30   "(\<And>h. execute f h = execute g h) \<Longrightarrow> f = g"
    31     by (cases f, cases g) (auto simp: expand_fun_eq)
    32 
    33 lemma Heap_eqI':
    34   "(\<And>h. (\<lambda>x. execute (f x) h) = (\<lambda>y. execute (g y) h)) \<Longrightarrow> f = g"
    35     by (auto simp: expand_fun_eq intro: Heap_eqI)
    36 
    37 lemma Heap_strip: "(\<And>f. PROP P f) \<equiv> (\<And>g. PROP P (Heap g))"
    38 proof
    39   fix g :: "heap \<Rightarrow> ('a + exception) \<times> heap" 
    40   assume "\<And>f. PROP P f"
    41   then show "PROP P (Heap g)" .
    42 next
    43   fix f :: "'a Heap" 
    44   assume assm: "\<And>g. PROP P (Heap g)"
    45   then have "PROP P (Heap (execute f))" .
    46   then show "PROP P f" by simp
    47 qed
    48 
    49 definition
    50   heap :: "(heap \<Rightarrow> 'a \<times> heap) \<Rightarrow> 'a Heap" where
    51   [code del]: "heap f = Heap (\<lambda>h. apfst Inl (f h))"
    52 
    53 lemma execute_heap [simp]:
    54   "execute (heap f) h = apfst Inl (f h)"
    55   by (simp add: heap_def)
    56 
    57 definition
    58   bindM :: "'a Heap \<Rightarrow> ('a \<Rightarrow> 'b Heap) \<Rightarrow> 'b Heap" (infixl ">>=" 54) where
    59   [code del]: "f >>= g = Heap (\<lambda>h. case execute f h of
    60                   (Inl x, h') \<Rightarrow> execute (g x) h'
    61                 | r \<Rightarrow> r)"
    62 
    63 notation
    64   bindM (infixl "\<guillemotright>=" 54)
    65 
    66 abbreviation
    67   chainM :: "'a Heap \<Rightarrow> 'b Heap \<Rightarrow> 'b Heap"  (infixl ">>" 54) where
    68   "f >> g \<equiv> f >>= (\<lambda>_. g)"
    69 
    70 notation
    71   chainM (infixl "\<guillemotright>" 54)
    72 
    73 definition
    74   return :: "'a \<Rightarrow> 'a Heap" where
    75   [code del]: "return x = heap (Pair x)"
    76 
    77 lemma execute_return [simp]:
    78   "execute (return x) h = apfst Inl (x, h)"
    79   by (simp add: return_def)
    80 
    81 definition
    82   raise :: "string \<Rightarrow> 'a Heap" where -- {* the string is just decoration *}
    83   [code del]: "raise s = Heap (Pair (Inr Exn))"
    84 
    85 notation (latex output)
    86   "raise" ("\<^raw:{\textsf{raise}}>")
    87 
    88 lemma execute_raise [simp]:
    89   "execute (raise s) h = (Inr Exn, h)"
    90   by (simp add: raise_def)
    91 
    92 
    93 subsubsection {* do-syntax *}
    94 
    95 text {*
    96   We provide a convenient do-notation for monadic expressions
    97   well-known from Haskell.  @{const Let} is printed
    98   specially in do-expressions.
    99 *}
   100 
   101 nonterminals do_expr
   102 
   103 syntax
   104   "_do" :: "do_expr \<Rightarrow> 'a"
   105     ("(do (_)//done)" [12] 100)
   106   "_bindM" :: "pttrn \<Rightarrow> 'a \<Rightarrow> do_expr \<Rightarrow> do_expr"
   107     ("_ <- _;//_" [1000, 13, 12] 12)
   108   "_chainM" :: "'a \<Rightarrow> do_expr \<Rightarrow> do_expr"
   109     ("_;//_" [13, 12] 12)
   110   "_let" :: "pttrn \<Rightarrow> 'a \<Rightarrow> do_expr \<Rightarrow> do_expr"
   111     ("let _ = _;//_" [1000, 13, 12] 12)
   112   "_nil" :: "'a \<Rightarrow> do_expr"
   113     ("_" [12] 12)
   114 
   115 syntax (xsymbols)
   116   "_bindM" :: "pttrn \<Rightarrow> 'a \<Rightarrow> do_expr \<Rightarrow> do_expr"
   117     ("_ \<leftarrow> _;//_" [1000, 13, 12] 12)
   118 syntax (latex output)
   119   "_do" :: "do_expr \<Rightarrow> 'a"
   120     ("(\<^raw:{\textsf{do}}> (_))" [12] 100)
   121   "_let" :: "pttrn \<Rightarrow> 'a \<Rightarrow> do_expr \<Rightarrow> do_expr"
   122     ("\<^raw:\textsf{let}> _ = _;//_" [1000, 13, 12] 12)
   123 notation (latex output)
   124   "return" ("\<^raw:{\textsf{return}}>")
   125 
   126 translations
   127   "_do f" => "f"
   128   "_bindM x f g" => "f \<guillemotright>= (\<lambda>x. g)"
   129   "_chainM f g" => "f \<guillemotright> g"
   130   "_let x t f" => "CONST Let t (\<lambda>x. f)"
   131   "_nil f" => "f"
   132 
   133 print_translation {*
   134 let
   135   fun dest_abs_eta (Abs (abs as (_, ty, _))) =
   136         let
   137           val (v, t) = Syntax.variant_abs abs;
   138         in (Free (v, ty), t) end
   139     | dest_abs_eta t =
   140         let
   141           val (v, t) = Syntax.variant_abs ("", dummyT, t $ Bound 0);
   142         in (Free (v, dummyT), t) end;
   143   fun unfold_monad (Const (@{const_syntax bindM}, _) $ f $ g) =
   144         let
   145           val (v, g') = dest_abs_eta g;
   146           val vs = fold_aterms (fn Free (v, _) => insert (op =) v | _ => I) v [];
   147           val v_used = fold_aterms
   148             (fn Free (w, _) => (fn s => s orelse member (op =) vs w) | _ => I) g' false;
   149         in if v_used then
   150           Const (@{syntax_const "_bindM"}, dummyT) $ v $ f $ unfold_monad g'
   151         else
   152           Const (@{syntax_const "_chainM"}, dummyT) $ f $ unfold_monad g'
   153         end
   154     | unfold_monad (Const (@{const_syntax chainM}, _) $ f $ g) =
   155         Const (@{syntax_const "_chainM"}, dummyT) $ f $ unfold_monad g
   156     | unfold_monad (Const (@{const_syntax Let}, _) $ f $ g) =
   157         let
   158           val (v, g') = dest_abs_eta g;
   159         in Const (@{syntax_const "_let"}, dummyT) $ v $ f $ unfold_monad g' end
   160     | unfold_monad (Const (@{const_syntax Pair}, _) $ f) =
   161         Const (@{const_syntax return}, dummyT) $ f
   162     | unfold_monad f = f;
   163   fun contains_bindM (Const (@{const_syntax bindM}, _) $ _ $ _) = true
   164     | contains_bindM (Const (@{const_syntax Let}, _) $ _ $ Abs (_, _, t)) =
   165         contains_bindM t;
   166   fun bindM_monad_tr' (f::g::ts) = list_comb
   167     (Const (@{syntax_const "_do"}, dummyT) $
   168       unfold_monad (Const (@{const_syntax bindM}, dummyT) $ f $ g), ts);
   169   fun Let_monad_tr' (f :: (g as Abs (_, _, g')) :: ts) =
   170     if contains_bindM g' then list_comb
   171       (Const (@{syntax_const "_do"}, dummyT) $
   172         unfold_monad (Const (@{const_syntax Let}, dummyT) $ f $ g), ts)
   173     else raise Match;
   174 in
   175  [(@{const_syntax bindM}, bindM_monad_tr'),
   176   (@{const_syntax Let}, Let_monad_tr')]
   177 end;
   178 *}
   179 
   180 
   181 subsection {* Monad properties *}
   182 
   183 subsubsection {* Monad laws *}
   184 
   185 lemma return_bind: "return x \<guillemotright>= f = f x"
   186   by (simp add: bindM_def return_def)
   187 
   188 lemma bind_return: "f \<guillemotright>= return = f"
   189 proof (rule Heap_eqI)
   190   fix h
   191   show "execute (f \<guillemotright>= return) h = execute f h"
   192     by (auto simp add: bindM_def return_def split: sum.splits prod.splits)
   193 qed
   194 
   195 lemma bind_bind: "(f \<guillemotright>= g) \<guillemotright>= h = f \<guillemotright>= (\<lambda>x. g x \<guillemotright>= h)"
   196   by (rule Heap_eqI) (auto simp add: bindM_def split: split: sum.splits prod.splits)
   197 
   198 lemma bind_bind': "f \<guillemotright>= (\<lambda>x. g x \<guillemotright>= h x) = f \<guillemotright>= (\<lambda>x. g x \<guillemotright>= (\<lambda>y. return (x, y))) \<guillemotright>= (\<lambda>(x, y). h x y)"
   199   by (rule Heap_eqI) (auto simp add: bindM_def split: split: sum.splits prod.splits)
   200 
   201 lemma raise_bind: "raise e \<guillemotright>= f = raise e"
   202   by (simp add: raise_def bindM_def)
   203 
   204 
   205 lemmas monad_simp = return_bind bind_return bind_bind raise_bind
   206 
   207 
   208 subsection {* Generic combinators *}
   209 
   210 definition
   211   liftM :: "('a \<Rightarrow> 'b) \<Rightarrow> 'a \<Rightarrow> 'b Heap"
   212 where
   213   "liftM f = return o f"
   214 
   215 definition
   216   compM :: "('a \<Rightarrow> 'b Heap) \<Rightarrow> ('b \<Rightarrow> 'c Heap) \<Rightarrow> 'a \<Rightarrow> 'c Heap" (infixl ">>==" 54)
   217 where
   218   "(f >>== g) = (\<lambda>x. f x \<guillemotright>= g)"
   219 
   220 notation
   221   compM (infixl "\<guillemotright>==" 54)
   222 
   223 lemma liftM_collapse: "liftM f x = return (f x)"
   224   by (simp add: liftM_def)
   225 
   226 lemma liftM_compM: "liftM f \<guillemotright>== g = g o f"
   227   by (auto intro: Heap_eqI' simp add: expand_fun_eq liftM_def compM_def bindM_def)
   228 
   229 lemma compM_return: "f \<guillemotright>== return = f"
   230   by (simp add: compM_def monad_simp)
   231 
   232 lemma compM_compM: "(f \<guillemotright>== g) \<guillemotright>== h = f \<guillemotright>== (g \<guillemotright>== h)"
   233   by (simp add: compM_def monad_simp)
   234 
   235 lemma liftM_bind:
   236   "(\<lambda>x. liftM f x \<guillemotright>= liftM g) = liftM (\<lambda>x. g (f x))"
   237   by (rule Heap_eqI') (simp add: monad_simp liftM_def bindM_def)
   238 
   239 lemma liftM_comp:
   240   "liftM f o g = liftM (f o g)"
   241   by (rule Heap_eqI') (simp add: liftM_def)
   242 
   243 lemmas monad_simp' = monad_simp liftM_compM compM_return
   244   compM_compM liftM_bind liftM_comp
   245 
   246 primrec 
   247   mapM :: "('a \<Rightarrow> 'b Heap) \<Rightarrow> 'a list \<Rightarrow> 'b list Heap"
   248 where
   249   "mapM f [] = return []"
   250   | "mapM f (x#xs) = do y \<leftarrow> f x;
   251                         ys \<leftarrow> mapM f xs;
   252                         return (y # ys)
   253                      done"
   254 
   255 primrec
   256   foldM :: "('a \<Rightarrow> 'b \<Rightarrow> 'b Heap) \<Rightarrow> 'a list \<Rightarrow> 'b \<Rightarrow> 'b Heap"
   257 where
   258   "foldM f [] s = return s"
   259   | "foldM f (x#xs) s = f x s \<guillemotright>= foldM f xs"
   260 
   261 definition
   262   assert :: "('a \<Rightarrow> bool) \<Rightarrow> 'a \<Rightarrow> 'a Heap"
   263 where
   264   "assert P x = (if P x then return x else raise (''assert''))"
   265 
   266 lemma assert_cong [fundef_cong]:
   267   assumes "P = P'"
   268   assumes "\<And>x. P' x \<Longrightarrow> f x = f' x"
   269   shows "(assert P x >>= f) = (assert P' x >>= f')"
   270   using assms by (auto simp add: assert_def return_bind raise_bind)
   271 
   272 subsubsection {* A monadic combinator for simple recursive functions *}
   273 
   274 text {* Using a locale to fix arguments f and g of MREC *}
   275 
   276 locale mrec =
   277 fixes
   278   f :: "'a => ('b + 'a) Heap"
   279   and g :: "'a => 'a => 'b => 'b Heap"
   280 begin
   281 
   282 function (default "\<lambda>(x,h). (Inr Exn, undefined)") 
   283   mrec 
   284 where
   285   "mrec x h = 
   286    (case Heap_Monad.execute (f x) h of
   287      (Inl (Inl r), h') \<Rightarrow> (Inl r, h')
   288    | (Inl (Inr s), h') \<Rightarrow> 
   289           (case mrec s h' of
   290              (Inl z, h'') \<Rightarrow> Heap_Monad.execute (g x s z) h''
   291            | (Inr e, h'') \<Rightarrow> (Inr e, h''))
   292    | (Inr e, h') \<Rightarrow> (Inr e, h')
   293    )"
   294 by auto
   295 
   296 lemma graph_implies_dom:
   297   "mrec_graph x y \<Longrightarrow> mrec_dom x"
   298 apply (induct rule:mrec_graph.induct) 
   299 apply (rule accpI)
   300 apply (erule mrec_rel.cases)
   301 by simp
   302 
   303 lemma mrec_default: "\<not> mrec_dom (x, h) \<Longrightarrow> mrec x h = (Inr Exn, undefined)"
   304   unfolding mrec_def 
   305   by (rule fundef_default_value[OF mrec_sumC_def graph_implies_dom, of _ _ "(x, h)", simplified])
   306 
   307 lemma mrec_di_reverse: 
   308   assumes "\<not> mrec_dom (x, h)"
   309   shows "
   310    (case Heap_Monad.execute (f x) h of
   311      (Inl (Inl r), h') \<Rightarrow> False
   312    | (Inl (Inr s), h') \<Rightarrow> \<not> mrec_dom (s, h')
   313    | (Inr e, h') \<Rightarrow> False
   314    )" 
   315 using assms
   316 by (auto split:prod.splits sum.splits)
   317  (erule notE, rule accpI, elim mrec_rel.cases, simp)+
   318 
   319 
   320 lemma mrec_rule:
   321   "mrec x h = 
   322    (case Heap_Monad.execute (f x) h of
   323      (Inl (Inl r), h') \<Rightarrow> (Inl r, h')
   324    | (Inl (Inr s), h') \<Rightarrow> 
   325           (case mrec s h' of
   326              (Inl z, h'') \<Rightarrow> Heap_Monad.execute (g x s z) h''
   327            | (Inr e, h'') \<Rightarrow> (Inr e, h''))
   328    | (Inr e, h') \<Rightarrow> (Inr e, h')
   329    )"
   330 apply (cases "mrec_dom (x,h)", simp)
   331 apply (frule mrec_default)
   332 apply (frule mrec_di_reverse, simp)
   333 by (auto split: sum.split prod.split simp: mrec_default)
   334 
   335 
   336 definition
   337   "MREC x = Heap (mrec x)"
   338 
   339 lemma MREC_rule:
   340   "MREC x = 
   341   (do y \<leftarrow> f x;
   342                 (case y of 
   343                 Inl r \<Rightarrow> return r
   344               | Inr s \<Rightarrow> 
   345                 do z \<leftarrow> MREC s ;
   346                    g x s z
   347                 done) done)"
   348   unfolding MREC_def
   349   unfolding bindM_def return_def
   350   apply simp
   351   apply (rule ext)
   352   apply (unfold mrec_rule[of x])
   353   by (auto split:prod.splits sum.splits)
   354 
   355 
   356 lemma MREC_pinduct:
   357   assumes "Heap_Monad.execute (MREC x) h = (Inl r, h')"
   358   assumes non_rec_case: "\<And> x h h' r. Heap_Monad.execute (f x) h = (Inl (Inl r), h') \<Longrightarrow> P x h h' r"
   359   assumes rec_case: "\<And> x h h1 h2 h' s z r. Heap_Monad.execute (f x) h = (Inl (Inr s), h1) \<Longrightarrow> Heap_Monad.execute (MREC s) h1 = (Inl z, h2) \<Longrightarrow> P s h1 h2 z
   360     \<Longrightarrow> Heap_Monad.execute (g x s z) h2 = (Inl r, h') \<Longrightarrow> P x h h' r"
   361   shows "P x h h' r"
   362 proof -
   363   from assms(1) have mrec: "mrec x h = (Inl r, h')"
   364     unfolding MREC_def execute.simps .
   365   from mrec have dom: "mrec_dom (x, h)"
   366     apply -
   367     apply (rule ccontr)
   368     apply (drule mrec_default) by auto
   369   from mrec have h'_r: "h' = (snd (mrec x h))" "r = (Sum_Type.Projl (fst (mrec x h)))"
   370     by auto
   371   from mrec have "P x h (snd (mrec x h)) (Sum_Type.Projl (fst (mrec x h)))"
   372   proof (induct arbitrary: r h' rule: mrec.pinduct[OF dom])
   373     case (1 x h)
   374     obtain rr h' where "mrec x h = (rr, h')" by fastsimp
   375     obtain fret h1 where exec_f: "Heap_Monad.execute (f x) h = (fret, h1)" by fastsimp
   376     show ?case
   377     proof (cases fret)
   378       case (Inl a)
   379       note Inl' = this
   380       show ?thesis
   381       proof (cases a)
   382         case (Inl aa)
   383         from this Inl' 1(1) exec_f mrec non_rec_case show ?thesis
   384           by auto
   385       next
   386         case (Inr b)
   387         note Inr' = this
   388         obtain ret_mrec h2 where mrec_rec: "mrec b h1 = (ret_mrec, h2)" by fastsimp
   389         from this Inl 1(1) exec_f mrec show ?thesis
   390         proof (cases "ret_mrec")
   391           case (Inl aaa)
   392           from this mrec exec_f Inl' Inr' 1(1) mrec_rec 1(2)[OF exec_f Inl' Inr', of "aaa" "h2"] 1(3)
   393             show ?thesis
   394               apply auto
   395               apply (rule rec_case)
   396               unfolding MREC_def by auto
   397         next
   398           case (Inr b)
   399           from this Inl 1(1) exec_f mrec Inr' mrec_rec 1(3) show ?thesis by auto
   400         qed
   401       qed
   402     next
   403       case (Inr b)
   404       from this 1(1) mrec exec_f 1(3) show ?thesis by simp
   405     qed
   406   qed
   407   from this h'_r show ?thesis by simp
   408 qed
   409 
   410 end
   411 
   412 text {* Providing global versions of the constant and the theorems *}
   413 
   414 abbreviation "MREC == mrec.MREC"
   415 lemmas MREC_rule = mrec.MREC_rule
   416 lemmas MREC_pinduct = mrec.MREC_pinduct
   417 
   418 hide (open) const heap execute
   419 
   420 
   421 subsection {* Code generator setup *}
   422 
   423 subsubsection {* Logical intermediate layer *}
   424 
   425 definition
   426   Fail :: "String.literal \<Rightarrow> exception"
   427 where
   428   [code del]: "Fail s = Exn"
   429 
   430 definition
   431   raise_exc :: "exception \<Rightarrow> 'a Heap"
   432 where
   433   [code del]: "raise_exc e = raise []"
   434 
   435 lemma raise_raise_exc [code, code_unfold]:
   436   "raise s = raise_exc (Fail (STR s))"
   437   unfolding Fail_def raise_exc_def raise_def ..
   438 
   439 hide (open) const Fail raise_exc
   440 
   441 
   442 subsubsection {* SML and OCaml *}
   443 
   444 code_type Heap (SML "unit/ ->/ _")
   445 code_const Heap (SML "raise/ (Fail/ \"bare Heap\")")
   446 code_const "op \<guillemotright>=" (SML "!(fn/ f'_/ =>/ fn/ ()/ =>/ f'_/ (_/ ())/ ())")
   447 code_const return (SML "!(fn/ ()/ =>/ _)")
   448 code_const "Heap_Monad.Fail" (SML "Fail")
   449 code_const "Heap_Monad.raise_exc" (SML "!(fn/ ()/ =>/ raise/ _)")
   450 
   451 code_type Heap (OCaml "_")
   452 code_const Heap (OCaml "failwith/ \"bare Heap\"")
   453 code_const "op \<guillemotright>=" (OCaml "!(fun/ f'_/ ()/ ->/ f'_/ (_/ ())/ ())")
   454 code_const return (OCaml "!(fun/ ()/ ->/ _)")
   455 code_const "Heap_Monad.Fail" (OCaml "Failure")
   456 code_const "Heap_Monad.raise_exc" (OCaml "!(fun/ ()/ ->/ raise/ _)")
   457 
   458 setup {*
   459 
   460 let
   461 
   462 open Code_Thingol;
   463 
   464 fun imp_program naming =
   465 
   466   let
   467     fun is_const c = case lookup_const naming c
   468      of SOME c' => (fn c'' => c' = c'')
   469       | NONE => K false;
   470     val is_bindM = is_const @{const_name bindM};
   471     val is_return = is_const @{const_name return};
   472     val dummy_name = "";
   473     val dummy_type = ITyVar dummy_name;
   474     val dummy_case_term = IVar NONE;
   475     (*assumption: dummy values are not relevant for serialization*)
   476     val unitt = case lookup_const naming @{const_name Unity}
   477      of SOME unit' => IConst (unit', (([], []), []))
   478       | NONE => error ("Must include " ^ @{const_name Unity} ^ " in generated constants.");
   479     fun dest_abs ((v, ty) `|=> t, _) = ((v, ty), t)
   480       | dest_abs (t, ty) =
   481           let
   482             val vs = fold_varnames cons t [];
   483             val v = Name.variant vs "x";
   484             val ty' = (hd o fst o unfold_fun) ty;
   485           in ((SOME v, ty'), t `$ IVar (SOME v)) end;
   486     fun force (t as IConst (c, _) `$ t') = if is_return c
   487           then t' else t `$ unitt
   488       | force t = t `$ unitt;
   489     fun tr_bind' [(t1, _), (t2, ty2)] =
   490       let
   491         val ((v, ty), t) = dest_abs (t2, ty2);
   492       in ICase (((force t1, ty), [(IVar v, tr_bind'' t)]), dummy_case_term) end
   493     and tr_bind'' t = case unfold_app t
   494          of (IConst (c, (_, ty1 :: ty2 :: _)), [x1, x2]) => if is_bindM c
   495               then tr_bind' [(x1, ty1), (x2, ty2)]
   496               else force t
   497           | _ => force t;
   498     fun imp_monad_bind'' ts = (SOME dummy_name, dummy_type) `|=> ICase (((IVar (SOME dummy_name), dummy_type),
   499       [(unitt, tr_bind' ts)]), dummy_case_term)
   500     and imp_monad_bind' (const as (c, (_, tys))) ts = if is_bindM c then case (ts, tys)
   501        of ([t1, t2], ty1 :: ty2 :: _) => imp_monad_bind'' [(t1, ty1), (t2, ty2)]
   502         | ([t1, t2, t3], ty1 :: ty2 :: _) => imp_monad_bind'' [(t1, ty1), (t2, ty2)] `$ t3
   503         | (ts, _) => imp_monad_bind (eta_expand 2 (const, ts))
   504       else IConst const `$$ map imp_monad_bind ts
   505     and imp_monad_bind (IConst const) = imp_monad_bind' const []
   506       | imp_monad_bind (t as IVar _) = t
   507       | imp_monad_bind (t as _ `$ _) = (case unfold_app t
   508          of (IConst const, ts) => imp_monad_bind' const ts
   509           | (t, ts) => imp_monad_bind t `$$ map imp_monad_bind ts)
   510       | imp_monad_bind (v_ty `|=> t) = v_ty `|=> imp_monad_bind t
   511       | imp_monad_bind (ICase (((t, ty), pats), t0)) = ICase
   512           (((imp_monad_bind t, ty),
   513             (map o pairself) imp_monad_bind pats),
   514               imp_monad_bind t0);
   515 
   516   in (Graph.map_nodes o map_terms_stmt) imp_monad_bind end;
   517 
   518 in
   519 
   520 Code_Target.extend_target ("SML_imp", ("SML", imp_program))
   521 #> Code_Target.extend_target ("OCaml_imp", ("OCaml", imp_program))
   522 
   523 end
   524 
   525 *}
   526 
   527 code_reserved OCaml Failure raise
   528 
   529 
   530 subsubsection {* Haskell *}
   531 
   532 text {* Adaption layer *}
   533 
   534 code_include Haskell "Heap"
   535 {*import qualified Control.Monad;
   536 import qualified Control.Monad.ST;
   537 import qualified Data.STRef;
   538 import qualified Data.Array.ST;
   539 
   540 type RealWorld = Control.Monad.ST.RealWorld;
   541 type ST s a = Control.Monad.ST.ST s a;
   542 type STRef s a = Data.STRef.STRef s a;
   543 type STArray s a = Data.Array.ST.STArray s Int a;
   544 
   545 newSTRef = Data.STRef.newSTRef;
   546 readSTRef = Data.STRef.readSTRef;
   547 writeSTRef = Data.STRef.writeSTRef;
   548 
   549 newArray :: (Int, Int) -> a -> ST s (STArray s a);
   550 newArray = Data.Array.ST.newArray;
   551 
   552 newListArray :: (Int, Int) -> [a] -> ST s (STArray s a);
   553 newListArray = Data.Array.ST.newListArray;
   554 
   555 lengthArray :: STArray s a -> ST s Int;
   556 lengthArray a = Control.Monad.liftM snd (Data.Array.ST.getBounds a);
   557 
   558 readArray :: STArray s a -> Int -> ST s a;
   559 readArray = Data.Array.ST.readArray;
   560 
   561 writeArray :: STArray s a -> Int -> a -> ST s ();
   562 writeArray = Data.Array.ST.writeArray;*}
   563 
   564 code_reserved Haskell Heap
   565 
   566 text {* Monad *}
   567 
   568 code_type Heap (Haskell "Heap.ST/ Heap.RealWorld/ _")
   569 code_const Heap (Haskell "error/ \"bare Heap\"")
   570 code_monad "op \<guillemotright>=" Haskell
   571 code_const return (Haskell "return")
   572 code_const "Heap_Monad.Fail" (Haskell "_")
   573 code_const "Heap_Monad.raise_exc" (Haskell "error")
   574 
   575 end