Enter an error when trying to implement (>> =) a function to create a custom monad transformer

I am trying to create a monad transformer for a future project, but unfortunately my implementation of the Monad typeclasse (→ =) function does not work.

First of all, here is the main implementation of the monad:

newtype Runtime a = R { 
  unR :: State EInfo a
} deriving (Monad)

Here, the Monad typeclasse implementation is done automatically by the GHC (using the language pragma GeneralizedNewtypeDeriving). Monad transformer is defined as follows:

newtype RuntimeT m a = RuntimeT {
  runRuntimeT :: m (Runtime a)
} 

The problem arises because of how I run the function (→ =) for Monad typeclasse:

instance (Monad m) => Monad (RuntimeT m) where
    return a = RuntimeT $ (return . return) a
    x >>= f =  runRuntimeT x >>= id >>= f

As I see it, the first one >>=works in the base monad m. Thus, it runRuntimeT x >>=returns a type value Runtime a(on the right?). Then the following code id >>=should return a type value a. This value is passed to a function of type f f :: (Monad m) => a -> RuntimeT m b.

: f , ( → =). ? , , - .

: :

Core.hs:34:4:
    Occurs check: cannot construct the infinite type: m = RuntimeT m
    When generalising the type(s) for `>>='
    In the instance declaration for `Monad (RuntimeT m)'
Failed, modules loaded: none.

,
.

+3
2

, StateT - , RuntimeT, StateT. Runtime .

newtype RuntimeT m a = R { 
  unR :: StateT EInfo m a
}

type Runtime = RuntimeT Identity

instance Monad m => Monad (RuntimeT m) where
    return = R . return

    (R m) >>= f = R (m >>= unR . f)
+3

StateT s m a s -> m (a, s), m (s -> (a, s)). , s. , StateT?


, am (s -> (a, s)) : >>= ,

m (s -> (a, s))
a -> m (s -> (b, s))

m (s -> (b, s))

"" (.. fmap (const ())) , , a . m , - -— m, .

+4
source

Source: https://habr.com/ru/post/1741653/


All Articles