Skip to content

Instantly share code, notes, and snippets.

@alvaro-cuesta
Created June 27, 2012 19:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alvaro-cuesta/3006297 to your computer and use it in GitHub Desktop.
Save alvaro-cuesta/3006297 to your computer and use it in GitHub Desktop.
Chain of handlers
;; 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