tags:

views:

86

answers:

2

I am having a hard time writing type checks in Clojure. Pleas help me.

  1. How do I write/perform 'char?' in Clojure?
  2. How do I write/perform 'atom?' in Clojure?

  3. How do I know what type an item is in Clojure?
    Can I write (type? an-item)?

+4  A: 

Typically type questions in Clojure come down to asking "what class is this, or what primitive-wrapper-class can contain it." This comes from Clojure's first class treatment of java. Clojure uses java classes instead of introducing its own type system that would require lots or wrappers to convert back and forth from java.

  1. (= Character (class \a))
  2. (symbol? 'asdf) ; not quite what you want but close. see http://clojure.org/reader
  3. (= String (class "asdf"))
Arthur Ulfeldt
Brians anser using instance? is better than using ='s
Arthur Ulfeldt
+3  A: 
user> (instance? Character \c)
true

Character here is java.lang.Character.

The traditional definition of atom?, I think, is "nil, or anything that's not a pair", but this makes no sense in Clojure because Clojure doesn't use cons cells for everything under the sun. We also have vectors and hashmaps and sets etc. One possibility in Clojure is:

(defn atom? [x] (not (coll? x)))
Brian Carper