Search code examples
clojure

Defining atom? in clojure


Common Lisp has an atom predicate, but Clojure doesn't seem to have an equivalent - atom in Clojure is a completely different thing.

In ANSI Common Lisp, Paul Graham defines it as (not (consp x)).

Would (not (coll? x)) be the correct implementation?

I'm not very used to the collection abstraction yet.

Edit:

I'd need this predicate for a function to copy a tree, for example:

(defn our-copy-tree
  [tr]
  (if-not (coll? tr)
    tr
    (cons (our-copy-tree (first tr))
          (our-copy-tree (rest tr)))))

Is this right?


Solution

  • Yeah, so it turns out coll? would not be the Clojure equivalent to Common Lisp consp.

    The reason is that the empty list () is a coll, so I was getting a stack overflow - while with CL (consp '()); => false).

    The right answer is also to check if the tr is empty, thusly:

    (defn our-copy-tree
      [tr]
      (if (or (not (coll? tr)) (empty? tr))
        tr
        (cons (our-copy-tree (first tr))
              (our-copy-tree (rest tr)))))