Skip to content

Instantly share code, notes, and snippets.

@jtobin
Created December 9, 2015 18:51
Show Gist options
  • Save jtobin/ba992310771bd499e457 to your computer and use it in GitHub Desktop.
Save jtobin/ba992310771bd499e457 to your computer and use it in GitHub Desktop.
A program defined using 'Cofree'
{-# 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