我有这段代码。
(defn get-movie [name-movie contents]
(loop [n (count contents) contents contents]
(let [movie (first contents)]
(if (= (:name (first contents)) name-movie)
(movie)
(recur (dec n) (rest contents))))))
我有一系列地图({:id,:name,:price} {} {})。我需要找到地图:我给出的名字(匹配电影)。当我给出
(get-movie "Interstellar" contents)
其中的内容是
({:id 10000 :name "Interstellar" :price 1}{:id 10001 :name "Ouija" :price 2}).
我收到以下异常。 :
clojure.lang.ArityException:传递给args(0)的错误数量:PersistentArrayMap AFn.java:437 clojure.lang.AFn.throwArity AFn.java:35 clojure.lang.AFn.invoke C:\ Users \ Shalima \ Documents \ Textbooks \ Functional Programming \ Programs \ Assignment5.clj:53 file.test / get-movie C:\ Users \ Shalima \ Documents \ Textbooks \ Functional Programming \ Programs \ Assignment5.clj:77 file.test / eval6219
我一直坐在这里已经有一段时间了,仍然无法弄清楚出了什么问题。我在这里做错了什么?
答案 0 :(得分:7)
您正在调用电影(地图),就像一个功能。可以使用用于查找的键来调用映射,但是没有0-arity形式。大概你只是想要返回电影而不是调用它(用括号括起来)。
(defn get-movie [name-movie contents]
(loop [n (count contents) contents contents]
(let [movie (first contents)]
(if (= (:name (first contents)) name-movie)
movie ;; don't invoke
(recur (dec n) (rest contents))))))
这个问题并不重要,但是使用解构编写这个循环的简单方法是:
(defn get-movie [name-movie contents]
(loop [[{n :name :as movie} & movies] contents]
(if (= n name-movie)
movie ;; don't invoke
(recur movies))))
如果你想转向更高阶的序列函数并完全远离低级循环,你可以做类似的事情:
(defn get-movie [name-movie contents]
(first (filter #(= name-movie (:name %)) contents)))