1

以下のコードには冗長なコードがたくさんあります。3つのファクトすべてに対して左側で同じ操作を実行しています。右側にも同じletブロックがあります。この冗長性にどのように対処しますか?

(facts "Data is grouped by the given keys."
       (fact "The grouping keys are a subset of the :month/:day keys in data"
             (group-data data :day) => (fn [d]
                                           (let [months (map :day data)
                                                 grouped-by-keys (keys d)]
                                             (subset? (set grouped-by-keys) (set months)))))
       (fact "All the grouping keys are distinct"
             (group-data data :day) => (fn [d]
                                           (let [months (map :day data)
                                                 grouped-by-keys (keys d)]
                                             (apply distinct? grouped-by-keys))))
       (fact "All the distinct keys from data are present in grouping keys"
             (group-data data :day) => (fn [d]
                                           (let [months (map :day data)
                                                 grouped-by-keys (keys d)]
                                             (empty? (difference (set months) (set grouped-by-keys)))))))
4

1 に答える 1

1

マクロは次の場合に役立ちます。

(defmacro day-facts [facts]
  (let [f (fn [[name expr]]
            `(~'fact ~name
                     (~'group-data ~'data :day) ~'=> (fn [~'d]
                                                       (let [~'months (map :day ~'data)
                                                             ~'grouped-by-keys (keys ~'d)]
                                                         ~expr))))]
    `(~'facts "Data is grouped by the given keys."
              ~@(map f facts))))


(day-facts [["The grouping keys are a subset of the :month/:day keys in data" (subset? (set grouped-by-keys) (set months))]
            ["All the grouping keys are distinct" (apply distinct? grouped-by-keys)]
            ["All the distinct keys from data are present in grouping keys" (empty? (difference (set months) (set grouped-by-keys)))]])
于 2013-03-21T04:45:11.963 に答える