-- Collected Haskell code of Section 11.6 from -- Kenneth C. Louden, Programming Languages -- Principles and Practice 2nd Edition -- Copyright (C) Brooks-Cole/ITP, 2003 -- page 513 fact 0 = 1 fact n = n * fact (n - 1) square x = x * x gcd1 u v = if v == 0 then u else gcd1 v (mod u v) reverse1 [] = [] reverse1 (h:t) = reverse1 t ++ [h] plus2 = (2 +) times3 = (* 3) -- page 514 square_list = map (\ x -> x * x) type ListFn a = [a] -> [a] type Salary = Float type Pair a b = (a,b) data BST a = Nil | Node a (BST a) (BST a) flatten:: BST a -> [a] flatten Nil = [] flatten (Node val left right) = (flatten left) ++ [val] ++ (flatten right) -- page 515 square_list2 lis = [ x * x | x <- lis] square_list_positive lis = [ x * x | x <- lis, x > 0] qsort [] = [] qsort (h:t) = qsort [x | x <- t, x <= h] ++ [h] ++ qsort [x | x <- t, x > h] f x = 2 my_if x y z = if x then y else z ones = 1 : ones -- page 516 sieve (p : lis) = p : sieve [n | n <- lis , mod n p /= 0] primes = sieve [2..] -- pages 519-520 (modified to avoid clash with previous definition) data BST2 a = Nil2 | Node2 a (BST2 a) (BST2 a) deriving (Show,Eq) tree = Node2 "horse" (Node2 "cow" Nil2 (Node2 "dog" Nil2 Nil2)) (Node2 "zebra" (Node2 "yak" Nil2 Nil2) Nil2)