Continuation monad for a yield/await function in Haskell

故事扮演 提交于 2019-11-29 14:53:18
Petr Pudlák

You could extend your automaton in the spirit of Conduit, that is, allow it to exit and return a value on finitely many inputs:

data Auto i o a
    = Step (i -> (o, Auto i o a))
    | End a

Then you can define a monad instance that concatenates two automata using >>=: When the first one finishes, the second one continues.

The good news is that you don't need to implement it yourself. Returning a value or nesting using a functor is exactly what the free monad does (see its haddock docs). So let's define

{-# LANGUAGE DeriveFunctor #-}
import Control.Monad.Free
import Data.Void

-- | A functor describing one step of the automaton
newtype AutoF i o t = AutoF (i -> (o, t))
  deriving (Functor)

Then the original Auto type can be defined just as an alias:

type Auto i o = Free (AutoF i o)

This automatically gives you all the instances of Free, and you can also define your original functions:

-- | If @a@ is 'Void', the machine runs forever:
runAuto :: Auto i o Void -> i -> (o, Auto i o Void)
runAuto (Pure v)  _         = absurd v
runAuto (Free (AutoF f)) i  = f i

yield :: o -> Auto i o ()
yield x = liftF (AutoF $ \_ -> (x, ()))

Note that using the same functor with FreeT you get the corresponding monad transformer:

import Control.Monad.Trans.Free

type AutoT i o = FreeT (AutoF i o)

yieldT :: (Monad m) => o -> AutoT i o m ()
yieldT x = liftF (AutoF $ \_ -> (x, ()))

...

That type is a Mealy machine. See https://hackage.haskell.org/package/machines-0.5.1/docs/Data-Machine-Mealy.html for a bunch of instances - but note that the Monad instance is always going to be slow, because it's required to diagonalize by the monad laws.

It sounds like what you really want is the auto package anyway.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!