Clojure 范围大小写宏

2024-01-02

在书里《Scheme 编程语言,第四版》 http://www.scheme.com/tspl4/,作者:R. Kent Dybvig,第 86 页,作者写了define-syntax(方案宏)对于case接受其条件范围的语句。我想我会在 Clojure 中尝试这个。

这是结果。

我该如何改进这个?我用:ii, :ie, :ei, and :ee对于范围运算符,表示包含-包含、包含-排除、独占-包含, 和独家独家。还有更好的选择吗?

我选择扩展到cond而不是离散的if声明,因为我觉得我将从未来的任何改进中受益cond macro.

(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)))))))

UPDATE:这是包含以下建议的更改的修订版本mikera https://stackoverflow.com/users/214010/mikera and kotarak https://stackoverflow.com/users/198935/kotarak:

(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)))))))

我也会投票支持一些稍微冗长但读起来不那么难看的东西。

 (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)

这可能是一个可行的替代方案。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Clojure 范围大小写宏 的相关文章

随机推荐

  • 获取手机中安装的所有社交媒体应用程序的列表?

    我正在开发一个应用程序 其中列出了用户移动设备中安装的所有应用程序 我检索了所有应用程序并将其列出在回收视图 现在我想将社交媒体应用程序从该列表中分离出来以用于其他目的 有什么办法可以分离社交媒体应用程序吗 我使用下面的代码从手机检索所有应
  • 何时使用 代替

    正如问题所示 如果我想在 HTML 中添加一些文本 那么我应该何时使用 p 我什么时候应该使用 span 您应该记住 HTML 旨在描述它包含的内容 所以 如果你想传达一段话 那就这么做吧 不过 您的比较并不完全正确 更直接的比较是 何时使
  • 有没有办法用带参数的sql脚本运行impala shell?

    有没有办法使用带参数的 SQL 脚本运行 impala shell 例如 impala shell f home john sql load sql dir1 dir2 dir3 data file 我收到错误 错误 无法解析参数 f ho
  • 流浪者警告:连接被拒绝。重试

    测试默认示例 vagrant init hashicorp precise32 vagrant up 我的盒子 视窗8 1 虚拟盒 5 0 2 流浪者1 7 4 Intel i7 4700MQ CPU 似乎具有 Intel 虚拟化技术 VT
  • 无法分配给引用或变量中的 Angular 产品构建错误

    我无法构建我的角度应用程序的产品版本 IDE 控制台中只有此消息 错误无法分配给引用或变量 所以我只有添加这些选项才能构建 aot false buildOptimizer false 但是 即使使用这些选项 应用程序在部署后也会失败 并在
  • 如何直接使用适配器从 AutoCompleteTextView 中删除数据

    I have AutoCompleteTextView which uses to search the value from database On Click of filtered value it s set to the Auto
  • Angular2 中 valueChanges 的空订阅

    我有一个奇怪的情况 如果留空 订阅永远不会触发 这不起作用 this formGroup get unitCount valueChanges do value gt console log value subscribe 当这工作正常时
  • 如何调用无状态小部件的重建?

    Context 我有两个无状态小部件 页面 HomePage and DetailsPage 显然应用程序启动并启动HomePage 用户可以按下一个按钮来导航到DetailsPage with a Navigator pop 按钮导航回到
  • 在 QGraphicsScene 中移动 QGraphicItems 的有效方法

    我正在使用 pyqt5 开发视频播放器 我在场景中使用 QGraphicsVideoItem 在此视频项目之上 我还需要一些在每个新帧上围绕场景移动的多边形 他们跟踪视频中的内容 理想情况下我不想让它们以 30 fps 的速度移动 我进行了
  • 如何将 hibernate-validator 4.3.0.Final 升级到 Glassfish 3.1.2?

    目前 Hibernate Validator 已发布最新版本为 4 3 0 Finalhere http bit ly KPJvw9 我尝试按照以下步骤将其升级到 Glassfish 3 1 2 1 Remove the GLASSFISH
  • 如何在 Bootstrap 3.3.7 中强制使用汉堡菜单,即使是桌面版?

    我的代码看起来与此页面相同 https getbootstrap com docs 3 3 examples navbar https getbootstrap com docs 3 3 examples navbar 当我在手机上打开页面
  • 如何使用IAM角色通过临时凭证访问资源?

    我使用的 AWS IAM 角色允许实例使用临时 API 凭证 访问密钥 密钥和安全令牌 访问某些资源 当我使用此 ruby 脚本测试临时凭据时 它运行没有任何问题 require rubygems require aws sdk AWS c
  • 在Python中使用正则表达式捕获所有连续的全大写单词?

    我正在尝试使用Python中的正则表达式来匹配所有连续的大写单词 短语 鉴于以下情况 text The following words are ALL CAPS The following word is in CAPS 代码将返回 ALL
  • iPad Safari 不触发模糊事件

    我的应用程序中有一个带有 jQ uery 模糊事件处理程序的 html 输入文本元素 textBox blur function console log blur 当我单击文本框外的页面区域时 桌面浏览器会触发此事件 但 iPad Safa
  • 正则表达式删除正文标签属性 (C#)

    任何人都有一个可以从 body 标记中删除属性的正则表达式 例如 回来 看到一个仅删除特定属性的示例也会很有趣 例如 回来 您无法使用正则表达式解析 XHTML https stackoverflow com questions 17323
  • 如何以角度方式制作嵌套表结构?

    SolutionsDetail SolutionId 658 name dk id 1568377327000 groups GroupId 1 requestDetails ReqId 2331
  • setTimeout 但对于给定的时间

    JavaScript 中是否有任何现成的东西 即不通过 插件 可以让我做类似的事情setTimeout 但我不是说应该在多少毫秒内发生某事 而是给它一个日期对象 告诉它何时做某事 setToHappen function alert Wak
  • 从 VBA 调用 Python 脚本 - 不起作用

    我参考了这里给出的答案 如何在Excel VBA上调用Python脚本 https stackoverflow com questions 18135551 how to call python script on excel vba但这对
  • 屏蔽 Polars 数据帧以进行复杂操作

    如果我有一个极坐标数据框并想要执行屏蔽操作 我目前看到两个选项 create data df pl DataFrame 1 2 3 4 5 6 7 8 schema a b lazy create a second dataframe fo
  • Clojure 范围大小写宏

    在书里 Scheme 编程语言 第四版 http www scheme com tspl4 作者 R Kent Dybvig 第 86 页 作者写了define syntax 方案宏 对于case接受其条件范围的语句 我想我会在 Cloju