How to add a meta / comment to a sequence defined via def in Clojure?

I had to comment on the line below (example from http://en.wikibooks.org/wiki/Clojure_Programming/Examples/Lazy_Fibonacci )

(def fib-seq ;"Implements Fibonacci sequence (starts with 0)." ((fn rfib [ab] (lazy-seq (cons a (rfib b (+ ab))))) 0 1)) 

If I left him, I would get:

 Clojure 1.2.0 java.lang.Exception: Too many arguments to def (Problem1.clj:1) 1:1 user=> 

I can do this with defn . Example (I know, I reinvent the wheel for even? Already defined):

 (defn is-even? [n] "Returns true if the number is even, false otherwise." (== (mod n 2) 0)) Clojure 1.2.0 1:1 user=> (is-even? 3) false 1:2 user=> (is-even? 4) true 1:3 user=> 
+4
source share
3 answers

(def ^{:doc "Implements Fib. sequence lazily."} fibs ...)

(:doc (meta (var fibs)))

; "Implements Fib. sequence lazily."


Just write a macro so you can write (def-with-docs foo "doc" 1) .

 (defmacro def-with-docs [name docstring value] `(def ~(with-meta name {:doc docstring}) ~value)) (def-with-docs fib-seq "Implements Fibbonaci sequence (starts with 0)." ((fn rfib [ab] (lazy-seq (cons a (rfib b (+ ab))))) 0 1)) 

(:doc (meta (var fib-seq)))

; "Implements Fibbonaci sequence (starts with 0)."


Also, note that with your defn example, a docstring must precede the arguments, otherwise it will not be associated with the character metadata.


Alternatively, you can use clojure.contrib.def / defvar .

+4
source

This problem has already been fixed in the new alpha versions for Clojure 1.3, where def supports an additional docstring.

 user> (clojure-version) "1.3.0-alpha3" user> (def answer "the answer to the final question" 42) #'user/answer user> (doc answer) ------------------------- user/answer nil the answer to the final question nil 
+4
source

From http://clojure.org/special_forms#def

(def symbol init?) creates and interns or finds a global var with the symbol name and namespace value of the current namespace.

From http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/defn

(defn name doc-string? attr-map? [params *] body) is the same as (def name (fn [params *] exprs *)) with the addition of any doc string or attrs metadata var.

So, when you write (def fib-seq "your comment" (...)), you are trying to define the fib-seq character with the value "your comment", and clojure complains that there are too many arguments.

0
source

All Articles