Clojure multimethod dispatching on functions and values

Posted by Josh Glover on Stack Overflow See other posts from Stack Overflow or by Josh Glover
Published on 2013-10-25T15:39:45Z Indexed on 2013/10/25 15:54 UTC
Read the original article Hit count: 171

Filed under:

I have a function that returns the indexes in seq s at which value v exists:

(defn indexes-of [v s]
  (map first (filter #(= v (last %)) (zipmap (range) s))))

What I'd like to do is extend this to apply any arbitrary function for the existence test. My idea is to use a multimethod, but I'm not sure exactly how to detect a function. I want to do this:

(defmulti indexes-of ???)
(defmethod indexes-of ??? [v s]  ;; v is a function
  (map first (filter v (zipmap (range) s))))
(defmethod indexes-of ??? [v s]  ;; v is not a function
  (indexes-of #(= v %) s))

Is a multimethod the way to go here? If so, how can I accomplish what I'm trying to do?

© Stack Overflow or respective owner

Related posts about clojure