开发者

for clojure vector via parameter

(def andre {:owner "Andre" :type "car" :cur-speed "100" :license-plate "ABC"})
(def blastoise {:owner "Blastoise" :type "truck" :cur-speed "120" :license-plate "XYZ"})
(def car-tax[andre blastoise])
(defn calculate-car-tax [v]
    开发者_开发百科(for [v] (println (v)))
)

(calculate-car-tax(car-tax))

I'm getting this exception: java.lang.IllegalArgumentException: for requires an even number of forms in binding vector (cartax.cl:5)

in this line: (for [v] (println (v))) this v is passed via parameter


You likely want the following

(def andre {:owner "Andre" :type "car" :cur-speed "100" :license-plate "ABC"})
(def blastoise {:owner "Blastoise" :type "truck" :cur-speed "120" :license-plate "XYZ"})
(def car-tax [andre blastoise])
(defn calculate-car-tax [v]
    (for [element v] (println element))
)

(calculate-car-tax car-tax)

You need to use the for macro with a binding. That is you want something to range over your vector. The reason for "even number" is that you can range over multiple vectors at once! Also arguments are best left unparenthesized; that is, make sure to write

(calculate-car-tax car-tax)

and not

(calculate-car-tax(car-tax))

Here is a transcript:

user=> (def andre {:owner "Andre" :type "car" :cur-speed "100" :license-plate "ABC"})
#'user/andre
user=> (def blastoise {:owner "Blastoise" :type "truck" :cur-speed "120" :license-plate "XYZ"})
#'user/blastoise
user=> (def car-tax [andre blastoise])
#'user/car-tax
user=> (defn calculate-car-tax [v]
    (for [element v] (println element))
)
#'user/calculate-car-tax
user=> (calculate-car-tax car-tax)
({:owner Andre, :type car, :cur-speed 100, :license-plate ABC}
{:owner Blastoise, :type truck, :cur-speed 120, :license-plate XYZ}
nil nil)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