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