Last active
March 3, 2021 16:46
-
-
Save chansey97/baf0edf28b2136bf195c317ef8540afb to your computer and use it in GitHub Desktop.
do-notation for maybe monad by `local-eval` and `the-environment `.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also, there is an online Guile IDE, you can compile and run it.
https://rextester.com/ZIRPE83539