Clojure的协议函数可以像普通函数一样可变吗? [英] Can Clojure's protocol functions be variadic like ordinary functions?

查看:130
本文介绍了Clojure的协议函数可以像普通函数一样可变吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用clojure函数,我可以定义:

With clojure functions, I can define:

(defn f [x & xs] (apply some-function x xs))



我试图用协议做同样的事情, p>

I'm attempting to do this same sort of thing with a protocol, e.g.

(defprotocol foo
  (bar [f])
  (baz [f & gs]))

这样编译(至少在REPL中),但是任何实现类型似乎都失败了,baz)方法。这是官方不支持吗?

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.

推荐答案

这是不支持的,因为Stuart Sierra给出的原因。更多细节,& 符号仅在解构上下文中特殊,如 let 或函数参数。正如Stuart所说, defprotocol 不是这样的上下文。

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 like let or function arguments. As Stuart makes clear, defprotocol is not such a context.

& / code>仍然是一个合法符号,所以你定义了一个带有两个函数的协议: bar 接受一个参数,名为 f baz 需要三个名为 f / code>和 gs

But & is still a legal symbol, so you've defined a protocol with two functions: bar takes one argument, named f, and baz takes three, named f, &, and gs.

这篇关于Clojure的协议函数可以像普通函数一样可变吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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