使用Poor Mans Concurrency和continuation / free monads?

时间:2017-03-17 18:03:55

标签: haskell concurrency continuations

我想创建一个带有挂起函数的交错线程,我可以在调用时传递一个函数。

基本延续类型:

data ContT m a = ContT {runContT :: (a -> m a) -> m a}

suspendedFunction :: Int -> ContT Maybe Int
suspendedFunction i = ContT $ \todo -> todo i

calculation :: Int -> Maybe Int --(a -> m a)
calculation i = Just 100

与穷人并发的延续:

data C m a = Atomic (m (C m a)) | Done a

instance Monad m => Monad (C m) where
  (>>=) (Atomic m) f      = Atomic $ (liftM (>>= f) m)
  (>>=) (Done a) f        = f a
  return                  = Done

atomic :: Monad m => m a -> C m a
atomic m = Atomic $ liftM Done m

interleave :: Monad m => C m a -> C m a -> C m a
interleave (Atomic m1) (Atomic m2) = do
  n1 <- atom $ m1
  n2 <- atom $ m2
interleave n1 n2
interleave m1 (Done _)             = m1
interleave (Done _) m2             = m2

runInterleavedThread :: Monad m => C m a -> m a
runInterleavedThread m = m >>= runInterleaved

createSuspendedThread :: Int -> C (ContT Maybe) Int
createSuspendedThread i = atomic $ suspendedFunction i

main = do
 let inter = interleave (createSuspendedThread 1) (createSuspendedThread 2)
 let complete = runContT $ runThreads inter $ calculation

错误:

 "No instance for (Monad (ContT Maybe))
    arising from a use of ‘atomic’"

我在这里遗漏了一些基本的东西,有人可以解决一些问题吗?

0 个答案:

没有答案