module AlgDataType where data Weekday = Mon | Tue | Wed | Thu | Fri | Sat | Sun deriving Eq instance Show Weekday where show Mon = "Monday" show Tue = "Tuesday" show Wed = "Wednesday" show Thu = "Thursday" show Fri = "Friday" show Sat = "Saturday" show Sun = "Sunday" data IntTree = IntBranch IntTree IntTree | IntLeaf Int deriving Show testIntTree = IntBranch (IntLeaf 1) (IntBranch (IntLeaf 3) (IntLeaf 5)) data Tree a = Branch (Tree a) (Tree a) | Leaf a showTree :: Show a => Tree a -> String showTree t = (showTreeIndent 0 t) where showTreeIndent ind t = let indent = replicate ind ' ' in "\n" ++ case t of Branch l r -> indent ++ "L:" ++ (showTreeIndent (ind + 2) l) ++ "\n" ++ indent ++ "R:" ++ (showTreeIndent (ind + 2) r) Leaf l -> indent ++ show l instance Show a => Show (Tree a) where show = showTree -- example Trees: tr = Branch (Branch (Branch (Leaf 1) (Leaf 2)) (Leaf 3)) (Branch (Leaf 4) (Leaf 5)) -- tiny evaluator data Term = TmInt Integer | TmBool Bool | TmIf Term Term Term | TmStuck deriving (Show, Eq) isValue (TmInt _) = True isValue (TmBool _) = True isValue _ = False eval :: Term -> Term eval t = case t of tm@(TmInt _) -> tm tm@(TmBool _) -> tm TmIf (TmBool True) th el -> eval th TmIf (TmBool False) th el -> eval el TmIf cond th el -> eval (TmIf (eval cond) th el) -- _ -> error "Unknown Term" -- is the evaluator type safe? -- smallstep evaluator: evalOne :: Term -> Term evalOne (TmIf (TmBool True) t2 t3) = t2 evalOne (TmIf (TmBool False) t2 t3) = t3 evalOne (TmIf t1 t2 t3) | not (isValue t1) = TmIf (evalOne t1) t2 t3 evalOne _ = TmStuck evalStar :: Term -> Term evalStar tm | isValue tm = tm evalStar TmStuck = error "order pizza" evalStar tm = evalStar . evalOne $ tm