Skip to content

Instantly share code, notes, and snippets.

@chansey97
Last active March 3, 2021 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chansey97/baf0edf28b2136bf195c317ef8540afb to your computer and use it in GitHub Desktop.
Save chansey97/baf0edf28b2136bf195c317ef8540afb to your computer and use it in GitHub Desktop.
do-notation for maybe monad by `local-eval` and `the-environment `.
;guile 2.2.3
(use-modules (ice-9 local-eval))
(use-modules (ice-9 match))
(use-modules (srfi srfi-9))
(define-record-type Just
(make-Just x)
Just?
(x Just-x))
(define-record-type Nothing
(make-Nothing)
Nothing?)
(define (extends-env env var-name value)
(local-eval
`(let ((,var-name ,value))
(the-environment)) env))
(define (do env binds return)
(match binds
[()
(local-eval return env)]
[((var e) rest-binds ...)
(match (local-eval e env)
[($ Nothing) (make-Nothing)]
[($ Just x) (do (extends-env env var x) rest-binds return)])]))
(define (bigger-than-two n)
(if (> n 2)
(make-Just n)
(make-Nothing)))
(display
(do (the-environment)
(list '[x (bigger-than-two 4)]
'[y (bigger-than-two 5)])
'(make-Just (+ x y))))
(display "\n")
(display
(do (the-environment)
(list '[x (bigger-than-two 1)]
'[y (bigger-than-two 5)])
'(make-Just (+ x y))))
(display "\n")
;; >> #<Just x: 9>
;; >> #<Nothing>
@chansey97
Copy link
Author

Also, there is an online Guile IDE, you can compile and run it.
https://rextester.com/ZIRPE83539

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment