diff --git a/continuations.ipynb b/continuations.ipynb new file mode 100644 index 0000000..554fa14 --- /dev/null +++ b/continuations.ipynb @@ -0,0 +1,174 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "(>>-) :: forall r a. MCont r a -> (a -> r) -> r" + ], + "text/plain": [ + "(>>-) :: forall r a. MCont r a -> (a -> r) -> r" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "newtype MCont r a = MCont { (>>-) :: (a -> r) -> r }\n", + "\n", + ":t (>>-)\n", + "\n", + "instance Functor (MCont r) where\n", + " fmap f cra = MCont $ \\k -> cra >>- \\a -> k (f a)\n", + " \n", + "instance Applicative (MCont r) where\n", + " pure a = MCont $ \\aTor -> aTor a\n", + " cf <*> cx = MCont $ \\bTor ->\n", + " cx >>- \\a ->\n", + " cf >>- \\f ->\n", + " bTor (f a)\n", + " \n", + "instance Monad (MCont r) where\n", + " return = pure\n", + " cra >>= f = MCont $ \\bTor ->\n", + " cra >>- \\a ->\n", + " (f a) >>- \\b ->\n", + " bTor b\n", + " \n", + "join' :: MCont r (MCont r a) -> MCont r a\n", + "join' ccx = MCont $ \\k ->\n", + " ccx >>- \\cx -> -- extract inner continuation\n", + " cx >>- \\x -> -- extract value of inner continuation\n", + " k x -- wrap value in k again" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "square :: Int -> MCont r Int\n", + "square x = MCont $ \\k -> k (x ^ 2)\n", + "\n", + "add :: Int -> Int -> MCont r Int\n", + "add x y = MCont $ \\k -> k (x + y)" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [], + "source": [ + "pythagoras :: Int -> Int -> MCont r Int\n", + "pythagoras x y = do\n", + " xsquare <- square x\n", + " ysquare <- square y\n", + " add xsquare ysquare" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Haskell", + "language": "haskell", + "name": "haskell" + }, + "language_info": { + "codemirror_mode": "ihaskell", + "file_extension": ".hs", + "name": "haskell", + "pygments_lexer": "Haskell", + "version": "8.6.5" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +}