Skip to content

Instantly share code, notes, and snippets.

@jaked
Last active December 20, 2015 06:18
Show Gist options
  • Save jaked/6084411 to your computer and use it in GitHub Desktop.
Save jaked/6084411 to your computer and use it in GitHub Desktop.
little Clojure hack to find functions by their behavior, like Smalltalk method finder
(defn find-functions [pred]
(let [pred (fn [fun]
(binding [*out* nil *err* nil clojure.test/*test-out* nil]
(try (pred fun)
(catch Throwable t false))))
excluded #{'clojure.core/read-line 'clojure.main/repl-read}]
(for [ns (all-ns)
[name fun] (ns-publics ns)
:let [sym (symbol (str (ns-name ns)) (str name))]
:when (not (excluded sym))
:when (ifn? fun)
:when (pred fun)]
sym)))
Examples:
user> (find-functions #(= (% "foo") "oof"))
(clojure.string/reverse)
user> (find-functions #(= (% "foo") "FOO"))
(clojure.string/upper-case)
user> (find-functions #(and (% (fn [x] x)) (not (% 17))))
(clojure.test/function? clojure.core/fn? clojure.core/ifn?)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment