为 Clojure 匿名函数声明虚拟(未使用)参数 [英] Declare dummy (unused) parameters for Clojure anonymous function

查看:37
本文介绍了为 Clojure 匿名函数声明虚拟(未使用)参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如在这个问题的答案 中所解释的,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 需要一个参数,我想测试 foo 带有一个总是返回 true 的谓词.(即,类似于 #(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:

  1. 输入几乎和 fn 变量一样多.
  2. 如果有通用的解决方案,我很感兴趣.

所以要清楚,我正在寻找这样的东西:

so to be clear, I'm looking for something like this:

#[1](true) ;;匿名函数接受一个参数

推荐答案

没有.只需使用 fn.这就是它的用途.

No. Just use fn. That's what it's for.

这篇关于为 Clojure 匿名函数声明虚拟(未使用)参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