summaryrefslogtreecommitdiff
path: root/guix/monads.scm
diff options
context:
space:
mode:
authorLudovic Courtès <ludo@gnu.org>2015-01-17 18:46:41 +0100
committerLudovic Courtès <ludo@gnu.org>2015-01-17 23:45:48 +0100
commit81a97734e04fa40412b2d44ccfae1b4796257648 (patch)
treedbb6513d891d778c41abe564891466c564721339 /guix/monads.scm
parent5db3719153ccabd192eadaf99b14ad1149172c5b (diff)
downloadgnu-guix-81a97734e04fa40412b2d44ccfae1b4796257648.tar
gnu-guix-81a97734e04fa40412b2d44ccfae1b4796257648.tar.gz
monads: Add the state monad.
* guix/monads.scm (state-return, state-bind, run-with-state, current-state, set-current-state, state-push, state-pop): New procedures. (%state-monad): New variable. * tests/monads.scm (%monads): Add %STATE-MONAD. (%monad-run): Add 'run-with-state'. (values->list): New macro. ("set-current-state", "state-push etc."): New tests.
Diffstat (limited to 'guix/monads.scm')
-rw-r--r--guix/monads.scm65
1 files changed, 64 insertions, 1 deletions
diff --git a/guix/monads.scm b/guix/monads.scm
index 7fec3d5168..f97f4add5d 100644
--- a/guix/monads.scm
+++ b/guix/monads.scm
@@ -46,7 +46,16 @@
anym
;; Concrete monads.
- %identity-monad))
+ %identity-monad
+
+ %state-monad
+ state-return
+ state-bind
+ current-state
+ set-current-state
+ state-push
+ state-pop
+ run-with-state))
;;; Commentary:
;;;
@@ -291,4 +300,58 @@ lifted in MONAD, for which PROC returns true."
(bind identity-bind)
(return identity-return))
+
+;;;
+;;; State monad.
+;;;
+
+(define-inlinable (state-return value)
+ (lambda (state)
+ (values value state)))
+
+(define-inlinable (state-bind mvalue mproc)
+ "Bind MVALUE, a value in the state monad, and pass it to MPROC."
+ (lambda (state)
+ (call-with-values
+ (lambda ()
+ (mvalue state))
+ (lambda (value state)
+ ;; Note: as of Guile 2.0.11, declaring a variable to hold the result
+ ;; of (mproc value) prevents a bit of unfolding/inlining.
+ ((mproc value) state)))))
+
+(define-monad %state-monad
+ (bind state-bind)
+ (return state-return))
+
+(define* (run-with-state mval #:optional (state '()))
+ "Run monadic value MVAL starting with STATE as the initial state. Return
+two values: the resulting value, and the resulting state."
+ (mval state))
+
+(define-inlinable (current-state)
+ "Return the current state as a monadic value."
+ (lambda (state)
+ (values state state)))
+
+(define-inlinable (set-current-state value)
+ "Set the current state to VALUE and return the previous state as a monadic
+value."
+ (lambda (state)
+ (values state value)))
+
+(define (state-pop)
+ "Pop a value from the current state and return it as a monadic value. The
+state is assumed to be a list."
+ (lambda (state)
+ (match state
+ ((head . tail)
+ (values head tail)))))
+
+(define (state-push value)
+ "Push VALUE to the current state, which is assumed to be a list, and return
+the previous state as a monadic value."
+ (lambda (state)
+ (values state (cons value state))))
+
;;; monads.scm end here