声明Clojure匿名函数的虚拟(未使用)参数 [英] Declare dummy (unused) parameters for Clojure anonymous function
问题描述
也如该问题的答案中所述,Clojure通过主体中引用的最大参数索引(例如,如果最大引用的参数为%4
,则该匿名函数具有4个值)来确定匿名函数的参数数量(通过#()
定义).参数).
As also explained in the answers of this question, Clojure determines the number of parameters of an anonymous function (defined through #()
), by the maximal parameter index referenced in the body (e.g. if the maximal referenced parameter is %4
, then that anonymous function has 4 parameters).
问题:是否有一些语法告诉Clojure编译器匿名函数需要一个参数,甚至没有引用该参数?或者,在这种情况下,唯一的干净方法" *是使用 fn语法? (*干净的方式":我知道在大多数情况下,您可以引用哑参数而不影响功能-参见下文,但我想避免此类解决方法.)
Question: is there some syntax to tell the Clojure compiler that an anonymous function expects one parameter, even not referencing that parameter? Or, in this case, the only "clean way"* is to use the fn syntax? (* "Clean way": I'm aware that in most cases, you could reference the dummy parameter without affecting the function -- see below, but I would like to avoid such workarounds.)
我的用例:我有一个函数(defn foo [predicate])
,其中predicate
恰好期望一个参数,并且我想用始终返回true
的谓词测试foo
. (即类似#(true)
的东西.)这会导致产生ArityException
,因为解释器认为#(true)
期望参数为零.
My use case: I have a function (defn foo [predicate])
, where predicate
expects exactly one argument, and I would like to test foo
with a predicate that always returns true
. (I.e., something like #(true)
.) This causes an ArityException
since the interpreter thinks that #(true)
expects zero arguments.
在这种情况下,我可以使用诸如#(or true %)
这样的聪明技巧,但是:
In this particular case, I could use some clever hack like #(or true %)
, but:
- 键入的内容几乎与
fn
变体相同. - 我对是否有通用解决方案感兴趣.
- It is almost as much to type as the
fn
-variant. - I'm interested if there is a generic solution.
为清楚起见,我正在寻找类似这样的内容:
so to be clear, I'm looking for something like this:
#[1](true) ;; the anonymous function takes one parameter
推荐答案
否.只需使用fn
.那就是它的目的.
No. Just use fn
. That's what it's for.
这篇关于声明Clojure匿名函数的虚拟(未使用)参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!