Search code examples
clojure

Is it possible to destructure in case for use in a threading macro?


(def val { :type "bar" })

(-> val
  (case ???
    "bar" "bar type"
    "baz" "baz type"
    "other type"))

I'd like to include a case in a threading macro so I can branch based on one of the keys of val, a hash map. Is this possible?

EDIT: I need to thread val not a key from val as further functions will need the whole of val. I essentially want to branch to a function within the threading macro based on a key of val. But still pass val onward.


Solution

  • Consider using a multimethod dispatch here:

    (defmulti some-operation :type)
    
    (defmethod some-operation "bar"
      [val]
      (println "Bar type!")
      (assoc val :x 42))
    
    (defmethod some-operation "baz"
      [val]
      (println "Baz type!")
      (assoc val :x 100))
    
    (-> {:type "bar"}
        some-operation
        some-other-operation)