Created
December 9, 2015 18:51
-
-
Save jtobin/ba992310771bd499e457 to your computer and use it in GitHub Desktop.
A program defined using 'Cofree'
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE DeriveFunctor #-} | |
{-# LANGUAGE FlexibleContexts #-} | |
{-# LANGUAGE StandaloneDeriving #-} | |
{-# LANGUAGE UndecidableInstances #-} | |
data Program f a = Program { | |
annotation :: a | |
, running :: f (Program f a) | |
} | |
deriving instance (Show a, Show (f (Program f a))) => Show (Program f a) | |
data Instruction r = | |
Increment r | |
| Decrement r | |
| Terminate | |
deriving (Functor, Show) | |
remaining :: Program Instruction Int -> Int | |
remaining = loop where | |
loop (Program a f) = case f of | |
Increment p -> succ (loop p) | |
Decrement p -> succ (loop p) | |
Terminate -> succ a | |
increment :: Program Instruction Int -> Program Instruction Int | |
increment p = Program (remaining p) (Increment p) | |
decrement :: Program Instruction Int -> Program Instruction Int | |
decrement p = Program (remaining p) (Decrement p) | |
terminate :: Program Instruction Int | |
terminate = Program 0 Terminate | |
program :: Program Instruction Int | |
program = | |
increment | |
. increment | |
. decrement | |
$ terminate |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment