Sunday, December 7, 2008

Clojure

I've been playing a bit with Clojure recently. Playing only: I haven't written anything serious yet. One thing I did write, though, was the Clojure example in Geir Magnusson Jr's Java Mongo driver.

There's a bug somewhere, though: the sample only prints records 1 and 3 out of 3. The Java sample works correctly, as does the JRuby sample. I can't figure out why, because the Clojure code that iterates over the records that are inserted is pretty simple. Here's the code:

(def mongo (org.mongodb.driver.impl.Mongo.))
(def db (.getDB mongo "clojure"))
(def coll (.getCollection db "test"))

(. coll clear)                          ; erase all records in the collection

; insert three records
(dorun (map #(do (.insert coll {"a" (+ % 1)})) (range 0 3)))

; print the number of records in the collection.
(println "There are" (.getCount coll (org.mongodb.driver.MongoSelector.))
  "records in the collection 'test'")

; one way to do a query
(loop [i (.find coll)]
  (when i
    (do (println (first i))
        (recur (rest i)))))

; and another
(dorun (map println (.find coll)))

If you can see what's wrong, please let me know.

No comments: