-- code_2009_02_27.hs
-- Glenn G. Chappell
-- 27 Feb 2009
--
-- For CS 331 Spring 2009
-- Sample Haskell code
-- From the Friday, February 27, 2009 class meeting

module Main where


-- ---------------------------------------------------------------------
-- Code from topic Haskell: Lists & Loops
-- ---------------------------------------------------------------------


-- Various List Operations

-- head & tail, with error checking
hd [] = error "hd: Empty list"
hd (x:xs) = x
tl [] = error "tl: Empty list"
tl (x:xs) = xs
-- Note: Same as standard functions head, tail

-- Concatenation
cat [] b = b
cat (x:xs) b = x:(cat xs b)
-- Typing  cat [1,2,3] [4,5,6]
-- gives   [1,2,3,4,5,6]
-- Note: Same as standard operator ++ (e.g., [1,2,3] ++ [4,5,6])

-- Lookup by Index
-- lookp, since "lookup" was already taken
lookp n [] = error "lookp: Index too large"
lookp n (x:xs)  | n < 0      = error "lookp: Index too small"
                | n == 0     = x
                | otherwise  = lookp (n-1) xs
-- Typing  lookp 3 [5,4,7,8,6,2]
-- gives   8
-- Note: Same as standard operator !! (e.g., [1,2,3] !! 1)

-- Map, Filter, and Fold Examples

square x = x * x
-- Typing  map square [1,2,3,8,6,8,1,14]
-- gives   [1,4,9,64,36,64,1,196]

isBig x = (x >= 6)
-- Typing  filter isBig [1,2,3,8,6,8,1,14]
-- gives   [8,6,8,14]
-- while
-- typing  map isBig [1,2,3,8,6,8,1,14]
-- gives   [False,False,False,True,True,True,False,True]

add x y = x + y
-- Typing          foldl add 0 [5,2,4,1]
-- is the same as  (((0+5)+2)+4)+1
-- Similarly:
-- typing          foldr add 0 [5,2,4,1]
-- is the same as  5+(2+(4+(1+0)))

