Clojure范围大小写宏

如何解决Clojure范围大小写宏

| 在R. Kent Dybvig的书“ The Scheme Programming Language,第4版”(第86页)中,作者为接受条件范围的
case
语句写了
define-syntax
(Scheme宏)。我以为我会在Clojure中尝试这个。 这是结果。 我该如何改善?对于范围运算符,我使用
:ii
:ie
:ei
:ee
,表示包含式,包含式,包含式,排除式, 和排他-排他。有更好的选择吗? 我选择扩展为
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)))))))
更新:这是修订版,其中包含了mikera和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,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)
这可能是一个可行的选择。     ,        一些想法: 具有运算符的默认值(例如,“:ie \”在典型问题中可能是最自然的) 将一个边界默认设置为上一个或下一个上/下边界,这样您就无需重复相同的边界值。 考虑ifs而不是cond,以便您可以进行间隔二等分(如果您期望大量案例,那将是性能上的胜利) 一种替代方法是使宏在案例级别下工作,如下所示:
(cond
  (in-range target [0.0 1.0]) :greatly-disagree)
  (in-range target [1.0 2.0]) :disagree)
  ...)
我个人喜欢这样,因为如果需要,您可以将范围测试与其他谓词混合。     ,        我最初的看法:
(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)
我的版本可能违反了原始示例的精神,但是“优点”包括: 您不会硬编码为一个15英镑。您也不限于两个测试(较低的测试和较高的测试)。你可以做
[0 < x <= y < 4 <= z]
等。 语法更类似于数学比较符号。 Clojure的比较运算符可以自己作为参数传递。无需使用关键字并将其转换为比较运算符。这样,比较运算符就不会硬编码到函数中,而删除此间接层会使它的读取效果更好。 平等不再是特例。 劣势?
x
被重复了很多次。抓住ѭ17并将其放在顶部是否值得增加复杂性并降低灵活性? 像您的原始示例一样,它使用中缀表示法。在前缀表示法的世界中,这可能会有些刺耳。 再说一遍,在这一点上,我们的宏所做的不只是将方括号更改为括号并“ 19”将一堆东西放在一起。所以我质疑您是否真的需要一个宏。
(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)
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res