Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/main/clojure/clojure/algo/monads.clj
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,17 @@
(m-result '())
(reverse ms)))

(defmonadfn m-lift-fn
"A purely functional replacement for m-lift
((m-lift 2 +) (m-result 5) (m-result 6)) should be equal to
((m-lift-fn +) (m-result 5) (m-result-6))
Note that this is untested"
[f]
(fn [& args]
(m-bind
(m-seq args)
#(m-result (apply f %)))))

(defmonadfn m-map
"'Executes' the sequence of monadic values resulting from mapping
f onto the values xs. f must return a monadic value."
Expand Down
18 changes: 17 additions & 1 deletion src/test/clojure/clojure/algo/test_monads.clj
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
(:use [clojure.test :only (deftest is are run-tests)]
[clojure.algo.monads
:only (with-monad domonad m-lift m-seq m-chain writer-m write
sequence-m maybe-m state-m maybe-t sequence-t)]))
sequence-m maybe-m state-m maybe-t sequence-t m-lift-fn)]))


(deftest domonad-if-then
Expand Down Expand Up @@ -95,6 +95,22 @@
'(0 0 0 1 0 0 1 0 1 2)
(m-plus (range 3) (range 2))
'(0 1 2 0 1))))

(deftest sequence-monad-using-m-lift-fn
(with-monad sequence-m
(are [a b] (= a b)
(domonad [x (range 3) y (range 2)] (+ x y))
'(0 1 1 2 2 3)
(domonad [x (range 5) y (range (+ 1 x)) :when (= (+ x y) 2)] (list x y))
'((1 1) (2 0))
((m-lift-fn #(list %1 %2)) (range 3) (range 2))
'((0 0) (0 1) (1 0) (1 1) (2 0) (2 1))
(m-seq (replicate 3 (range 2)))
'((0 0 0) (0 0 1) (0 1 0) (0 1 1) (1 0 0) (1 0 1) (1 1 0) (1 1 1))
((m-chain (replicate 3 range)) 5)
'(0 0 0 1 0 0 1 0 1 2)
(m-plus (range 3) (range 2))
'(0 1 2 0 1))))

(deftest maybe-monad
(with-monad maybe-m
Expand Down