Is it possible to overload Clojure multi-methods on arity?

前端 未结 3 832
借酒劲吻你
借酒劲吻你 2021-02-12 13:35

I have some code that uses multi-methods and would ideally like to overload the function (in this case, multi-function) so that I can pass in a higher order function to help wit

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-12 13:58

    Basically you can dispatch on anything, neither the type nor the number of args has to be consistent..like this:

    (defn- map-classes [an-object]
         (let [cmap 
             {1 :thing
              2  666
              3  "yada"}
        the-class (class an-object)]
        (get cmap an-object the-class)))
    
    (defn- mk-class [& args] (map #(map-classes %) args))
    (defmulti play-thing mk-class )
    (defmethod play-thing [:thing] [v] (= 1 v))
    (defmethod play-thing [666] [v] (= 2 v))
    (defmethod play-thing ["yada" String] [v x] (str x v))
    

    The possibilities are endless

提交回复
热议问题