在 'rest arguments' 读取器宏之后带有 'discard' 宏的 Clojure 函数文字

标签 clojure reader-macro

我想要 Clojure 中的函数文字,它可以接受任意数量的参数,但实际上并不使用它们。所以我发现了 %& ('rest arg' 用于函数文字)和 #_ (“丢弃”读卡器宏)。

但它们如何协同工作让我感到惊讶:

=> (macroexpand `#(... #_ %&))
(fn* [& rest__125459__125460__auto__] (...))

这看起来像我想要的(并且似乎最终有效),但是丢弃宏应该如何工作?文档 says :

The form following #_ is completely skipped by the reader.



但显然这里忽略了 %& form 有一个副作用,即它会影响函数文字 args 列表。我应该依赖这种行为还是它看起来更像是一个错误?

最佳答案

丢弃读取器宏 #_不打算单独使用。在这里你可以看到它的实际效果:

前:

(println "first")
(do
  (print "second ")
  (dotimes [i 5]
    (print i " "))
  (newline))
(println "third")

first
second 0  1  2  3  4  
third

之后:
(println "first")
#_(do
    (print "second ")
    (dotimes [i 5]
      (print i " "))
    (newline))
(println "third")

first
third

所以添加 #_ (递归地)丢弃它所应用到的表单中的所有内容。

关于忽略参数的原始问题,您有几个选择:
(mapv  #(do %& 42)        (range 3)) => [42 42 42]
(mapv   (fn [& _]   42)   (range 3)) => [42 42 42]
(mapv   (constantly 42)   (range 3)) => [42 42 42]

关于在 'rest arguments' 读取器宏之后带有 'discard' 宏的 Clojure 函数文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42840202/

相关文章:

common-lisp - 如何强制 Common Lisp 将数字视为符号名称?

lisp - 为什么阅读器宏扩展不传播到运行时(读取)?

lisp - .sbclrc 中的运算符 #+ 和 #-

java - JVM 在旧代为 'empty' 时运行旧代垃圾回收

scala - 生产级数据存储的功能语言实现

clojure - 协议(protocol)继承

clojure - 为什么 Clojure 缺少用户定义的读取器宏?

java - 将 Java 概念转换为 Clojure

clojure lein(读取行)stdin 问题