Session 21: Haskell introduction

Today we cover Chapter 2, as well as Sections 3.1 and 3.2, from Hudak, Peterson, and Fasel's A Gentle Introduction to Haskell 98. Here are the specific examples covered in class.

-- using functions

double :: Integer -> Integer
double n = 2 * n

fact :: Integer -> Integer
fact 0 = 1                        -- you can list multiple cases...
fact n = n * fact (n - 1)         -- and you can use recursion

double2 :: Integer -> Integer
double2 = \n -> 2 * n

quadruple :: Integer -> Integer
quadruple n = double (double n)   -- Note parentheses required!

doublef :: (Integer -> Integer) -> (Integer -> Integer)
doublef f = \n -> f (f n)

quadruple2 :: Integer -> Integer
quadruple2 n = doublef double n   -- Note no parens: doublef gets double

add :: Integer -> Integer -> Integer
add m n = m + n


-- using tuples and polymorphic functions

addTuple :: (Integer, Integer) -> Integer
addTuple (m, n) = m + n

firstTuple :: (a, b) -> a         -- function works for variety of types
firstTuple (m, n) = m

doubleFirst :: (Integer, a) -> Integer
doubleFirst (m, n) = 2 * firstTuple (m, n)


-- using user-defined types

data Suit = Clubs | Diamonds | Hearts | Spades
data Rank = Ace | R2 | R3 | R4 | R5 | R6 | R7 | R8 | R9 | R10
	| Jack | Queen | King

nextSuit :: Suit -> Suit
nextSuit Clubs    = Diamonds
nextSuit Diamonds = Hearts
nextSuit Hearts   = Spades

data Card = Card Rank Suit                   -- values incorporate data

isTrump :: Card -> Bool
isTrump (Card r Spades) = True
isTrump (Card r s)      = False

data Tree a = Leaf a | Branch (Tree a) (Tree a)   -- type is recursive

size :: Tree a -> Integer
size (Leaf a)            = 1
size (Branch left right) = size left + size right


-- using lists

myLength :: [a] -> Integer
myLength []       = 0
myLength (x : xs) = 1 + myLength xs

quickSort :: [Integer] -> [Integer]
quickSort [] = []
quickSort (x : xs) = quickSort [ a | a <- xs, a < x ] ++ [x]
	++ quickSort [a | a <- xs, a >= x ]