11

I am trying to get ONLY the docstring of a function in Clojure, nevertheless I have encountered several problems as all the functions that I find actually print the function signature + docstring.

So for example (doc map) will actually print something like.


clojure.core/map

([f coll] [f c1 c2] [f c1 c2 c3] [f c1 c2 c3 & colls])

Returns a lazy sequence consisting of the result of applying f to the ...

I am only interested in getting the docstring not printing it nor having its namespace or arity. What I am looking for is something like (get-doc function-name) which would return a string with

"Returns a lazy sequence consisting of the result of applying f to the ..."

Is this possible in Clojure?

Community
  • 1
  • 1
carocad
  • 455
  • 6
  • 12

2 Answers2

15

You can do this:

(:doc (meta #'map))

map itself is just a symbol, that is, a name. This symbol resolves to a var, which is accessed by the special form #'map. The value of this var is the actual function, and the docstring for the function is stored as metadata on the var.

Therefore, #'map gives you the var (this can also be done using (var map)), meta gives you the metadata for that var, and :doc extracts the docstring.

For more information, have a look at var, metadata, and special forms.

bsvingen
  • 2,699
  • 14
  • 18
  • Hey @bsvingen, your answer is definitely correct :) Thanks a lot, but could you expand on it? I really dont get what var does :/ I was always trying using meta directly but always run into errors. Could you explain it to me please? – carocad Aug 19 '15 at 16:23
  • 1
    yes, I think it is clearer now, Thanks. From what I understand this has to do with the separation in Clojure between identity, name and state, right? So on runtime the symbol is resolved to the actual function and then executed? – carocad Aug 20 '15 at 08:33
4

Based bsvingen's answer we can define a macro which returns the docstring like:

(defmacro docstring [symbol]
  `(:doc (meta (var ~symbol))))

If we specifically want it to be a function, e.g. for use with map, you can write it as

(defn docstring [symbol]
   (:doc (meta (resolve symbol))))
Rovanion
  • 4,382
  • 3
  • 29
  • 49