用于 Clojure 中的标识 monad
我一直在阅读 优秀的介绍为 Clojure 程序员提供 monad。本文说明了 Identity monad 在功能上等同于 Clojure 的 let,并且 Sequence/List monad 等同于 for。
当文章谈到 monad 转换器时,它展示了一个结合 Maybe 和 Sequence monad 的示例。好的,所以使用 Sequence monad 而不是 for 的原因之一是我可以转换它。然而,转换一个 Identity monad 对我来说没有意义——这不是总是等同于构建任何转换的 monad 吗?例如,如果我用 Identity 转换 Maybe - 这不是给了我一个 Maybe,这会更容易直接声明吗?
有人可以澄清一下在 Clojure 中选择 Identity monad 而不是 let 是否有实际用途(也许我没有完全考虑 Transformer 的含义?) ,或者只是为了理论完整性?
I've been reading an excellent introduction to monads for Clojure programmers. The article illustrates that the Identity monad is functionally equivalent to Clojure's let and that the Sequence/List monad is equivalent to for.
When the article gets to monad transformers, it shows an example combining the Maybe and Sequence monads. Ok, so one reason for using a Sequence monad instead of a for is that I can transform it. However, transforming an Identity monad doesn't make sense to me - wouldn't that always be equivalent to just building up whatever the transforming monad is? For example, if I transformed Maybe with Identity - doesn't that just give me a Maybe, which would have been easier to declare directly?
Can someone clear up whether there's a practical use in Clojure for choosing an Identity monad over a let (perhaps I'm not thinking all the way through the implications of transformers?), or is it just there for theoretical completeness?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
事实上,identity monad 作为 monad 转换器的基础非常有用。例如,maybe monad 转换器 (maybe-t) 允许除 nil 之外的任何值:
请注意,使用 Maybe-m 作为基本 monad 会在 :fail 和 nil 上进行快捷操作,而不仅仅是 :fail。
Indeed the identity monad is very useful as a base in a monad transformer. For instance the maybe monad transformer (maybe-t) allows for a nothing value other than nil:
Note that using maybe-m as the base monad would shortcut on both :fail and nil, instead of just :fail.
一个很好的理由是,您可以编写不与特定 monad 绑定的 monadic 函数,然后在
with-monad
块中执行它们。如果您编写(with-monad Identity-m ...)
,identity-m
可以让您选择不涉及任何特殊的 Monadic voodoo。(显然,如果您的单子函数本质上使用了其所使用的单子的某些属性,例如状态的 getter 和 setter 的可用性等,那么这将不起作用。但是,并非所有单子函数都是这样的。)
One good reason is that you can write monadic functions which are not tied to a particular monad and then execute them in a
with-monad
block.identity-m
gives you the option of not involving any special monadic voodoo if you write(with-monad identity-m ...)
.(Clearly, this won't work if your monadic function makes essential use of some properties of the monad its working with, like the availability of a getter and a setter for state etc. Not all monadic functions are like this, however.)