Question

What is an equivalent data statement for this Haskell type statement:

type CWIO a = CWorld -> (a, CWorld)

...that would allow me to write:

instance Monad CWIO where
    (action1 >>= action2) w0 =
        let (x1, w1) = action1 w0
            (x2, w2) = action2 x1 w1
        in  (x2, w2)
    return a = \world -> (a, world)

where CWorld:

data CWorld = CWorld {
    cin :: String,
    cout :: String
}

I'm working on a quest to "really grok" monads by actually building a "virtual IO monad" that actually works (in its "virtual universe"). Some kind of "understanding/explanation by building/engineering" for the concept of monads because I'm the kind of person that needs to build something from scratch by myself in order to really understand that "something", so I'm going the same route here. The whole code context is here https://gist.github.com/NeuronQ/11119444/adbf0a9d6d17d4231d7ec68f565203f8dd75f702 , but it will probably seem meaningless and "atrocious" to any experienced Haskell programmer.

Was it helpful?

Solution

You want something like

newtype CWIO a = CWIO { unCWIO :: CWorld -> (a, CWorld) }

which will allow you to define the appropriate instances and to use CWIO and unCWIO to move back and forth between wrapped CWIO computations and the unwrapped underlying functions. newtype is a variant of data tailored and optimised for wrappers with a single constructor.

Note that by adopting such a definition for CWIO you will end up with something equivalent to the State monad specialised for a CWorld state.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top