Skip to content

Instantly share code, notes, and snippets.

@noahlz
Created August 22, 2012 06:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noahlz/3422860 to your computer and use it in GitHub Desktop.
Save noahlz/3422860 to your computer and use it in GitHub Desktop.
Exploration of Clojure doc and meta functions
;; See http://stackoverflow.com/questions/12066020/in-clojure-why-i-need-to-write-doc-str-but-meta-str
;; Define a var foo that points to a function
(def foo (with-meta (fn [] (println "bar")) {:doc "prints bar"} ))
;=> #'user/foo
(foo)
;=> bar
;=> nil
;; We see the :doc in our foo metadata...but where's our REPL documentation?
(meta foo)
;=> {:doc "prints bar"}
(doc foo)
;=> -------------------------
;=> user/foo
;=> nil
;=> nil
(doc #'foo)
;=> #<ClassCastException java.lang.ClassCastException: clojure.lang.Cons cannot be cast to clojure.lang.Symbol
;; read metadata from the var "foo" that maps the fn
(meta #'foo)
=> {:ns #<Namespace user>, :name foo, :line 59, :file "REPL"}
(meta (var foo))
=> {:ns #<Namespace user>, :name foo, :line 59, :file "REPL"}
;; Use the metadata reader macro to assign arbitrary metadata to a Var (this is basically what defn does)
(def ^{:doc "prints bar!"} foo foo)
;=> #'user/foo
;; Now we have our documentation without having using defn
(meta #'foo)
;=> {:ns #<Namespace user>, :name foo, :doc "prints bar!", :line 10, :file "REPL"}
(doc foo)
;=> -------------------------
;=> user/foo
;=> prints bar!
;=> nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment