Clojure 的协议函数可以像普通函数一样是可变参数吗?
使用 clojure 函数,我可以定义:
(defn f [x & xs] (apply some-function x xs))
我正在尝试使用协议做同样的事情,例如,
(defprotocol foo
(bar [f])
(baz [f & gs]))
这可以编译(至少在 REPL 中),但任何实现类型似乎都在此(可变参数、baz)方法上失败。官方不支持这个吗?我查阅过的消息来源都保持沉默。
With clojure functions, I can define:
(defn f [x & xs] (apply some-function x xs))
I'm attempting to do this same sort of thing with a protocol, e.g.
(defprotocol foo
(bar [f])
(baz [f & gs]))
This compiles (at least in the REPL), but any implementing type seems to fail on this (the variadic, baz) method. Is this officially not supported? The sources that I've consulted are silent.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于 Stuart Sierra 给出的原因,这不受支持。更详细地说,
&
符号仅在像let
或函数参数这样的解构上下文中是特殊的。正如 Stuart 所明确指出的,defprotocol 并不是这样的上下文。但
&
仍然是一个合法的符号,因此您定义了一个具有两个函数的协议:bar
接受一个名为f
的参数,并且baz
包含三个,分别命名为f
、&
和gs
。This is not supported, for the reasons Stuart Sierra gives. To go into a little more detail, the
&
symbol is special only in a destructuring context likelet
or function arguments. As Stuart makes clear,defprotocol
is not such a context.But
&
is still a legal symbol, so you've defined a protocol with two functions:bar
takes one argument, namedf
, andbaz
takes three, namedf
,&
, andgs
.正如 Stuart Sierra 在以下线程中的回答,可变参数方法不是不支持,将来可能也不会支持
As answered Stuart Sierra in following thread, variadic methods aren't supported, and possibly will not supported in the future