Commits

Meikel Brandmeyer committed d5afe52

Added Reader Monad

* monad/reader.clj: new file

* build.xml: added monad.reader namespace for AOT compilation

  • Participants
  • Parent commits a873e4d

Comments (0)

Files changed (2)

 			<arg value="de.kotka.monad.maybe"/>
 			<arg value="de.kotka.monad.state"/>
 			<arg value="de.kotka.monad.error"/>
+			<arg value="de.kotka.monad.reader"/>
 		</java>
 	</target>
 

File src/de/kotka/monad/reader.clj

+;-
+; Copyright 2008 (c) Meikel Brandmeyer.
+; All rights reserved.
+;
+; Permission is hereby granted, free of charge, to any person obtaining a copy
+; of this software and associated documentation files (the "Software"), to deal
+; in the Software without restriction, including without limitation the rights
+; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+; copies of the Software, and to permit persons to whom the Software is
+; furnished to do so, subject to the following conditions:
+;
+; The above copyright notice and this permission notice shall be included in
+; all copies or substantial portions of the Software.
+;
+; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+; THE SOFTWARE.
+
+(clojure.core/ns de.kotka.monad.reader
+  (:use
+     de.kotka.monad
+     [clojure.contrib.def :only (defvar)]))
+
+(declare Reader)
+
+(derive `Reader `Monad)
+(derive `Reader `MRunnable)
+
+(defvar
+  ask
+  (make-monad `Reader identity)
+  "Returns the current environment when run.")
+
+(defn asks
+  "Returns a monad which applies the given function to the current
+  environment and returns the result."
+  [f]
+  (bind ask (fn [e] (return `Reader (f e)))))
+
+(defn local
+  "Return a new monad which runs the given monad in a modified
+  environment by applying the given function to it, before running
+  the monad."
+  [m f]
+  (make-monad (monad-type m)
+              (fn [e]
+                (run m (f e)))))
+
+(defmethod return `Reader
+  [t x]
+  (make-monad t (fn [_] x)))
+
+(defmethod bind `Reader
+  [m f]
+  (make-monad (monad-type m)
+              (fn [e]
+                (let [x (run m e)]
+                  (run (f x) e)))))