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

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

问题描述

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

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]))

这可以编译(至少在 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.

但是 & 仍然是一个合法的符号,所以你定义了一个具有两个函数的协议: bar 接受一个参数,名为 fbaz 取三个,分别命名为 f&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天全站免登陆