Theory and Design of PL (CS 538)
January 29, 2020
slowSumTo 0 = 0
slowSumTo n = n + slowSumTo (n - 1)
-- After recursive call returns, need to add n
fastSumTo n = helper 0 n
where helper total 0 = total
helper total n = helper (total + n) (n - 1)
-- After recursive call returns, can just return
myEmptyList = [] -- empty list
myNonEmptyList = 1 : 2 : myEmptyList -- [1, 2]
-- singleton list: list with one element
mySingleton = [42] -- list with just 42
-- cons operation: add an element to the front of a list
(:) :: a -> [a] -> [a]
-- appending lists: glue two lists together
(++) :: [a] -> [a] -> [a]
myAppList = mySingleton ++ myNonEmptyList -- [42, 1, 2]
sortNums :: [Int] -> [Int]
sortNums [] = []
sortNums (x:xs) = lesser ++ [x] ++ greater
where lesser = sortNums (filter (< x) xs)
greater = sortNums (filter (> x) xs)
zip :: [a] -> [b] -> [(a, b)]
zip [] _ = []
zip _ [] = []
zip (x:xs) (y:ys) = (x, y) : zip xs ys
list = [1, 2, 3]
list' = [4, 5, 6]
paired = zip list list'
-- paired = [(1, 4), (2, 5), (3, 6)]
lengthList :: [a] -> Int
lengthList [] = 0
lengthList (x:xs) = 1 + lengthList xs
add42 :: [Int] -> [Int]
add42 [] = []
add42 (x:xs) = (x + 42) : add42 xs
foldr :: (a -> b -> b) -> b -> [a] -> b
foldr f init [] = init
foldr f init (x:xs) = f x (foldr f init xs)
a
is type of item, b
is type of resultprodList :: [Int] -> Int
prodList ls = prod' 1 ls
where prod' acc [] = acc
prod' acc (x:xs) = prod' (x * acc) xs
flipBool :: [Bool] -> [Bool]
flipBool bs = flip' [] bs
where flip' acc [] = acc
flip' acc (x:xs) = flip' (acc ++ [not x]) xs
foldl :: (a -> b -> a) -> a -> [b] -> a
foldl f init [] = init
foldl f init (x:xs) = foldl f (f init x) xs
a
is type of accumulator/result, b
is type of item