Why wrapping the Data.Binary.Put monad creates a memory leak?

前端 未结 2 564
夕颜
夕颜 2020-12-18 23:46

I\'m trying to wrap the Data.Binary.Put monad into another so that later I can ask it questions like \"how many bytes it\'s going to write\" or \"what is the current positio

相关标签:
2条回答
  • 2020-12-19 00:26

    Did you tried to make the monad more strict? Eg. try to make the constructors of your datatyp strict / replace them with a newtype.

    I don't know what's the exact problem here, but this is the usual source of leaks.

    PS: And try to remove unnecessary lambdas, for instance:

      ma >>= f = Writer1M $ (write ma) >=> write . f
    
    0 讨论(0)
  • 2020-12-19 00:40

    After poking around for a bit, I found that the problem seems to be the usage of binary's (>>=) to implement (>>). The following addition to the Writer1M monad implementation solves the problem:

      m >> k = Writer1M $ write m >> write k
    

    Whereas this version still leaks memory:

      m >> k = Writer1M $ write m >>= const (write k)
    

    Looking at binary's source, (>>) seems to discard the result of the first monad explicitly. Not sure how exactly this prevents the leak, though. My best theory is that GHC otherwise holds onto the PairS object, and the "a" reference leaks because it never gets looked at.

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