【问题标题】:Clojure range-case macroClojure 范围案例宏
【发布时间】:2011-06-14 13:43:28
【问题描述】:

在 R. Kent Dybvig 所著的《"The Scheme Programming Language, 4th Edition"》一书的第 86 页中,作者为case 语句编写了一个define-syntax(方案宏),该语句接受其条件的范围。我想我会在 Clojure 中尝试这个。

这是结果。

我该如何改进呢?我使用:ii:ie:ei:ee作为范围运算符,表示inclusive-inclusive、inclusive-exclusive、exclusive-inclusive, 和exclusive-exclusive,分别。有更好的选择吗?

我选择扩展为 cond 而不是离散的 if 语句,因为我觉得我将从未来对 cond 宏的任何改进中受益。

(defmacro range-case [target & cases]
  "Compare the target against a set of ranges or constant values and return
   the first one that matches. If none match, and there exists a case with the
   value :else, return that target. Each range consists of a vector containing
   3 terms: a lower bound, an operator, and an upper bound. The operator must
   be one of :ii, :ie, :ei, or :ee, which indicate that the range comparison
   should be inclusive-inclusive, inclusive-exclusive, exclusive-inclusive,
   or exclusive-exclusive, respectively.
   Example:
     (range-case target
                 [0.0 :ie 1.0] :greatly-disagree
                 [1.0 :ie 2.0] :disagree
                 [2.0 :ie 3.0] :neutral
                 [3.0 :ie 4.0] :agree
                 [4.0 :ii 5.0] :strongly-agree
                 42 :the-answer
                 :else :do-not-care)
   expands to
     (cond
       (and (<= 0.0 target) (< target 1.0)) :greatly-disagree
       (and (<= 1.0 target) (< target 2.0)) :disagree
       (and (<= 2.0 target) (< target 3.0)) :neutral
       (and (<= 3.0 target) (< target 4.0)) :agree
       (<= 4.0 target 5.0) :strongly-agree
       (= target 42) :the-answer
       :else :do-not-care)
    Test cases:
      (use '[clojure.test :only (deftest is run-tests)])
      (deftest unit-tests
        (letfn [(test-range-case [target]
                                 (range-case target
                                             [0.0 :ie 1.0] :greatly-disagree
                                             [1.0 :ie 2.0] :disagree
                                             [2.0 :ie 3.0] :neutral
                                             [3.0 :ie 4.0] :agree
                                             [4.0 :ii 5.0] :strongly-agree
                                             42 :the-answer
                                             :else :do-not-care))]
      (is (= (test-range-case 0.0) :greatly-disagree))
      (is (test-range-case 0.5) :greatly-disagree)
      (is (test-range-case 1.0) :disagree)
      (is (test-range-case 1.5) :disagree)
      (is (test-range-case 2.0) :neutral)
      (is (test-range-case 2.5) :neutral)
      (is (test-range-case 3.0) :agree)
      (is (test-range-case 3.5) :agree)
      (is (test-range-case 4.0) :strongly-agree)
      (is (test-range-case 4.5) :strongly-agree)
      (is (test-range-case 5.0) :strongly-agree)
      (is (test-range-case 42) :the-answer)
      (is (test-range-case -1) :do-not-care)))
    (run-tests)"
  `(cond
    ~@(loop [cases cases ret []]
        (cond
         (empty? cases)
         ret

         (odd? (count cases))
         (throw (IllegalArgumentException.
                 (str "no matching clause: " (first cases))))

         (= :else (first cases))
         (recur (drop 2 cases) (conj ret :else (second cases)))

         (vector? (first cases))
         (let [[lower-bound operator upper-bound] (first cases)
               clause (second cases)

               [condition clause]
               (case operator
                     :ii `((<= ~lower-bound ~target ~upper-bound) ~clause)
                     :ie `((and (<= ~lower-bound ~target)
                                (< ~target ~upper-bound)) ~clause)
                     :ei `((and (< ~lower-bound ~target)
                                (<= ~target ~upper-bound)) ~clause)
                     :ee `((< ~lower-bound ~target ~upper-bound) ~clause)
                     (throw (IllegalArgumentException.
                             (str "unknown operator: " operator))))]
           (recur (drop 2 cases) (conj ret condition clause)))

         :else
         (let [[condition clause]
               `[(= ~target ~(first cases)) ~(second cases)]]
           (recur (drop 2 cases) (conj ret condition clause)))))))

更新:这是包含mikerakotarak 建议的更改的修订版本:

