-- Lecture 2A Part II. Back to Lists data Suit = Hearts | Diamonds | Clubs | Spades deriving (Eq,Show) data Rank = Numeric Int | Jack | Queen | King | Ace deriving (Eq,Show) data Card = Card Rank Suit deriving (Eq,Show) rank :: Card -> Rank rank (Card r _) = r suit :: Card -> Suit suit (Card _ s) = s type Hand = [Card] ---------------------------- -- example card oneEye :: Card oneEye = Card King Diamonds -- Building lists with list comprehensions suits = [Hearts, Diamonds, Clubs, Spades] allKings :: Hand allKings = [ Card King s | s <- suits ] allClubs :: Hand -> Hand -- allClubs h = [ c | c <- h, suit c == Clubs] allClubs h = select Clubs h allSpades :: Hand -> Hand -- allSpades h = [ c | c <- h, suit c == Spades] allSpades h = select Spades h -- select all the cards from the hand of the given suit. select :: Suit -> Hand -> Hand select s h = [ c | c <- h, suit c == s] ------------------------------------------ -- Programming with lists using (:) and [], -- the basic building blocks for lists -- Prelude functions null, head and tail null' [] = True null' _ = False head' (x:_) = x tail' (_:xs) = xs third (_:_:x:_) = x last' xs = head (reverse xs) -- polymorphic types ------------------------------------------ -- Recall recursion: fac 0 = 1 fac n | n > 0 = n * fac (n-1) -- example: how to compute fac 3 using these rules -- by hand (and put in a list so you can check it) example = [ fac 3 , 3 * fac 2 , 3 * 2 * fac 1 , 3 * 2 * 1 * fac 0 , 3 * 2 * 1 * 1 , 6 ] -- -- length (called size in lab2) size [] = 0 size (x:xs) = 1 + size xs {- size [8,9] = size (8:9:[]) = 1 + size (9:[]) = 1 + 1 + size [] = 1 + 1 + 0 = 2 -} hasOne [_] = True hasOne _ = False -- sum (add all the elements in a list) -- Two argument functions -- append -- reverse -- index (!!)