5

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]
4

1 回答 1

6

conj 的行为会根据它添加元素的集合类型而有所不同。在您的第一个示例中,它正在向地图添加元素,并且需要集合中的键和值。在您的 REPL 示例中,它正在向向量添加元素,并且只需要一个值。

swap!进入地图:

(def registry (atom{}))
(let [moments (java.util.Date.)
  right-now (.getTime moments)]                                                 
  (swap! registry conj [:time right-now]))
{:time 1345700872898}  
于 2012-08-23T05:36:26.580 回答