clojurenoir

Repeatedly get random element in clojure


I'm messing around in Clojure specifically the Noir web framework and trying to generate a random grid of tiles.

This is probably pretty bad code but I'm learning! :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)))}])])]))

But this code is throwing a exception:

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

Solution

  • repeatedly takes a function not a body so you need to wrap the bodies in functions:

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