Skip to content

Instantly share code, notes, and snippets.

@zelinskiy
Created March 13, 2017 16:59
Show Gist options
  • Select an option

  • Save zelinskiy/9188bb7355c54e42a4658aa0db054833 to your computer and use it in GitHub Desktop.

Select an option

Save zelinskiy/9188bb7355c54e42a4658aa0db054833 to your computer and use it in GitHub Desktop.
newtype Cont r a = Cont { runCont :: (a -> r) -> r }
instance Functor (Cont c) where
fmap f (Cont c) = Cont $ \k -> c (\x -> k (f x))
instance Applicative (Cont c) where
Cont cf <*> Cont cx = Cont $ \k -> cf (\fn -> cx (\x -> k (fn x)))
pure x = Cont $ \k -> k x
instance Monad (Cont r) where
return a = Cont ($ a)
f >>= g = Cont $ \k -> runCont f (\a -> runCont (g a) k)
f :: Int -> Cont r Int
f x = Cont $ \c -> c (x * 2)
g :: Int -> Cont r Int
g x = Cont $ \c -> c (x + 10)
h :: Int -> Cont r Int
h x = if x == 5 then f x else g x
compos :: Cont r Int
compos = return 5 >>= g >>= f
finale :: Show a => a -> String
finale x = "Done: " ++ show(x)
main = print $ runCont compos finale
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment