0

我有这段代码。

(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} {} {})。我需要找到我给出的 :name 的地图(匹配电影)。当我给

(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

我已经坐了一段时间了,但仍然无法弄清楚出了什么问题。我在这里做错了什么?

4

1 回答 1

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)))
于 2014-11-11T05:25:52.227 回答