Question

What's a docstring? What's the difference with comments?

Answer

A docstring is a string literal specified in source code that is used, like a comment, to document a specific segment of code. Unlike conventional source code comments, docstrings are not stripped from the source tree when it is parsed, but are retained throughout the runtime of the program. This allows the program to inspect these comments at run time, for instance as an interactive help system. [1]

Clojure lets you add a docstring to a var like this...

(def a "A sample value." 5)
(defn b
  "A simple calculation using `a`."
  [c]
  (+ a c))
(doc a)
; -------------------------
; user/a
; A sample value.

(doc b) ; ------------------------- ; user/b ; ([c]) ; A simple calculation using a.

Docstrings are just metadata on the var...

(meta #'a) ;= {:ns #, :name a, :doc "A sample value.", ;= :line 1, :file "NO_SOURCE_PATH"}

This means that the docstring can also be added by specifying the :doc metadata explicitly, either when the var is defined, or even afterward by altering the var’s metadata:

(def ^{:doc "A sample value."} a 5) (alter-meta! #'a assoc :doc "A dummy value.")

[2]

There's a clojure.repl/find-doc, which searches not just function names but also their docstrings for the given term. [3][4]

[1] https://en.wikipedia.org/wiki/Docstring [2] Emerick's "Clojure Programming", p. 199 [3] Fogus' "The Joy of Clojure", p. 51 [4] http://clojure.github.io/clojure/clojure.repl-api.html#clojure.repl/find-doc

Learn

Author

xavi

Reviews
Last
next

Students 0