Table Of ContentContents
1 Wehaveaproblem... 4
2 HaskellTools 6
3 SimpleValues 11
4 DrawingCardsfromStrings 18
5 Sorting&Grouping 26
6 CategoriesofHands 33
7 ComparingHands 37
8 Specialcases 42
9 TestingtheRankings 50
10 Howtofindagoodhand 55
11 Printingthescores 65
DidyoureadTheLittleSchemer byDavidFriedmann Yes. It’safascinatingbook.
1
andMatthiasFelleisen?
What’sfascinatingaboutit? It’sdifferentfromeveryotherprogrammingbook.
2
Saymore. Most programming books feature some bits of code,
3
surroundedbylotsofexplanations. Thisoneisdiffer-
ent. It’s practically only code, and almost zero expla-
nations.
What’swrongwithlengthyexplanations? It’sboring. Plussometimesthecodeisnotevencor-
4
rectorbeautiful.
What’s important for you when you read about pro- Ineedtoreadcode,notlengthyexplanations. WhenI
5
gramming? seeanexplanationaboutthecodeIjustread,it’sabit
asiftheauthorwassaying”Ifthecodecouldspeak,it
wouldsay.. blahblah”.
Whatwouldyouyourselfsaytosuchanauthor? Hey... thecodecanspeak!
6
Whydidyouwritethisbook? TheLittleSchemeraimstoteachtheconceptofrecur-
7
sion. Iwaswonderingifitwouldbeinterestingnotto
teachoneconceptinparticular,buttowriteaprogram
in that manner, i.e. through a book of questions and
answers.
Whoshouldreadthisbook? PeoplewhoknownothingabouttheHaskellprogram-
8
ming language, and don’t like to read lots of explana-
tions.
Whoelse? Peoplewholiketoreadcode!
9
Doyouhaveanyhintsabouthowtoreadthebook? Yes:
10
→ Takethetimetoreadeverything.
→ Skimmingthroughchapterswillhurtyou.
→ Trythingsonyourcomputer.
Anythingelseyouwanttosay? Thank You! to the remarkable friends who helped
11
me write this book: Andrea Chiou, Fre´de´ric Merizen,
Michel Belleville, Jonathan Perret, Raphae¨l Pierquin,
and to all the kind persons who asked questions dur-
ingthehundredsofDojosessionswhereIwrotesome
Haskellcodeinfrontofothers. Curiosityisinspiring.
Shouldwestart? Byallmeans.
12
3
1 We have a problem...
(cid:114)
Whatisthis: ”8 ”? 13AString.
Yes. Whatdoesitrepresent? Aneightofhearts,or8(cid:114).
14
Whatdoes”7♣6(cid:113)9♠”represent? 15Someotherscards: 7♣,6(cid:113),and9♠.
(cid:114) (cid:114) (cid:114) (cid:114) (cid:114)
Right. Andwhatdoes”A K Q J T ”represent? 16Itrepresentsvictory: it’saroyalflush.
Whatisthebesthandwecandowiththefollowing: Aflush.
17
4(cid:113)2(cid:113)K♠K(cid:113)9(cid:113)3♣6(cid:113)?
Andwith9♣A(cid:114)K♠K(cid:113)9(cid:113)3♣6(cid:113)? Twopairs.
18
Correct. AndwithA♣Q♣K♠K(cid:113)9(cid:113)3♣? Nothing,becausetherearelessthansevencards.
19
Andwith9(cid:114)5♠? Nothing,forthesamereason.
20
That’sright. It’s a full house. Say, why are you showing me all
21
WhataboutK♣9♠K♠K(cid:113)9(cid:113)3♣6(cid:113)? thesecards?
Because we have a problem, and I wanted to be sure Showmewhattheproblemis.
22
youknowthebasicsaboutPoker.
4
Wehavetowriteaprogramwhich,giventhisinput: These are the cards of some players in a game of
23
K♣ 9♠ K♠ K(cid:113) 9(cid:113) 3♣ 6(cid:113) TexasHold’em1. Right?
9♣ A(cid:114) K♠ K(cid:113) 9(cid:113) 3♣ 6(cid:113)
A♣ Q♣ K♠ K(cid:113) 9(cid:113) 3♣
9(cid:114) 5♠
4(cid:113) 2(cid:113) K♠ K(cid:113) 9(cid:113) 3♣ 6(cid:113)
7♠ T♠ K♠ K(cid:113) 9(cid:113)
–right–..wouldoutputthis: Isee.
24
K♣ 9♠ K♠ K(cid:113) 9(cid:113) 3♣ 6(cid:113) Full House (winner)
9♣ A(cid:114) K♠ K(cid:113) 9(cid:113) 3♣ 6(cid:113) Two Pair
A♣ Q♣ K♠ K(cid:113) 9(cid:113) 3♣
9(cid:114) 5♠
4(cid:113) 2(cid:113) K♠ K(cid:113) 9(cid:113) 3♣ 6(cid:113) Flush
7♠ T♠ K♠ K(cid:113) 9(cid:113)
Whatdoyousee? Some lines are just left as they are. Some lines are
25
markedwiththerankingofthebestpossiblehandgiven
thecardsontheline. Thelinewiththebestrankingis
markedasthewinner.
Doyouthinkwecansolvetheproblem? Yes,Isuppose,providedwehavegoodtools.
26
1Seehttp://rubyquiz.com/quiz24.html
5
2 Haskell Tools
Whatistheeffectofthisprogram? ItprintstheAnswertotheUltimateQuestionofLife,
27
The Universe, and Everything. It is a very simple
main :: IO ()
main=putStrLn”42” Haskellprogram.
Howmanyfunctionsaredefinedinthisprogram? 28Onlyone,calledmain.
Whatisthetypeofthefunction? 29 This function is of type IO (), which means it will
performsomeinput/outputoperations,andyieldavoid
resultthatwedon’tcareabout.
Howdowerunthisprogram? One way is to save it to a file, for example
30
answer.hs,andthenlaunchrunhaskell:
runhaskell answer.hs ←(cid:45)
42
How do we execute some Haskell code in an interac- Onewayistolaunchghci: andtrythingsthere:
31
tiveway,withouthavingtowriteaprogram?
ghci ←(cid:45)
GHCi, http://www.haskell.org/ghc/ :? for help
6 * 7 ←(cid:45)
42
sqrt 2 ←(cid:45)
1.4142135623730951
4 > 3 ←(cid:45)
True
6
Whatothertoolsdowehavetosolvetheproblem? ToolsthatwewillcodeinHaskell,Isuppose.
32
(cid:114)
Thatisright. Whatis: ’ ’? 33It’saCharvalue.
Whatis: ’♠’? 34It’sanotherCharvalue.
Whatis: ”(cid:114)♣(cid:113)♠”? 35It’salistofChars,orStringvalue.
Howdoyougetinformationaboutthetypeofavalue? Using:typeand:infoinghci:2
36
(cid:114)
:type ’ ’ ←(cid:45)
(cid:114)
’ ’ :: Char
:type "(cid:114)♣(cid:113)♠" ←(cid:45)
"(cid:114)♣(cid:113)♠" :: [Char]
:info String ←(cid:45)
type String = [Char]
Whatisthevalueofthisexpression: length ”(cid:114)♠(cid:113)♣”? 374.
Whatisthevalueof: length [3,2,7,6,8] ? 385.
Whatisthetypeof: length ”(cid:114)♠(cid:113)♣”? 39 Int.
Whatisthetypeof: length? 40 [a] → Int3
HowdoesthisHaskellexpression: 41lengthisafunctionfromlistofanytype,to Int.
length :: [a] → Int
read?
Whatisthevalueoftheexpression: 42 [”time”,”flies”,”like”,”an”,”arrow”].
words”time flies like anarrow”
Whatisthetypeof: words? 43It’safunctionfromStringtolistofStrings:
:type words ←(cid:45)
words :: String → [String]
Whatisthevalueof: 4 == 5? 44False.
Whatisthevalueof: 4 == 3+1? 45True.
2Unicodehexvaluesfor’(cid:114)’,’♣’,’(cid:113)’and’♠’are:2665,2663,2666and2660.Using’H’,’C’,’D’and’S’wouldalsoworkverywell.
3ThisistrueforoldversionsofGHConly.ThetypesignatureoflengthisactuallyFoldable t =⇒ta→Int.Foldabletypesarecontainers
thatcanbefoldedintoasummaryvalue([a]issuchatype).
7
Whatisthevalueof: 4 == 2∗ 1+1? 46False.
Whatisthevalueof: 4 == 2∗ (1 +1)? 47True.
Whatisthetypeoftheexpression4 == 5? 48It’sabooleanexpression:
:type 4 == 5 ←(cid:45)
4 == 5 :: Bool
Let’screateincidents. Whatisthevalueof: It’snotavalidHaskellexpression:
49
’(cid:114)’ == True?
Couldn’t match expected type ‘Char’ with actual type ‘Bool’
In the second argument of ‘(==)’, namely ‘True’
In the expression: ’(cid:114)’ == True
Whatdoyouinfer? 50 If the first argument of (==) is a Char, the second
argumentshouldbealsoaChar.
Whatelsecanyouinfer? 51Thereisafunction(==)thattakestwoarguments:
(==) 3 4 ←(cid:45)
False
Whatisthevalueof: (+) 45? 529.
Whatdoyouconclude? Operatorsarefunctionstoo.
53
Whatisthevalueofexpression: 4+False? 54Again,it’snotavalidexpression:
No instance for (Num Bool) arising from a use of ‘+’
Possible fix: add an instance declaration for (Num Bool)
In the expression: 4 + False
Butthemessageisdifferent.
Let’strytounderstandthemessage. 55(+) :: Numa=⇒a→a→a.
Whatisthetypeof(+)?
Heresome:infoaboutNum: Explain in your own words what the error message is
about.
Class Num a where
(+) :: a → a → a
(*) :: a → a → a
(-) :: a → a → a
negate :: a → a
abs :: a → a
signum :: a → a
fromInteger :: Integer → a
instance Num Integer
instance Num Int
instance Num Float
instance Num Double
8
56Thereare4typesthatareinstancesoftheclassNum, Thereforetheexpression: 4+False isinvalid.
andBoolisnotoneofthosetypes.
Making Bool an instance of Num would make the ex-
The operator (+) requires operands of a type that is pression a valid expression. (Although I don’t think
aninstanceofNum. it’sagoodidea).
Whatisthevalueoftheexpression: subtract 110? 579.
Whatisthevalueof: subtract 25100? 5875.
Whatisthetypeof: subtract 110? 59Numa=⇒a.
Whatisthetypeofsubtract 1? 60Numa=⇒a→a.
Whatisthetypeofsubtract? 61Numa=⇒a→a→a.
Let’ssupposethatdec=subtract 1. 62Let’sask:
Whatisthevalueofdec1000? let dec = subtract 1 ←(cid:45)
dec 1000 ←(cid:45)
999
Wejustcreatedanewfunction.
Let’screateanotherone: inc = (+) 1. 63Let’saskagain:
Whatisthevalueof: inc (inc (inc 1))? let inc = (+) 1 ←(cid:45)
inc (inc (inc 1)) ←(cid:45)
4
Andanotherone: dbl = (∗) 2. 64IthinkIknowtheanswer.
Whatisthevalueofdbl 6? let dbl = (*) 2 ←(cid:45)
dbl 6 ←(cid:45)
12
Good. Nowlet’sdefinesomethingnew: Ihavenoidea. Let’stry:4
65
foo =inc ◦ dbl. let foo = inc ◦ dbl ←(cid:45)
Whatisthevalueoffoo 10? foo 10 ←(cid:45)
21
Whyistheresult21? 66Itis10multipliedby2,plus1.
Whatisthetypeof: o? 67
:type (◦) ←(cid:45)
(◦) :: (b → c) → (a → b) → a → c
ThatisthemostcomplexfunctionI’veseen.
4Inghci,replace ◦ with..
9
Supposewehavethefollowing: Interesting!
68
fry :: Batter →Pancake
mix :: (Flour,Milk,Egg)→Batter
Thensupposewedefineanewfunction: Ithinkitshouldbesomethinglike:
69
cook=fry ◦ mix
cook :: (Flour, Milk, Egg)→Pancake
Whatwouldbethetypeofthisnewfunction?
How would you explain the role of ◦ in this expres- 70The ◦ functiontakestwofunctions f andgandcom-
sion: f ◦ g? posethemintoanewfunction.Applyingthisnewfunc-
tion to an argument x is the same as applying f to the
resultofapplyinggtox.
Infewerwords? 71(f ◦ g) x = f (gx)
Supposewewantanewfunction: wc :: String → Int. 72Thatseemseasytodo.
ThejobofthisfunctionistocountwordsinaString.
Createthewcfunctioninghci. 73Hereitis:
let wc = length ◦ words ←(cid:45)
wc "a four words sentence" ←(cid:45)
4
Perfect! Doyouwanttosolvetheproblem? Let’smakesometeafirst.
74
10