(defmacro range-case [target & cases]
  "Compare the target against a set of ranges or constant values and return
   the first one that matches. If none match, and there exists a case with the
   value :else, return that target. Each range consists of a vector containing
   one of the following patterns:
     [upper-bound]                 if this is the first pattern, match any
                                   target <= upper-bound
                                   otherwise, match any target <= previous
                                   upper-bound and <= upper-bound
     [< upper-bound]               if this is the first pattern, match any
                                   target < upper-bound
                                   otherwise, match any target <= previous
                                   upper-bound and < upper-bound
     [lower-bound upper-bound]     match any target where lower-bound <= target
                                   and target <= upper-bound
     [< lower-bound upper-bound]   match any target where lower-bound < target
                                   and target <= upper-bound
     [lower-bound < upper-bound]   match any target where lower-bound <= target
                                   and target < upper-bound
     [< lower-bound < upper-bound] match any target where lower-bound < target
                                   and target < upper-bound
   Example:
     (range-case target
                 [0 < 1] :strongly-disagree
                 [< 2]     :disagree
                 [< 3]     :neutral
                 [< 4]     :agree
                 [5]       :strongly-agree
                 42          :the-answer
                 :else       :do-not-care)
   expands to
     (cond
       (and (<= 0 target) (< target 1)) :strongly-disagree
       (and (<= 1 target) (< target 2)) :disagree
       (and (<= 2 target) (< target 3)) :neutral
       (and (<= 3 target) (< target 4)) :agree
       (<= 4 target 5) :strongly-agree
       (= target 42) :the-answer
       :else :do-not-care)
    Test cases:
      (use '[clojure.test :only (deftest is run-tests)])
      (deftest unit-tests
        (letfn [(test-range-case [target]
                                 (range-case target
                                             [0 < 1] :strongly-disagree
                                             [< 2]   :disagree
                                             [< 3]   :neutral
                                             [< 4]   :agree
                                             [5]     :strongly-agree
                                             42      :the-answer
                                             :else   :do-not-care))]
      (is (= (test-range-case 0) :strongly-disagree))
      (is (= (test-range-case 0.5) :strongly-disagree))
      (is (= (test-range-case 1) :disagree))
      (is (= (test-range-case 1.5) :disagree))
      (is (= (test-range-case 2) :neutral))
      (is (= (test-range-case 2.5) :neutral))
      (is (= (test-range-case 3) :agree))
      (is (= (test-range-case 3.5) :agree))
      (is (= (test-range-case 4) :strongly-agree))
      (is (= (test-range-case 4.5) :strongly-agree))
      (is (= (test-range-case 5) :strongly-agree))
      (is (= (test-range-case 42) :the-answer))
      (is (= (test-range-case -1) :do-not-care))))
    (run-tests)"
  (if (odd? (count cases))
    (throw (IllegalArgumentException. (str "no matching clause: "
                                           (first cases))))
    `(cond
      ~@(loop [cases cases ret [] previous-upper-bound nil]
          (cond
           (empty? cases)
           ret

           (= :else (first cases))
           (recur (drop 2 cases) (conj ret :else (second cases)) nil)

           (vector? (first cases))
           (let [condition (first cases)
                 clause (second cases)

                 [case-expr prev-upper-bound]
                 (let [length (count condition)]
                   (cond
                    (= length 1)
                    (let [upper-bound (first condition)]
                      [(if previous-upper-bound
                         `(and (<= ~previous-upper-bound ~target)
                               (<= ~target ~upper-bound))
                         `(<= ~target ~upper-bound))
                       upper-bound])

                    (= length 2)
                    (if (= '< (first condition))
                      (let [[_ upper-bound] condition]
                        [(if previous-upper-bound
                           `(and (<= ~previous-upper-bound ~target)
                                 (< ~target ~upper-bound))
                           `(< ~target ~upper-bound))
                         upper-bound])
                      (let [[lower-bound upper-bound] condition]
                        [`(and (<= ~lower-bound ~target)
                               (<= ~target ~upper-bound))
                         upper-bound]))

                    (= length 3)
                    (cond
                     (= '< (first condition))
                     (let [[_ lower-bound upper-bound] condition]
                       [`(and (< ~lower-bound ~target)
                              (<= ~target ~upper-bound))
                        upper-bound])

                     (= '< (second condition))
                     (let [[lower-bound _ upper-bound] condition]
                       [`(and (<= ~lower-bound ~target)
                              (< ~target ~upper-bound))
                        upper-bound])

                     :else
                     (throw (IllegalArgumentException. (str "unknown pattern: "
                                                            condition))))

                    (and (= length 4)
                         (= '< (first condition))
                         (= '< (nth condition 3)))
                    (let [[_ lower-bound _ upper-bound] condition]
                      [`(and (< ~lower-bound ~target) (< ~target ~upper-bound))
                       upper-bound])

                    :else
                    (throw (IllegalArgumentException. (str "unknown pattern: "
                                                           condition)))))]
             (recur (drop 2 cases)
                    (conj ret case-expr clause)
                    prev-upper-bound))

           :else
           (let [[condition clause]
                 `[(= ~target ~(first cases)) ~(second cases)]]
             (recur (drop 2 cases) (conj ret condition clause) nil)))))))

