Created
September 18, 2012 20:27
-
-
Save cark/3745638 to your computer and use it in GitHub Desktop.
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
(ns cara.type.core) | |
;(declare Nothing Just) | |
(defprotocol PDataType | |
(get-constructors [self])) | |
(defprotocol PConstructor | |
(get-datatype [self])) | |
(declare Maybe) | |
(deftype Nothing [] | |
PConstructor | |
(get-datatype [this] | |
Maybe)) | |
(defprotocol PJust | |
(from-just [this])) | |
(deftype Just [value] | |
PConstructor | |
(get-datatype [this] | |
Maybe) | |
PJust | |
(from-just [this] | |
value)) | |
(def Maybe (reify | |
PDataType | |
(get-constructors [this] | |
[Nothing Just]))) | |
(def nothing (Nothing.)) | |
(defn just [value] | |
(Just. value)) | |
(defn maybe-case* [value nothing-func just-func] | |
(cond (instance? Just value) (just-func (from-just value)) | |
(instance? Nothing value) (nothing-func) | |
:else (throw (Exception. (str value " is not an instance of the Maybe data type"))))) | |
(defn t [] | |
(dotimes [_ 100000] | |
(maybe-case* (just :a) #(str "nothing") #(str "just " %)))) | |
(defprotocol PMonad | |
(return [self value])) | |
(defprotocol PMonadValue | |
(bind [self func])) | |
(def MaybeM | |
(reify PMonad | |
(return [self value] | |
(just value)))) | |
(extend-type Just | |
PMonadValue | |
(bind [self func] (func (from-just self)))) | |
(extend-type Nothing | |
PMonadValue | |
(bind [self func] nothing)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment