src/HOL/Library/State_Monad.thy
author haftmann
Wed Mar 12 08:47:36 2008 +0100 (2008-03-12)
changeset 26260 23ce0d32de11
parent 26141 e1b3a6953cdc
child 26266 35ae83ca190a
permissions -rw-r--r--
tuned
haftmann@21192
     1
(*  Title:      HOL/Library/State_Monad.thy
haftmann@21192
     2
    ID:         $Id$
haftmann@21192
     3
    Author:     Florian Haftmann, TU Muenchen
haftmann@21192
     4
*)
haftmann@21192
     5
haftmann@21192
     6
header {* Combinators syntax for generic, open state monads (single threaded monads) *}
haftmann@21192
     7
haftmann@21192
     8
theory State_Monad
haftmann@25595
     9
imports List
haftmann@21192
    10
begin
haftmann@21192
    11
haftmann@21192
    12
subsection {* Motivation *}
haftmann@21192
    13
haftmann@21192
    14
text {*
haftmann@21192
    15
  The logic HOL has no notion of constructor classes, so
haftmann@21192
    16
  it is not possible to model monads the Haskell way
haftmann@21192
    17
  in full genericity in Isabelle/HOL.
haftmann@21192
    18
  
haftmann@21192
    19
  However, this theory provides substantial support for
haftmann@21192
    20
  a very common class of monads: \emph{state monads}
haftmann@21192
    21
  (or \emph{single-threaded monads}, since a state
haftmann@21192
    22
  is transformed single-threaded).
haftmann@21192
    23
haftmann@21192
    24
  To enter from the Haskell world,
haftmann@21192
    25
  \url{http://www.engr.mun.ca/~theo/Misc/haskell_and_monads.htm}
haftmann@21192
    26
  makes a good motivating start.  Here we just sketch briefly
haftmann@21192
    27
  how those monads enter the game of Isabelle/HOL.
haftmann@21192
    28
*}
haftmann@21192
    29
haftmann@21192
    30
subsection {* State transformations and combinators *}
haftmann@21192
    31
haftmann@21192
    32
(*<*)
haftmann@21192
    33
typedecl \<alpha>
haftmann@21192
    34
typedecl \<beta>
haftmann@21192
    35
typedecl \<gamma>
haftmann@21192
    36
typedecl \<sigma>
haftmann@21192
    37
typedecl \<sigma>'
haftmann@21192
    38
(*>*)
haftmann@21192
    39
haftmann@21192
    40
text {*
haftmann@21192
    41
  We classify functions operating on states into two categories:
haftmann@21192
    42
haftmann@21192
    43
  \begin{description}
haftmann@21192
    44
    \item[transformations]
haftmann@21192
    45
      with type signature @{typ "\<sigma> \<Rightarrow> \<sigma>'"},
haftmann@21192
    46
      transforming a state.
haftmann@21192
    47
    \item[``yielding'' transformations]
haftmann@21192
    48
      with type signature @{typ "\<sigma> \<Rightarrow> \<alpha> \<times> \<sigma>'"},
haftmann@21192
    49
      ``yielding'' a side result while transforming a state.
haftmann@21192
    50
    \item[queries]
haftmann@21192
    51
      with type signature @{typ "\<sigma> \<Rightarrow> \<alpha>"},
haftmann@21192
    52
      computing a result dependent on a state.
haftmann@21192
    53
  \end{description}
haftmann@21192
    54
haftmann@21192
    55
  By convention we write @{typ "\<sigma>"} for types representing states
haftmann@21192
    56
  and @{typ "\<alpha>"}, @{typ "\<beta>"}, @{typ "\<gamma>"}, @{text "\<dots>"}
haftmann@21192
    57
  for types representing side results.  Type changes due
haftmann@21192
    58
  to transformations are not excluded in our scenario.
haftmann@21192
    59
haftmann@21192
    60
  We aim to assert that values of any state type @{typ "\<sigma>"}
haftmann@21192
    61
  are used in a single-threaded way: after application
haftmann@21192
    62
  of a transformation on a value of type @{typ "\<sigma>"}, the
haftmann@21192
    63
  former value should not be used again.  To achieve this,
haftmann@21192
    64
  we use a set of monad combinators:
haftmann@21192
    65
*}
haftmann@21192
    66
haftmann@21192
    67
definition
haftmann@21192
    68
  mbind :: "('a \<Rightarrow> 'b \<times> 'c) \<Rightarrow> ('b \<Rightarrow> 'c \<Rightarrow> 'd) \<Rightarrow> 'a \<Rightarrow> 'd"
wenzelm@21404
    69
    (infixl ">>=" 60) where
haftmann@21283
    70
  "f >>= g = split g \<circ> f"
wenzelm@21404
    71
wenzelm@21404
    72
definition
haftmann@21192
    73
  fcomp :: "('a \<Rightarrow> 'b) \<Rightarrow> ('b \<Rightarrow> 'c) \<Rightarrow> 'a \<Rightarrow> 'c"
wenzelm@21404
    74
    (infixl ">>" 60) where
haftmann@21283
    75
  "f >> g = g \<circ> f"
wenzelm@21404
    76
wenzelm@21404
    77
definition
wenzelm@21404
    78
  run :: "('a \<Rightarrow> 'b) \<Rightarrow> 'a \<Rightarrow> 'b" where
haftmann@21192
    79
  "run f = f"
haftmann@21192
    80
haftmann@21283
    81
syntax (xsymbols)
haftmann@21192
    82
  mbind :: "('a \<Rightarrow> 'b \<times> 'c) \<Rightarrow> ('b \<Rightarrow> 'c \<Rightarrow> 'd) \<Rightarrow> 'a \<Rightarrow> 'd"
haftmann@21283
    83
    (infixl "\<guillemotright>=" 60)
haftmann@21192
    84
  fcomp :: "('a \<Rightarrow> 'b) \<Rightarrow> ('b \<Rightarrow> 'c) \<Rightarrow> 'a \<Rightarrow> 'c"
haftmann@21283
    85
    (infixl "\<guillemotright>" 60)
haftmann@21192
    86
haftmann@21192
    87
abbreviation (input)
haftmann@21192
    88
  "return \<equiv> Pair"
haftmann@21192
    89
wenzelm@22377
    90
print_ast_translation {*
wenzelm@22377
    91
  [(@{const_syntax "run"}, fn (f::ts) => Syntax.mk_appl f ts)]
wenzelm@22377
    92
*}
haftmann@21835
    93
haftmann@21192
    94
text {*
haftmann@21192
    95
  Given two transformations @{term f} and @{term g}, they
haftmann@21192
    96
  may be directly composed using the @{term "op \<guillemotright>"} combinator,
haftmann@21192
    97
  forming a forward composition: @{prop "(f \<guillemotright> g) s = f (g s)"}.
haftmann@21192
    98
haftmann@21192
    99
  After any yielding transformation, we bind the side result
haftmann@21192
   100
  immediately using a lambda abstraction.  This 
haftmann@21192
   101
  is the purpose of the @{term "op \<guillemotright>="} combinator:
haftmann@21192
   102
  @{prop "(f \<guillemotright>= (\<lambda>x. g)) s = (let (x, s') = f s in g s')"}.
haftmann@21192
   103
haftmann@21192
   104
  For queries, the existing @{term "Let"} is appropriate.
haftmann@21192
   105
haftmann@21192
   106
  Naturally, a computation may yield a side result by pairing
haftmann@21192
   107
  it to the state from the left;  we introduce the
haftmann@21192
   108
  suggestive abbreviation @{term return} for this purpose.
haftmann@21192
   109
haftmann@21192
   110
  The @{const run} ist just a marker.
haftmann@21192
   111
haftmann@21192
   112
  The most crucial distinction to Haskell is that we do
haftmann@21192
   113
  not need to introduce distinguished type constructors
haftmann@21192
   114
  for different kinds of state.  This has two consequences:
haftmann@21192
   115
  \begin{itemize}
haftmann@21192
   116
    \item The monad model does not state anything about
haftmann@21192
   117
       the kind of state; the model for the state is
haftmann@26260
   118
       completely orthogonal and may be
haftmann@26260
   119
       specified completely independently.
haftmann@21192
   120
    \item There is no distinguished type constructor
haftmann@21192
   121
       encapsulating away the state transformation, i.e.~transformations
haftmann@21192
   122
       may be applied directly without using any lifting
haftmann@21192
   123
       or providing and dropping units (``open monad'').
haftmann@21192
   124
    \item The type of states may change due to a transformation.
haftmann@21192
   125
  \end{itemize}
haftmann@21192
   126
*}
haftmann@21192
   127
haftmann@21192
   128
haftmann@21192
   129
subsection {* Obsolete runs *}
haftmann@21192
   130
haftmann@21192
   131
text {*
haftmann@21192
   132
  @{term run} is just a doodle and should not occur nested:
haftmann@21192
   133
*}
haftmann@21192
   134
haftmann@21192
   135
lemma run_simp [simp]:
haftmann@21192
   136
  "\<And>f. run (run f) = run f"
haftmann@21192
   137
  "\<And>f g. run f \<guillemotright>= g = f \<guillemotright>= g"
haftmann@21192
   138
  "\<And>f g. run f \<guillemotright> g = f \<guillemotright> g"
haftmann@21192
   139
  "\<And>f g. f \<guillemotright>= (\<lambda>x. run g) = f \<guillemotright>= (\<lambda>x. g)"
haftmann@21192
   140
  "\<And>f g. f \<guillemotright> run g = f \<guillemotright> g"
haftmann@21192
   141
  "\<And>f. f = run f \<longleftrightarrow> True"
haftmann@21192
   142
  "\<And>f. run f = f \<longleftrightarrow> True"
haftmann@21192
   143
  unfolding run_def by rule+
haftmann@21192
   144
haftmann@21192
   145
subsection {* Monad laws *}
haftmann@21192
   146
haftmann@21192
   147
text {*
haftmann@21192
   148
  The common monadic laws hold and may also be used
haftmann@21192
   149
  as normalization rules for monadic expressions:
haftmann@21192
   150
*}
haftmann@21192
   151
haftmann@21192
   152
lemma
haftmann@21192
   153
  return_mbind [simp]: "return x \<guillemotright>= f = f x"
haftmann@21192
   154
  unfolding mbind_def by (simp add: expand_fun_eq)
haftmann@21192
   155
haftmann@21192
   156
lemma
haftmann@21192
   157
  mbind_return [simp]: "x \<guillemotright>= return = x"
haftmann@21192
   158
  unfolding mbind_def by (simp add: expand_fun_eq split_Pair)
haftmann@21192
   159
haftmann@21192
   160
lemma
haftmann@21418
   161
  id_fcomp [simp]: "id \<guillemotright> f = f"
haftmann@21418
   162
  unfolding fcomp_def by simp
haftmann@21418
   163
haftmann@21418
   164
lemma
haftmann@21418
   165
  fcomp_id [simp]: "f \<guillemotright> id = f"
haftmann@21418
   166
  unfolding fcomp_def by simp
haftmann@21418
   167
haftmann@21418
   168
lemma
haftmann@21192
   169
  mbind_mbind [simp]: "(f \<guillemotright>= g) \<guillemotright>= h = f \<guillemotright>= (\<lambda>x. g x \<guillemotright>= h)"
haftmann@21192
   170
  unfolding mbind_def by (simp add: split_def expand_fun_eq)
haftmann@21192
   171
haftmann@21192
   172
lemma
haftmann@21192
   173
  mbind_fcomp [simp]: "(f \<guillemotright>= g) \<guillemotright> h = f \<guillemotright>= (\<lambda>x. g x \<guillemotright> h)"
haftmann@21192
   174
  unfolding mbind_def fcomp_def by (simp add: split_def expand_fun_eq)
haftmann@21192
   175
haftmann@21192
   176
lemma
haftmann@21192
   177
  fcomp_mbind [simp]: "(f \<guillemotright> g) \<guillemotright>= h = f \<guillemotright> (g \<guillemotright>= h)"
haftmann@21192
   178
  unfolding mbind_def fcomp_def by (simp add: split_def expand_fun_eq)
haftmann@21192
   179
haftmann@21192
   180
lemma
haftmann@21192
   181
  fcomp_fcomp [simp]: "(f \<guillemotright> g) \<guillemotright> h = f \<guillemotright> (g \<guillemotright> h)"
haftmann@21192
   182
  unfolding fcomp_def o_assoc ..
haftmann@21192
   183
haftmann@21418
   184
lemmas monad_simp = run_simp return_mbind mbind_return id_fcomp fcomp_id
haftmann@21192
   185
  mbind_mbind mbind_fcomp fcomp_mbind fcomp_fcomp
haftmann@21192
   186
haftmann@21192
   187
text {*
haftmann@21192
   188
  Evaluation of monadic expressions by force:
haftmann@21192
   189
*}
haftmann@21192
   190
haftmann@21192
   191
lemmas monad_collapse = monad_simp o_apply o_assoc split_Pair split_comp
haftmann@21192
   192
  mbind_def fcomp_def run_def
haftmann@21192
   193
haftmann@26260
   194
subsection {* ML abstract operations *}
haftmann@26260
   195
haftmann@26260
   196
ML {*
haftmann@26260
   197
structure StateMonad =
haftmann@26260
   198
struct
haftmann@26260
   199
haftmann@26260
   200
fun liftT T sT = sT --> HOLogic.mk_prodT (T, sT);
haftmann@26260
   201
fun liftT' sT = sT --> sT;
haftmann@26260
   202
haftmann@26260
   203
fun return T sT x = Const (@{const_name return}, T --> liftT T sT) $ x;
haftmann@26260
   204
haftmann@26260
   205
fun mbind T1 T2 sT f g = Const (@{const_name mbind},
haftmann@26260
   206
  liftT T1 sT --> (T1 --> liftT T2 sT) --> liftT T2 sT) $ f $ g;
haftmann@26260
   207
haftmann@26260
   208
fun run T sT f = Const (@{const_name run}, liftT' (liftT T sT)) $ f;
haftmann@26260
   209
haftmann@26260
   210
end;
haftmann@26260
   211
*}
haftmann@26260
   212
haftmann@26260
   213
haftmann@21192
   214
subsection {* Syntax *}
haftmann@21192
   215
haftmann@21192
   216
text {*
haftmann@21192
   217
  We provide a convenient do-notation for monadic expressions
haftmann@21192
   218
  well-known from Haskell.  @{const Let} is printed
haftmann@21192
   219
  specially in do-expressions.
haftmann@21192
   220
*}
haftmann@21192
   221
haftmann@21192
   222
nonterminals do_expr
haftmann@21192
   223
haftmann@21192
   224
syntax
haftmann@21192
   225
  "_do" :: "do_expr \<Rightarrow> 'a"
haftmann@21192
   226
    ("do _ done" [12] 12)
haftmann@21192
   227
  "_mbind" :: "pttrn \<Rightarrow> 'a \<Rightarrow> do_expr \<Rightarrow> do_expr"
haftmann@21192
   228
    ("_ <- _;// _" [1000, 13, 12] 12)
haftmann@21192
   229
  "_fcomp" :: "'a \<Rightarrow> do_expr \<Rightarrow> do_expr"
haftmann@21192
   230
    ("_;// _" [13, 12] 12)
haftmann@21192
   231
  "_let" :: "pttrn \<Rightarrow> 'a \<Rightarrow> do_expr \<Rightarrow> do_expr"
haftmann@21192
   232
    ("let _ = _;// _" [1000, 13, 12] 12)
haftmann@21192
   233
  "_nil" :: "'a \<Rightarrow> do_expr"
haftmann@21192
   234
    ("_" [12] 12)
haftmann@21192
   235
haftmann@21192
   236
syntax (xsymbols)
haftmann@21192
   237
  "_mbind" :: "pttrn \<Rightarrow> 'a \<Rightarrow> do_expr \<Rightarrow> do_expr"
haftmann@21192
   238
    ("_ \<leftarrow> _;// _" [1000, 13, 12] 12)
haftmann@21192
   239
haftmann@21192
   240
translations
wenzelm@22664
   241
  "_do f" => "CONST run f"
haftmann@21192
   242
  "_mbind x f g" => "f \<guillemotright>= (\<lambda>x. g)"
haftmann@21192
   243
  "_fcomp f g" => "f \<guillemotright> g"
haftmann@24195
   244
  "_let x t f" => "CONST Let t (\<lambda>x. f)"
haftmann@21192
   245
  "_nil f" => "f"
haftmann@21192
   246
haftmann@21192
   247
print_translation {*
haftmann@21192
   248
let
haftmann@24253
   249
  fun dest_abs_eta (Abs (abs as (_, ty, _))) =
haftmann@24253
   250
        let
haftmann@24253
   251
          val (v, t) = Syntax.variant_abs abs;
haftmann@24253
   252
        in ((v, ty), t) end
haftmann@24253
   253
    | dest_abs_eta t =
haftmann@21192
   254
        let
haftmann@24253
   255
          val (v, t) = Syntax.variant_abs ("", dummyT, t $ Bound 0);
haftmann@24253
   256
        in ((v, dummyT), t) end
haftmann@24253
   257
  fun unfold_monad (Const (@{const_syntax mbind}, _) $ f $ g) =
haftmann@24253
   258
        let
haftmann@24253
   259
          val ((v, ty), g') = dest_abs_eta g;
haftmann@24253
   260
        in Const ("_mbind", dummyT) $ Free (v, ty) $ f $ unfold_monad g' end
haftmann@24195
   261
    | unfold_monad (Const (@{const_syntax fcomp}, _) $ f $ g) =
haftmann@24195
   262
        Const ("_fcomp", dummyT) $ f $ unfold_monad g
haftmann@24253
   263
    | unfold_monad (Const (@{const_syntax Let}, _) $ f $ g) =
haftmann@24195
   264
        let
haftmann@24253
   265
          val ((v, ty), g') = dest_abs_eta g;
haftmann@24253
   266
        in Const ("_let", dummyT) $ Free (v, ty) $ f $ unfold_monad g' end
haftmann@24195
   267
    | unfold_monad (Const (@{const_syntax Pair}, _) $ f) =
haftmann@21192
   268
        Const ("return", dummyT) $ f
haftmann@21192
   269
    | unfold_monad f = f;
haftmann@21192
   270
  fun tr' (f::ts) =
haftmann@21192
   271
    list_comb (Const ("_do", dummyT) $ unfold_monad f, ts)
wenzelm@22377
   272
in [(@{const_syntax "run"}, tr')] end;
haftmann@21192
   273
*}
haftmann@21192
   274
haftmann@24195
   275
haftmann@21418
   276
subsection {* Combinators *}
haftmann@21418
   277
haftmann@21418
   278
definition
wenzelm@21601
   279
  lift :: "('a \<Rightarrow> 'b) \<Rightarrow> 'a \<Rightarrow> 'c \<Rightarrow> 'b \<times> 'c" where
haftmann@21418
   280
  "lift f x = return (f x)"
haftmann@21418
   281
haftmann@25765
   282
primrec
haftmann@21418
   283
  list :: "('a \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> 'a list \<Rightarrow> 'b \<Rightarrow> 'b" where
haftmann@21418
   284
  "list f [] = id"
krauss@22492
   285
| "list f (x#xs) = (do f x; list f xs done)"
haftmann@21418
   286
haftmann@25765
   287
primrec
haftmann@25765
   288
  list_yield :: "('a \<Rightarrow> 'b \<Rightarrow> 'c \<times> 'b) \<Rightarrow> 'a list \<Rightarrow> 'b \<Rightarrow> 'c list \<times> 'b" where
haftmann@21418
   289
  "list_yield f [] = return []"
krauss@22492
   290
| "list_yield f (x#xs) = (do y \<leftarrow> f x; ys \<leftarrow> list_yield f xs; return (y#ys) done)"
haftmann@26141
   291
haftmann@26141
   292
definition
haftmann@26260
   293
  collapse :: "('a \<Rightarrow> ('a \<Rightarrow> 'b \<times> 'a) \<times> 'a) \<Rightarrow> 'a \<Rightarrow> 'b \<times> 'a" where
haftmann@26141
   294
  "collapse f = (do g \<leftarrow> f; g done)"
haftmann@26141
   295
haftmann@21418
   296
text {* combinator properties *}
haftmann@21418
   297
haftmann@21418
   298
lemma list_append [simp]:
haftmann@21418
   299
  "list f (xs @ ys) = list f xs \<guillemotright> list f ys"
haftmann@26141
   300
  by (induct xs) (simp_all del: id_apply)
haftmann@21418
   301
haftmann@21418
   302
lemma list_cong [fundef_cong, recdef_cong]:
haftmann@21418
   303
  "\<lbrakk> \<And>x. x \<in> set xs \<Longrightarrow> f x = g x; xs = ys \<rbrakk>
haftmann@21418
   304
    \<Longrightarrow> list f xs = list g ys"
haftmann@25765
   305
proof (induct xs arbitrary: ys)
haftmann@25765
   306
  case Nil then show ?case by simp
haftmann@21418
   307
next
haftmann@25765
   308
  case (Cons x xs)
haftmann@25765
   309
  from Cons have "\<And>y. y \<in> set (x # xs) \<Longrightarrow> f y = g y" by auto
haftmann@21418
   310
  then have "\<And>y. y \<in> set xs \<Longrightarrow> f y = g y" by auto
haftmann@25765
   311
  with Cons have "list f xs = list g xs" by auto
haftmann@25765
   312
  with Cons have "list f (x # xs) = list g (x # xs)" by auto
haftmann@25765
   313
  with Cons show "list f (x # xs) = list g ys" by auto
haftmann@21418
   314
qed
haftmann@21418
   315
haftmann@21418
   316
lemma list_yield_cong [fundef_cong, recdef_cong]:
haftmann@21418
   317
  "\<lbrakk> \<And>x. x \<in> set xs \<Longrightarrow> f x = g x; xs = ys \<rbrakk>
haftmann@21418
   318
    \<Longrightarrow> list_yield f xs = list_yield g ys"
haftmann@25765
   319
proof (induct xs arbitrary: ys)
haftmann@25765
   320
  case Nil then show ?case by simp
haftmann@21418
   321
next
haftmann@25765
   322
  case (Cons x xs)
haftmann@25765
   323
  from Cons have "\<And>y. y \<in> set (x # xs) \<Longrightarrow> f y = g y" by auto
haftmann@21418
   324
  then have "\<And>y. y \<in> set xs \<Longrightarrow> f y = g y" by auto
haftmann@25765
   325
  with Cons have "list_yield f xs = list_yield g xs" by auto
haftmann@25765
   326
  with Cons have "list_yield f (x # xs) = list_yield g (x # xs)" by auto
haftmann@25765
   327
  with Cons show "list_yield f (x # xs) = list_yield g ys" by auto
haftmann@21418
   328
qed
haftmann@21418
   329
haftmann@21418
   330
text {*
haftmann@24195
   331
  For an example, see HOL/ex/Random.thy.
haftmann@21192
   332
*}
haftmann@21192
   333
wenzelm@22664
   334
end