Any methods for recovering enough laziness to tie the knot in a monad?
Asked Answered
C

1

11

I want to write a slick bit of code (saving me much time to implement otherwise) by tying the knot. It goes roughly like this,

n <- myinstr n x

where in theory, myinstr should run x to get a value, which will become n. myinstr, which runs inside a State monad, will put n into the state, but this doesn't affect x's computation.

I've tried using DoRec and a naiive implementation of mfix,

instance Monad π”ͺ => MonadFix (MyMonad π”ͺ) where
    mfix f = fix (\mx -> mx >>= f)

but things freeze. Are there any methods for fixing my code (or methodologies for designing it correctly the first time) or should I write something more straightforward?

Crescantia answered 5/12, 2011 at 0:41 Comment(0)
S
14

There is no generic way to make an arbitrary monad an instance of MonadFix. The actual code depends on the monad, and it's not even possible for all monads. You can look at the various monads to see how it's done. And if your monad is in fact State there should already be an instance.

Schnapps answered 5/12, 2011 at 3:21 Comment(5)
Interestingly enough, it is well defined for all comonads, but there are strictly fewer of them to worry about. =/ – Unstrung
I wish I could make IO an instance of MonadFix. – Libido
@JohnL Sounds like time travel. :) – Schnapps
@JohnL: I'm quite late to the party here, but IO is already an instance of MonadFix. Did you mean something else? – Vibraharp
@LeventErkok: no, I was just lamenting that it can't be done without various unsatisfying primitives (i.e. unsafe{Perform|Interleave}IO). Or, as augustss helpfully points out, time travel. – Libido

© 2022 - 2024 β€” McMap. All rights reserved.