我在一本书(Scala和Clojure中的函数式编程模式)中找到了以下代码。 for语句使用close-zip?过滤掉拉链外的人,然后它会给剩下的人带来问候。但是,我不太确定人们应该如何看待generate-greetings
和print-greetings
函数的论点?
(def close-zip? #{19123 19103})
(defn generate-greetings [people]
(for [{:keys [name address]} people :when (close-zip? (address :zip-code))]
(str "Hello, " name ", and welcome to the Lambda Bar And Grille!")))
(defn print-greetings [people]
(doseq [{:keys [name address]} people :when (close-zip? (address :zip-code))]
(println (str "Hello, " name ", and welcome to the Lambda Bar And Grille!"))))
答案 0 :(得分:2)
他们需要使用:name
和:address
键映射,例如:
{:name "A Person", :address {:zip-code 19103}}
for
将从people
中获取每个元素并将每个元素分配给{:keys [name address]}
。这称为destructuring,这只是一种便利。这跟说:
(for [person people
:let [name (:name person)
address (:address person)]
:when (close-zip? (:zip-code address))]
(str ...))