-- Comp1100
-- Sem 1 2006

-- Algebraic Data Type Examples

-- Clem Baker-Finch March 2006

module AlgDT where

---------------------------------------------------------------------------
-- Enumerated types.
---------------------------------------------------------------------------

data Day = Sun | Mon | Tue | Wed | Thu | Fri | Sat

data Month = Jan | Feb | Mar | Jun | Jul | Aug | Sep | Oct | Nov | Dec

-- data Temp = Cold | Hot

-- data Season = Spring | Summer | Autumn | Winter


---------------------------------------------------------------------------
-- What is the weather in England?
---------------------------------------------------------------------------

weather :: Season -> Temp
weather Summer = Hot
weather other  = Cold

---------------------------------------------------------------------------
-- This doesn't work unless type Season is not an instance of Eq.
---------------------------------------------------------------------------

weather' :: Season -> Temp
weather' s
    | s == Summer  = Hot
    | otherwise    = Cold

data Season = Spring | Summer | Autumn | Winter
              deriving (Eq, Show)

data Temp = Cold | Hot 
	    deriving (Eq, Show)

---------------------------------------------------------------------------

-- instance Eq Temp where
--    Hot == Hot    = True
--    Cold == Cold  = True
--    _ == _        = False

---------------------------------------------------------------------------
-- Union types -- geometric shapes.
-- Add other alternatives as you wish.
---------------------------------------------------------------------------

data Shape = Circle Float | Rectangle Float Float
             deriving (Eq, Show)

isRound :: Shape -> Bool
isRound (Circle r)      = True
isRound (Rectangle l b) = False

area :: Shape -> Float
area (Circle r)      = pi * r^2
area (Rectangle l b) = l * b

---------------------------------------------------------------------------
-- Recursive types -- lists of integers.
---------------------------------------------------------------------------

data List = Empty | Cons Int List
            deriving (Eq, Ord, Show)

---------------------------------------------------------------------------
-- Recursive types -- binary trees of strings.
---------------------------------------------------------------------------

data Tree = Null | Node String Tree Tree

---------------------------------------------------------------------------
-- Polymorphic algebraic types.
---------------------------------------------------------------------------

data List' a = Empty' | Cons' a (List' a)
               deriving (Eq, Ord, Show)

data Tree' a = Null' | Node' a (Tree' a) (Tree' a)

---------------------------------------------------------------------------




