module Algebraic where ------------------------------------------ -- Introduction to Algebraic Data Types -- ------------------------------------------ ------------------------------------ -- Example: enumerated data types -- ------------------------------------ data MyBool = MyTrue | MyFalse -- operations on MyBool myand :: MyBool -> MyBool -> MyBool myand _ MyFalse = MyFalse -- `_` is a don't care pattern, matches anything myand MyFalse _ = MyFalse -- function equations are processed from top to bottom myand _ _ = MyTrue myand MyTrue MyTrue = MyFalse -- this case will never happen! myor :: MyBool -> MyBool -> MyBool myor _ MyTrue = MyTrue myor MyTrue _ = MyTrue myor _ _ = MyFalse ----------------------------------------- -- Example: data types with parameters -- ----------------------------------------- -- see AexpExt.hs, data Res a = .... ----------------------------------- -- Example: recursive data types -- ----------------------------------- -- natural numbers data Nat = Zero | Succ Nat one = Succ Zero two = Succ one -- and so on add :: Nat -> Nat -> Nat add Zero n = n add (Succ n1) n2 = Succ (add n1 n2) mult :: Nat -> Nat -> Nat mult = error "your code" -- lists data List a = Nil | Cons a (List a) myempty :: List a myempty = Nil myhead :: List a -> a myhead (Cons x _) = x mytail :: List a -> List a mytail (Cons _ xs) = xs mylast :: List a -> a mylast (Cons x Nil) = x mylast (Cons _ xs) = mylast xs -- note that lists are builtin -- we write [] for Nil, and (x:xs) for Cons x xs, -- [x] is an abbreviation for (x:[])