Skip to content

Instantly share code, notes, and snippets.

@aardvarrk
Created November 30, 2012 09:58
Show Gist options
  • Select an option

  • Save aardvarrk/4174875 to your computer and use it in GitHub Desktop.

Select an option

Save aardvarrk/4174875 to your computer and use it in GitHub Desktop.
module Coroutine
( Coroutine(..)
) where
import Prelude hiding (id, (.))
import Control.Applicative
import Control.Arrow
import Control.Category
newtype Coroutine i o = Coroutine { runC :: i -> (o, Coroutine i o) }
instance Functor (Coroutine i) where
fmap f co = Coroutine $ \i ->
let (o, co') = runC co i
in (f o, fmap f co')
instance Applicative (Coroutine i) where
pure x = Coroutine $ const (x, pure x)
cof <*> cox = Coroutine $ \i ->
let (f, cof') = runC cof i
(x, cox') = runC cox i
in (f x, cof' <*> cox')
instance Category Coroutine where
id = Coroutine $ \i -> (i, id)
cof . cog = Coroutine $ \i ->
let (x, cog') = runC cog i
(y, cof') = runC cof x
in (y, cof' . cog')
instance Arrow Coroutine where
arr f = Coroutine $ \i -> (f i, arr f)
first co = Coroutine $ \(a, b) ->
let (c, co') = runC co a
in ((c, b), first co')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment