Skip to content

Instantly share code, notes, and snippets.

@jtobin jtobin/cofree.hs
Created Dec 9, 2015

What would you like to do?
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
. decrement
$ terminate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.