20-CS-4003-001 Organization of Programming Languages Fall 2017
Functors

Lambda calculus, Type theory, Formal semantics, Program analysis

Prev     Next     All lectures           Code

Basics

data Color =   
     Red | Green | Blue | Indigo | Violet 
     deriving (Ord, Eq, Show, Bounded)

{- Empty :: Tree a
   Node :: a -> Tree a -> Tree a -> Tree a
   Leaf :: a -> Tree a
-}
data Tree a = 
       Empty
     | Node a (Tree a) (Tree a)           {- a is the info of the Node -}
     | Leaf a deriving (Show, Read, Eq)   {- a is the info of the Leaf -}

{- treeInsert :: (Ord a) => a -> Tree a -> Tree a 
   Note: an entire new tree is returned
   Note: Ord is required because compares are made to place nodes in the tree
 -}
treeInsert x Empty = Leaf x  
treeInsert x (Leaf a)
    | x == a = Leaf x
    | x < a = Node a (treeInsert x Empty) Empty
    | x > a = Node a Empty (treeInsert x Empty)
treeInsert x (Node a left right)
    | x == a = Node x left right  
    | x < a  = Node a (treeInsert x left) right  
    | x > a  = Node a left (treeInsert x right)  

{- search for x in a Tree -}
inTree x Empty = False
inTree x (Leaf a)
    | x == a = True
    | otherwise = False
inTree x (Node a left right)
    | x == a = True  
    | x < a  = inTree x left  
    | x > a  = inTree x right  

v7 = treeInsert Green Empty
v8 = treeInsert Indigo v7
v9 = treeInsert Blue v8
v10 = treeInsert Red v9
v11 = treeInsert Violet v10

v12 = inTree Violet v11
v13 = inTree Violet v10

nums = [8,6,4,1,7,3,5]
{- foldr :: (a -> b -> b) -> b -> [a] -> b 
   so, b is a Tree and a is a Num 
-}
v14 = foldr treeInsert Empty nums
v15 = inTree 7 v14
v16 = inTree 10 v14

v17 = treeInsert Violet $ treeInsert Red $ treeInsert Blue $ treeInsert Indigo $ treeInsert Green Empty

{-   Node Green (Leaf Red) (Node Indigo (Leaf Blue) (Leaf Violet))
             
                    o Green
                   / \
                  /   \
             Red o     o Indigo
                      / \
                     /   \
               Blue o     o Violet

    
     Node 5 (Node 3 (Leaf 1) (Leaf 4)) (Node 7 (Leaf 6) (Leaf 8))

                       o 5
                   ___/ \___
                  /         \
               3 o           o 7
                / \         / \ 
             1 o   o 4   6 o   o 8
-}