如何在Clojure中编写monoid协议? [英] How to write monoid protocol in Clojure?

查看:95
本文介绍了如何在Clojure中编写monoid协议?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于显而易见的原因,以下操作无效。

 (defprotocol Monoid 
(mappend [ab])
(mzero []))

mzero 有零个参数,在协议中不允许零参数方法(或没有意义)。在Haskell或Scala中,其中分派是基于类型的而不是基于值的,这不是问题。



什么是正确的方式来概念化和写< > https://github.com/clojure/clojure/blob/89e5dce0fdfec4bc09fa956512af08d8b14004f6/src/clj/clojure/core/reducers.clj#L279\">资源,这是在新的减速器库不是一个procotol,而是一个超载功能。无参数调用是mzero;两个args调用是mappend。



更准确地说, monoid 需要两个参数 - / code>和 ctor ,并返回一个函数,当调用时没有参数,则计算 ctor 当调用两个时,委托 op



这与折叠处理零的一致,for示例 - reduce (fold)将评估被折叠的没有args的函数,如果必要,找到零。



我觉得有点ash愧,显示出那么不寻常的东西,但我不明白你怎么能在clojure做得更好。感谢评论中的解释/教育。


The following does not work, for obvious reasons.

(defprotocol Monoid
  (mappend [a b])
  (mzero []))

mzero has zero arguments, and zero argument methods are not allowed (or do not make sense) in protocols. In Haskell or Scala, where the dispatch is type-based rather than value-based, this is not a problem.

What would be the correct way to conceptualize and write Monoid protocol in Clojure?

解决方案

looking at the source, the way that this is implemented in the new reducers library is not as a procotol but an overloaded function. a no-args call is mzero; two args call is mappend.

more exactly, monoid takes two arguments - op and ctor and returns a function which, when called with no arguments, evaluates ctor, and when called with two, delegates to op.

this is consistent with how zero is handled in a fold, for example - reduce (fold) will evaluate the function being folded with no args to find the zero, if necessary.

i feel a bit ashamed to show something so unexciting, but i don't see how you can do better within clojure. thanks for the explanations/education in the comments.

这篇关于如何在Clojure中编写monoid协议?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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