【问题讨论】:

    标签: macros clojure case


    【解决方案1】:

    我也会投票赞成稍微冗长但不那么难读的东西。

     (range-case target
       [(<= 0.0) (< 1.0)] :greatly-disagree
       [(<= 1.0) (< 2.0)] :disagree
       [(<= 2.0) (< 3.0)] :neutral
       [(<= 3.0) (< 4.0)] :agree
       (<= 4.0 5.0)       :strongly-agree
       42 :the-answer
       :else :do-not-care)
    

    这可能是一个可行的选择。

    【讨论】:

    • 您的建议,结合 mikera 对“默认”运算符的建议和隐式下限可能会很有用。将进行调查。
    • 也许甚至 [LB UB][LB &lt; UB][&lt; LB UB][&lt; LB &lt; UB] 对于 :ii:ie:ei:ee,分别使用默认运算符是&lt;=
    【解决方案2】:

    一些想法:

    • 为运算符设置一个默认值(例如,“:ie”在典型问题中可能是最自然的)
    • 将其中一个边界默认为上一个或下一个上/下限,这样您就不需要重复相同的边界值。
    • 考虑 ifs 而不是 cond,这样您就可以进行区间二分(如果您预计会有大量案例,这将是一个性能上的赢家)

    另一种方法可能是让您的宏在案例级别工作,如下所示:

    (cond
      (in-range target [0.0 1.0]) :greatly-disagree)
      (in-range target [1.0 2.0]) :disagree)
      ...)
    

    我个人喜欢这样,因为如果需要,您可以将范围测试与其他谓词混合使用。

    【讨论】:

    • @mikera:这和普通的cond 一样冗长:-)。不过,我喜欢你的前两个厘米。我会进一步探索它们。
    • 作为一般原则,我不认为尽量减少冗长是一个特别有用的目标......我会选择可读性、可维护性和一致性,而不是节省一些打字字符:-)
    • @mikera:我同意。我是个聪明人。不过,您对(in-range ...) 的建议应该是另一个宏。它本身就非常有用。
    • @mikera:关于您对隐式下限的建议,在第一个 case 子句中,如果省略下限,它可能(隐式)是 (- Integer/MAX_INTEGER)(实际上没有添加 @ 987654325@ 到不断增长的cond)。我不确定我是否理解您提到的“区间二等分”。
    • @Ralph 区间二等分只是意味着你首先采用中间情况 - 如果目标是例如
    【解决方案3】:

    我最初的看法:

    (defn make-case [test val]
      (if (vector? test)
        `((and ~@(for [[lower comp upper] (partition 3 2 test)]
                   (list comp lower upper)))
          ~val)
    
        (list :else val)))
    
    (defmacro range-case [& cases]
      (let [cases (partition 2 cases)]
        `(cond ~@(mapcat (partial apply make-case) cases))))
    

    这需要稍微改变语法,如下所示:

    (range-case 
     [0.0 <= x < 1.0] :greatly-disagree
     [1.0 <= x < 2.0] :disagree
     [2.0 <= x < 3.0] :neutral
     [3.0 <= x < 4.0] :agree
     [4.0 <= x <= 5.0] :strongly-agree
     [42 = x] :the-answer
     :else :do-not-care)
    

    我的版本可能违反了原始示例的精神,但“优点”包括:

    1. 您没有硬编码为单个 target。您也不限于两个测试(较低的测试和较高的测试)。你可以做[0 &lt; x &lt;= y &lt; 4 &lt;= z] 等等。
    2. 语法更类似于数学比较符号。
    3. Clojure 的比较运算符本身可以作为参数传递;无需使用关键字并将其转换为比较运算符。这样一来,比较运算符就不会被硬编码到函数中,并且移除这个间接层可以让它更好地阅读。
    4. 平等不再是特例。

    缺点?

    1. x 重复了很多次。抓住x 并将其置于顶部是否值得增加复杂性和降低灵活性?
    2. 与您的原始示例一样,它使用中缀表示法。在前缀符号的世界中,这可能有点刺耳。

    再一次,在这一点上,我们的宏所做的只是将方括号更改为括号和and将一堆东西放在一起。所以我怀疑你是否真的需要一个宏。

    (defn ?? [& xs]
      (every? (fn [[lower comp upper]]
                (comp lower upper))
              (partition 3 2 xs)))
    
    (cond
      (?? 0.0 <= x < 1.0) :greatly-disagree
      (?? 1.0 <= x < 2.0) :disagree
      (?? 2.0 <= x < 3.0) :neutral
      (?? 3.0 <= x < 4.0) :agree
      (?? 4.0 <= x <= 5.0) :strongly-agree
      (= 42 x) :the-answer
      :else :do-not-care)
    

    【讨论】:

    • 谢谢。 “所以我怀疑你是否真的需要一个宏。”它更像是一种宏编写练习,而不是真正有用的东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多