在clojure中反复获取随机元素

时间:2014-01-21 07:33:02

标签: clojure noir

我在Clojure特别是Noir网络框架中乱搞并试图生成一个随机的网格网格。

这可能是非常糟糕的代码,但我正在学习! :d

(def tiles [:stairs :stone :monster]) 

(defpage "/" []
     (common/layout
       [:div {:class "level"}
        (repeatedly 10 [:div {:class "row"}
          (repeatedly 10
            [:div {:class (str "tile " (name (rand-nth tiles)))}])])]))

但是这段代码抛出异常:

Wrong number of args (0) passed to: PersistentVector - (class clojure.lang.ArityException)

3 个答案:

答案 0 :(得分:5)

repeatedly使用函数而不是函数,因此需要将函数包装在函数中:

(repeatedly 10 (fn []
                 [:div
                 {:class "row"}
                 (repeatedly 10 (fn []
                                  [:div {:class (str "tile " (name (rand-nth tiles)))}]))]))

答案 1 :(得分:4)

答案:

user=> (repeatedly 10 (fn [] [:div]))
([:div] [:div] [:div] [:div] [:div] [:div] [:div] [:div] [:div] [:div])


user=> (repeatedly 10 [:div])    
ArityException Wrong number of args (0) passed to: PersistentVector  clojure.lang.AFn.throwArity (AFn.java:437)


user=> (doc repeatedly)
-------------------------
clojure.core/repeatedly
([f] [n f])
  Takes a function of no args, presumably with side effects, and
  returns an infinite (or length n if supplied) lazy sequence of calls
  to it
nil
user=>

答案 2 :(得分:1)

(def tiles [:stairs :stone :monster]) 

(defpage "/" []
     (common/layout
       [:div {:class "level"}
        (repeatedly 10 (fn []
                 [:div
                 {:class "row"}
                 (repeatedly 10 (fn []
                                  [:div {:class (str "tile " (name (rand-nth tiles)))}]))]))