-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
identity.cljc
46 lines (36 loc) · 1.44 KB
/
identity.cljc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
(ns monnit.identity
"A pure computation that wraps a single value. Only useful because it
implements [[monnit.core/Functor]] and [[monnit.core/Monad]]."
(:require [monnit.core :as m]))
(defprotocol Identity
"A pure computation that wraps a single value. Only useful because it
implements [[monnit.core/Functor]] and [[monnit.core/Monad]]."
(identity? [self] "Is `self` an [[Identity]]?")
(run-identity [self]
"Extract the contained value. An implementation detail; call [[run]]
instead."))
(extend-protocol Identity
#?(:clj Object, :cljs default)
(identity? [_] false)
(run-identity [self]
(assert false (str "run-identity called on non-Identity value " self)))
nil
(identity? [_] false)
(run-identity [self] (assert false "run-identity called on nil")))
(deftype Pure [v]
Identity
(identity? [_] true)
(run-identity [_] v)
m/Functor
(-fmap [_ f] (Pure. (f v)))
(-fmap [_ f b] (Pure. (f v (.-v ^Pure b))))
(-fmap [_ f b c] (Pure. (f v (.-v ^Pure b) (.-v ^Pure c))))
(-fmap [_ f b c d] (Pure. (f v (.-v ^Pure b) (.-v ^Pure c) (.-v ^Pure d))))
(-fmap [_ f b c d args]
(Pure. (apply f v (.-v ^Pure b) (.-v ^Pure c) (.-v ^Pure d)
(map (fn [^Pure arg] (.-v arg)) args))))
m/Monad
(bind [_ f] (f v)))
(def ^{:arglists '([v])} pure "Wrap `v` in an [[Identity]]." ->Pure)
(defmethod m/pure Identity [_ v] (pure v))
(def ^{:arglists '([id])} run "Extract the value contained in `id`." run-identity)