Skip to content

Instantly share code, notes, and snippets.

@daveray
Created June 24, 2013 16:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daveray/5851508 to your computer and use it in GitHub Desktop.
Save daveray/5851508 to your computer and use it in GitHub Desktop.
DI
(defn lookup
[dep-graph key]
(let [{:keys [deps fn]} (dep-graph key)
context (map (partial lookup dep-graph) deps) ]
(apply fn context)))
;###############################################################################
; Define some functions with deps encoded as metadata
(defn bar*
[a b]
(+ a b))
(defn foo*
[bar x y]
(* (bar x y) (bar x y)))
(defn baz*
[foo bar pi a b]
(str "pi -> " pi ", (foo a b) -> " (foo a b) ", (bar a b) -> " (bar a b)))
;################################################################################
; Map names to functions
(def deps {:bar {:deps []
:fn (fn [] bar*)}
:foo {:deps [:bar]
:fn (fn [bar] (partial foo* bar))}
:pi {:deps [] :fn (constantly 3.14159)}
:baz {:deps [:foo :bar :pi]
:fn (fn [foo bar pi] (partial baz* foo bar pi))}})
; Lookup and call a function
(let [baz (lookup deps :baz)]
(println (baz 1 2)))
;=> pi -> 3.14159 (foo a b) -> 9 , (bar a b) -> 3
; Inject an alternate dependency impl, and call a function
(let [foo (lookup (assoc deps :bar {:deps [] :fn (constantly (constantly 100))})
:foo)]
(println (foo 4 5)))
;=> 10000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment