Monad to also measure side effects

前端 未结 1 734
不知归路
不知归路 2021-01-20 15:11

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 encapsulat

相关标签:
1条回答
  • 2021-01-20 15:48

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

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

    0 讨论(0)
提交回复
热议问题