summaryrefslogtreecommitdiff
path: root/monad/state.scm
blob: 12275d1d8c108cdc03c655e7e65ffdac32244e63 (about) (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
(define-module (monad state)
  #:use-module (monad core)
  #:re-export (with-monad)
  #:export (state-monad run-state
            get put modify))

(define (return x)
  (lambda (state)
    (cons x state)))

(define (>>= m f)
  (lambda (old-state)
    (let ((state-pair (m old-state)))
      ((f (car state-pair)) (cdr state-pair)))))

(define state-monad (make-monad >>= return))

(define (run-state initial-state m)
  (car (m initial-state)))

;; Examine the state at this point in the computation.
(define (get)
  (lambda (s)
    (cons s s)))

;; replace the state
(define (put s)
  (lambda (_)
    (cons #f s)))

;; update the state
(define (modify f)
  (lambda (s)
    (cons #f (f s))))