Created
January 21, 2012 19:49
-
-
Save sritchie/1653728 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
(ns monad-explore.core | |
(:use clojure.algo.monads)) | |
(defmacro let? | |
"Almost the same as let. If you add the :ensure keyword paired with | |
some predicate as a var in the let form, let? will not continue | |
unless the predicate evaluates to true. (The predicate will have | |
access to all bindings above.)" | |
[bindings & body] | |
(let [[bind [kwd pred & more]] (split-with (complement #{:ensure}) bindings)] | |
`(let [~@bind] | |
~@(cond (and kwd more) [`(when ~pred (let? [~@more] ~@body))] | |
kwd [`(when ~pred ~@body)] | |
:else body)))) | |
(let? [a 2 | |
:ensure (= a 2) | |
b (+ a 2) | |
:ensure (= b 3)] | |
(* a b)) | |
;;=> nil | |
(let? [a 2 | |
:ensure (= a 2) | |
b (+ a 2) | |
:ensure (= b 4)] | |
(* a b)) | |
;;=> 8 | |
;; I know it's the identity monad, I just wanted to get nil when guards failed vs. undefined. | |
(defmonad skip-m | |
[m-result identity | |
m-bind (fn [mv mf] (mf mv)) | |
m-zero nil]) | |
(domonad skip-m | |
[a 2 | |
:when (= a 2) | |
b (+ a 2) | |
:when (= b 3)] | |
(* a b)) | |
;;=> nil | |
(domonad skip-m | |
[a 2 | |
:when (= a 2) | |
b (+ a 2) | |
:when (= b 4)] | |
(* a b)) | |
;;=> 8 | |
;; OR, without defining anything of my own at all.... | |
(domonad maybe-m | |
[a 2 | |
:when (= a 2) | |
b (+ a 2) | |
:when (= b 3)] | |
(* a b)) | |
;;=> nil | |
(domonad maybe-m | |
[a 2 | |
:when (= a 2) | |
b (+ a 2) | |
:when (= b 4)] | |
(* a b)) | |
;;=> 8 |
You could use maybe-m instead of defining your own skip-m.
Pretty cool how a little experience with monads leads to elegant code, isn't it.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Whoops, you're absolutely right. That's what I get for not copy-pasting directly out of the repl. Thanks for the note, the gist should now be correct.