Skip to content

Instantly share code, notes, and snippets.

@cark
Created September 18, 2012 20:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cark/3745638 to your computer and use it in GitHub Desktop.
Save cark/3745638 to your computer and use it in GitHub Desktop.
(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