2

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)
Kristjan Oddsson
  • 343
  • 3
  • 18

3 Answers3

5

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)))}]))]))
ponzao
  • 20,684
  • 3
  • 41
  • 58
  • 1
    Ahh, I was missing the [] when trying the fn before. I must say that I was hoping that Clojure/Noir handled this in a prettier way :> Thanks! – Kristjan Oddsson Jan 21 '14 at 17:07
  • @KristjanOddsson, no problem! I actually find it quite nice that Clojure doesn't try to be too clever here (as it usually doesn't), you just pass functions to functions. – ponzao Jan 21 '14 at 19:18
4

Answer:

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=>
llj098
  • 1,404
  • 11
  • 13
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)))}]))]))
lao-xeim
  • 21
  • 1