Skip to content

Commit 839d5b6

Browse files
committed
Merge pull request #20 from vzaliva/StateGame-example
State game example
2 parents 811b3b0 + 4027ca0 commit 839d5b6

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

examples/StateGame.v

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
(* State monad example adapted from https://wiki.haskell.org/State_Monad
2+
3+
Example use of State monad
4+
Passes a string of dictionary {a,b,c}
5+
Game is to produce a number from the string.
6+
By default the game is off, a C toggles the
7+
game on and off. A 'a' gives +1 and a b gives -1.
8+
E.g
9+
'ab' = 0
10+
'ca' = 1
11+
'cabca' = 0
12+
State = game is on or off & current score
13+
= (Bool, Int)
14+
*)
15+
16+
Require Import Coq.ZArith.ZArith_base Coq.Strings.String.
17+
Require Import ExtLib.Data.Monads.StateMonad ExtLib.Structures.Monads.
18+
19+
Section StateGame.
20+
21+
Import MonadNotation.
22+
Local Open Scope Z_scope.
23+
Local Open Scope char_scope.
24+
Local Open Scope monad_scope.
25+
26+
Definition GameValue : Type := Z.
27+
Definition GameState : Type := (prod bool Z).
28+
29+
Variable m : Type -> Type.
30+
Context {Monad_m: Monad m}.
31+
Context {State_m: MonadState GameState m}.
32+
33+
Fixpoint playGame (s: string) {struct s}: m GameValue :=
34+
match s with
35+
| EmptyString =>
36+
v <- get ;;
37+
let '(on, score) := v in ret score
38+
| String x xs =>
39+
v <- get ;;
40+
let '(on, score) := v in
41+
match x, on with
42+
| "a", true => put (on, score + 1)
43+
| "b", true => put (on, score - 1)
44+
| "c", _ => put (negb on, score)
45+
| _, _ => put (on, score)
46+
end ;; playGame xs
47+
end.
48+
49+
Definition startState: GameState := (false, 0).
50+
51+
End StateGame.
52+
53+
Definition main : GameValue :=
54+
(@evalState GameState GameValue (playGame (state GameState) "abcaaacbbcabbab") startState).
55+
56+
(* The following should return '2%Z' *)
57+
Compute main.
58+

0 commit comments

Comments
 (0)