序列理解得到运行

时间:2015-05-20 03:14:04

标签: clojure

我在一本书(Scala和Clojure中的函数式编程模式)中找到了以下代码。 for语句使用close-zip?过滤掉拉链外的人,然后它会给剩下的人带来问候。但是,我不太确定人们应该如何看待generate-greetingsprint-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!"))))

1 个答案:

答案 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 ...))