Monad还可以测量副作用 [英] Monad to also measure side effects

查看:70
本文介绍了Monad还可以测量副作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何计算将绑定应用于Monad的次数-给出状态monad的示例,我想计算状态更改的次数.我如何最好地封装它?该逻辑应该是绑定运算符的一部分(由于它增加计数会产生副作用)还是有更好的方法呢?

How can I count the number of times bind is applied on a Monad - Example given a state monad, I'd like to count the number of times state changed. How can i best encapsulate this? Should this logic be part of bind operator (with side effect since it increments count) or is there a better way of doing it?

推荐答案

您不能.单子法则之一是

You can't. One of the monad laws is

return x >>= f = f x

在左边有一个绑定,在右边没有一个绑定,因此没有一个守法的单子可以观察到有多少绑定.

which has one bind on the left and none on the right, so no law-abiding monad can observe how many bindings there are.

充其量您可能会采取行动

At best you may have an action

increment :: M ()

在您的monad中,它会反击. (正如您所说,可以使用StateT或类似方法,或者通过其他两种基本同构的方法来实现.)

in your monad which bumps a counter. (This could be implemented, as you say, using StateT or similar, or in a couple other essentially isomorphic ways.)

这篇关于Monad还可以测量副作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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