Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure error when calling swap! on atom, trying 'conj this-number'

Tags:

clojure

I want a map in an atom that can keep track of times as Unix time stamps.

So, in my main function I have:

(defn -main [& args]
(println "Server is starting")
(def port (Integer/parseInt (first args)))
(def registry (atom {}))
(run-server port who-is-here registry))

And inside of run-server I have a call to add-to-logged-in-registry:

(defn add-to-logged-in-registry
[registry]
(let [moments (Date.)
    right-now (.getTime moments)]
(swap! registry conj right-now)))

This last line gives me this error:

Exception in thread "main" java.lang.IllegalArgumentException: Don't know how to create ISeq from: java.lang.Long at clojure.lang.RT.seqFrom(RT.java:487) at clojure.lang.RT.seq(RT.java:468) at clojure.lang.APersistentMap.cons(APersistentMap.java:39) at clojure.lang.RT.conj(RT.java:544) at clojure.core$conj.invoke(core.clj:83) at clojure.lang.Atom.swap(Atom.java:51) at clojure.core$swap_BANG_.invoke(core.clj:2107) at who_is_logged_in.core$add_to_logged_in_registry.invoke(core.clj:39) at who_is_logged_in.core$listen_and_respond.invoke(core.clj:42) at who_is_logged_in.core$run_server.invoke(core.clj:52) at who_is_logged_in.core$_main.doInvoke(core.clj:76) at clojure.lang.RestFn.applyTo(RestFn.java:137) at who_is_logged_in.core.main(Unknown Source)

What does this mean?

When I try this at the REPL in emacs, this works perfectly:

user>  (def registry (atom []))
#'user/registry

user>   (let [moments (Date.)
    right-now (.getTime moments)]
(swap! registry conj right-now))

[1345698128988]

user>   (let [moments (Date.)
    right-now (.getTime moments)]
(swap! registry conj right-now))

[1345698128988 1345698132472]
like image 944
cerhovice Avatar asked Aug 23 '12 05:08

cerhovice


1 Answers

conj behaves differently depending on the type of collection it is adding elements to. In your first example it is adding elements to a map and needs A key and a value in a collection. In your REPL example it is adding elements to a vector and needs only a single value.

swap!ing into a map:

(def registry (atom{}))
(let [moments (java.util.Date.)
  right-now (.getTime moments)]                                                 
  (swap! registry conj [:time right-now]))
{:time 1345700872898}  
like image 174
Arthur Ulfeldt Avatar answered Nov 16 '22 10:11

Arthur Ulfeldt