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
We can implement Maybe monad in Lisp as following:
This code works in Racket, but as you see, it doesn't look nice. Haskell solves this problem by do-notation, but Lisp has no do-notation by default. One way to implement do-notation in Lisp is by macros, but I don't want to use macro here.
There is an alternative of Lisp macros, called FEXPRs, see https://en.wikipedia.org/wiki/Macro_(computer_science)#Early_Lisp_macros
More information, see https://en.wikipedia.org/wiki/Fexpr and http://lambda-the-ultimate.org/node/4093
Note that the code only works in Guile, because Guile support "first-class-environment":
Racket does not support "first-class-environment", the namespaces of Racket are "environment-like" but contain only top-level variables.