Created
June 27, 2012 19:39
-
-
Save alvaro-cuesta/3006297 to your computer and use it in GitHub Desktop.
Chain of handlers
This file contains hidden or 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
;; raek's idea | |
(defn cool? [w] | |
true) ;; all words are cool | |
(def handlers | |
[[#(and (:small-word %) | |
(:first-word %)) #(.toUpperCase %)] | |
; you can even use functions as your predicate | |
[cool? #(.toLowerCase %)]]) | |
(defn chain [handlers [word tags]] | |
(loop [h handlers] | |
(if (empty? h) | |
word | |
(let [[pred? action] (first h)] | |
(if (pred? tags) | |
(action word) | |
(recur (rest h))))))) | |
(chain handlers | |
["hello" {:small-word true | |
:first-word true}]) | |
;; user=> "HELLO" | |
(map (partial chain handlers) | |
[["hello" {:small-word true | |
:first-word true}] | |
["wOrLd" {}]]) | |
;; user=> ("HELLO" "world") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment