Search code examples
clojure

Building a map with a list of functions in Clojure


I'm relatively new to Clojure, so I'm having trouble wrapping my mind around how to make the following work.

Starting with a Java method (from the reflect package), I want to extract various properties and end up with a map that looks something like the following:

{ :name "test-method
  :return-type "String"
  :public true
}

Since the logic of building the keys can be rather complex, I'd like to chain a series of functions that take the current map and the method object and either modify the map or return it as is. Something like:

(defn build-public 
[acc method] 
(if (is-public? method) (assoc acc :public true) acc))

Which might be called like:

(make-method-map method [build-public build-return-type build-name])

I've tried a couple of different approaches but can't seem to make it work, any suggestions would be greatly appreciated.


Solution

  • the simple way is to apply every function one by one with reduce:

    user> (defn make-method-map [method fns]
            (reduce (fn [acc f] (f acc method))
                    {} fns))
    #'user/make-method-map-2
    
    user> (defn make-name [acc method]
            (assoc acc :name 123))
    #'user/make-name
    
    user> (defn make-other [acc method]
            (assoc acc :something "ok"))
    #'user/make-other
    
    user> (make-method-map {:a 1 :b 2} [make-name make-other])
    ;;=> {:name 123, :something "ok"}