Learn You a Haskell for Great Good! - nostarch.com · INDEX 365 birds ignoring in Pierre example,...

14
INDEX Symbols & Numbers && (double ampersand) as Boolean operator conjunction, 2 using with folds and lists, 78–79 '(apostrophe) using with functions, 7 using with types, 149–150 * (asterisk) as multiplication function, 3 using with kinds, 150 ** (exponentiation), using with RPN func- tions, 207–208 \ (backslash), declaring lambdas with, 71 ` (backticks) using with functions, 4–5 : (colon) as cons operator bytestring version of, 200 using with applicatives, 238–239 using with lists, 8–9 using with infix constructors, 134 :: (double colon) using in record syntax, 116 using with type annotations, 30, 118 using with types, 24 :k command, identifying kinds with, 150–151 $ (function application operator), 80–81, 83 / (division), using with RPN functions, 207–208 /= (not-equal-to) operator, 3, 28 = (equal) sign using with data keyword, 109 using with data types, 122 using with functions, 5 == (double equal sign), 3 using with Eq type class, 28 using with type instances, 139–140 !! (double exlamation point) in Data.List module, 182 using with lists, 9 > (greater-than) operator, using with lists, 9–10 >> function, replacing, 279 >>= (bind) function in A Knight’s Quest, 292 nested use of, 280 using with functions as monads, 311 using with monads, 269–270, 272, 274–280, 283–284, 286 using with Reader monad, 312 using with State monad, 316–317 using with Writer type, 302 -> (arrow) in type signature, 60–61 using with functions, 25 using with lambdas, 71 -> r as functor and monad, 311 < (less-than) operator, using with lists, 9–10 <*> function calling with applicative values, 236 left-associative, 233 specializing for IO, 234 using with applicative style, 232 using with liftM function, 325 using with zip lists, 237 <= operator, using with lists, 9–10 <$>, using with applicative style, 231–232 <-, using with I/O actions and functors, 219 - (minus) operator, using with sections, 62 () (parentheses) minimizing use of, 81, 83 placement with functions, 7 using with operations, 2, 5 using with sections, 62 (,,) function, using with zip lists, 238 Learn You a Haskell for Great Good! © 2011 by Miran Lipovača

Transcript of Learn You a Haskell for Great Good! - nostarch.com · INDEX 365 birds ignoring in Pierre example,...

Page 1: Learn You a Haskell for Great Good! - nostarch.com · INDEX 365 birds ignoring in Pierre example, 278–280 representing in Pierre example, 275–278 BMI (body mass index) calculation

I N D E X

Symbols & Numbers

&& (double ampersand)as Boolean operator conjunction, 2using with folds and lists, 78–79

'(apostrophe)using with functions, 7using with types, 149–150

* (asterisk)as multiplication function, 3using with kinds, 150

** (exponentiation), using with RPN func-tions, 207–208

\ (backslash), declaring lambdas with, 71` (backticks) using with functions, 4–5: (colon)

as cons operatorbytestring version of, 200using with applicatives, 238–239using with lists, 8–9

using with infix constructors, 134:: (double colon)

using in record syntax, 116using with type annotations, 30, 118using with types, 24

:k command, identifying kinds with, 150–151

$ (function application operator), 80–81, 83

/ (division), using with RPN functions, 207–208

/= (not-equal-to) operator, 3, 28= (equal) sign

using with data keyword, 109using with data types, 122using with functions, 5

== (double equal sign), 3using with Eq type class, 28using with type instances, 139–140

!! (double exlamation point)in Data.List module, 182using with lists, 9

> (greater-than) operator, using with lists, 9–10

>> function, replacing, 279>>= (bind) function

in A Knight’s Quest, 292nested use of, 280using with functions as monads, 311using with monads, 269–270, 272,

274–280, 283–284, 286using with Reader monad, 312using with State monad, 316–317using with Writer type, 302

-> (arrow)in type signature, 60–61using with functions, 25using with lambdas, 71

-> r as functor and monad, 311< (less-than) operator, using with lists, 9–10<*> function

calling with applicative values, 236left-associative, 233specializing for IO, 234using with applicative style, 232using with liftM function, 325using with zip lists, 237

<= operator, using with lists, 9–10<$>, using with applicative style, 231–232<-, using with I/O actions and

functors, 219- (minus) operator, using with sections, 62() (parentheses)

minimizing use of, 81, 83placement with functions, 7using with operations, 2, 5using with sections, 62

(,,) function, using with zip lists, 238

Learn You a Haskell for Great Good! © 2011 by Miran Lipovača

Page 2: Learn You a Haskell for Great Good! - nostarch.com · INDEX 365 birds ignoring in Pierre example, 278–280 representing in Pierre example, 275–278 BMI (body mass index) calculation

364 INDEX

. (period), using with functions, 89

.. (dots), using with value constructors, 113–114

+ (plus) operator, 3, 5++ (concatenation) operator

excluding from pattern matching, 40using with lists, 8

; (semicolon), using with let expressions, 46[] (square brackets), using with lists, 7, 24[Char] and String types, 30, 127–128_ (underscore)

in pattern matching, 38using with lists, 18

| (vertical pipe)using with data keyword, 109using with data types, 122using with guards, 41

|| as Boolean operator disjunction, 2, 2560 flag, using in Heathrow to London

example, 2163D vector type, implementing, 121–122

A

accumulatorsusing with folds, 73using with right folds, 75using with scanl and scanr, 79–80

addDrink function, 301–302algebraic data structures, 137algebraic data types, 126–127, 133. See also

data typesalgebraic expressions, writing, 203–208All type, using with monoids, 257ampersands (&&)

as Boolean operator conjunction, 2using with folds and lists, 78–79

and functionusing with applicative functors, 241using with lists, 78

any function, 92Any newtype constructor, using with

monoids, 256–257apostrophe (')

using with functions, 7using with types, 149–150

appendFile functionin to-do list example, 180using in I/O, 180

applicative functors, 227–228, 237–238, 323. See also functors

Applicative type class, 228–229, 323functions as, 235–236

liftA2 function, 238–239lists as, 232–234, 243–244, 285–287Maybe types as, 269–270sequenceA function, 239–242upgrading, 267–269zip lists, 237

applicative laws, 238applicative operators, vs. monads, 278applicative style, using on lists, 233–234Applicative type class, 228–229, 323

Maybe implementation, 229–230style of pure, 230–232

applyLog functionusing with monoids, 300using with Writer monad, 299–300

arithmetic expressions, 2arrow (->)

in type signature, 60–61using with functions, 25using with lambdas, 71

askForNumber function, 197as-pattern, 40association lists, 98–100. See also listsassociativity

defined, 251using with monads, 294–296

asterisk (*)as multiplication function, 3using with kinds, 150

B

baby.hs fileappending code to, 6saving, 5

backslash (\), declaring lambdas with, 71backticks (`) using with functions, 4–5Banana on a Wire example, 278–280base case, reaching, 51binary functions

using on values, 251using with folds, 73

binary search tree, implementing, 135–137bind (>>=) function

in A Knight’s Quest, 292nested use of, 280using with functions as monads, 311using with monads, 269–270, 272,

274–280, 283–284, 286using with Reader monad, 312using with State monad, 316–317using with Writer type, 302

binding to variables, 39

Learn You a Haskell for Great Good! © 2011 by Miran Lipovača

Page 3: Learn You a Haskell for Great Good! - nostarch.com · INDEX 365 birds ignoring in Pierre example, 278–280 representing in Pierre example, 275–278 BMI (body mass index) calculation

INDEX 365

birdsignoring in Pierre example, 278–280representing in Pierre example, 275–278

BMI (body mass index)calculation of, 41–42listing of, 45repeating calculations of, 43

Boolean algebra, 2Boolean expressions, using with guards, 41Boolean values

generating randomly, 191for tossing coin, 193

Bool type, 26, 143–144, 256–257Bounded type class, 31–32, 126–127bracket function, using in I/O, 178–179bracketOnError function, 183–184breadcrumbs

in filesystem, 355representing in trees, 346–348using with lists and zippers, 352–353

bytestrings, 198–202. See also listschanging types of, 300copying files with, 201–202module functions, 201as monoids, 300strict and lazy, 199–201

C

Caesar cipher, 92–94calculations, performing once, 42–45capital letters, restriction of, 7capslocker.hs program

exiting, 171getContents I/O action, 171saving and compiling, 170

Car data type, 119–120case expressions, 48–49

vs. if else statements, 48vs. let expressions, 48syntax, 48

cat program, 180–181characters

converting into numbers, 96shifting, 93

[Char] and String types, 30, 127–128CharList value constructor, 245–246, 250Char type, 26chessboard example, 290–292circles, representing, 110–112class constraints, 140, 142class declarations, 140

code blocks, excluding, 48–49coin-toss function, 193–195Collatz sequence, 69–70colon (:)

as cons operatorbytestring version of, 200using with applicatives, 238–239using with lists, 8–9

using with infix constructors, 134command-line arguments, 184–185compare function

using Ordering type with, 29using with guards, 42using with monoids, 259

computationsdeferred, 199performing, 52

concatenation (++) operatorexcluding from pattern matching, 40using with lists, 8

concrete types, 150–151. See also data typesconditions, adding to list comprehen-

sions, 16conjunction (&&) Boolean operator, 2cons (:) operator, using with lists, 8–9Cons constructor, 133context of failure, adding to values, 321.Control.Exception bracketOnError,

183–184copyFile function, 201copying files with bytestrings, 201–202Cube.hs file in Geometry module, 107Cuboid.hs file in Geometry module, 106curried functions, 59–62, 222

max, 60printing functions, 63sections, 62–63

cycle function, using with lists, 14

D

Data.ByteString.Lazy module, 199Data.Char module, 93, 96data keyword, 109–110

vs. newtype, 244–245, 248–249using, 250

Data.List module, 88–89. See also lists!! function, 182any function, 92delete function, 182group function, 90tails function, 91–92words function, 90

Learn You a Haskell for Great Good! © 2011 by Miran Lipovača

Page 4: Learn You a Haskell for Great Good! - nostarch.com · INDEX 365 birds ignoring in Pierre example, 278–280 representing in Pierre example, 275–278 BMI (body mass index) calculation

366 INDEX

Data.Map module, 114.fromListWith function, 103lookup function, 100Map k v parameterized type, 120

Data.Monoid moduleProduct type, 255–256Sum type, 255–256

data structures. See also zippersreducing to values, 73using zippers with, 352

data types. See also algebraic data types; concrete types; recursive data struc-tures; type constructors; type param-eters; types

3D vector, 121–122applying to type constructors, 150–152defining, 109–110, 122for describing people, 114–117, 123–124identifying, 150–151making, 250record syntax, 116–117wrapping with newtype keywords,

244–245Day type, 127deferred computation, 199definitions, functions as, 7deletetodo.hs program, saving and compil-

ing, 182derived instances, 122–127. See also type

classesequating people, 123–124Read type class, 124–125Show type class, 124–125

deriving keyword, using with newtype, 245dictionaries, 98difference lists, using, 307–309digitToInt function, 96disjunction (||) Boolean operator, 2div function, 4–5division (/), using with RPN functions,

207–208do expressions. See also monads

actions of, 219failure of pattern matching in, 284let lines in, 282monadic expressions in, 282monadic values in, 282results of, 318writing, 283

do notation, 280–285, 290and <-, 156and list comprehensions, 288pattern matching and failure, 284–285using with Writer monad, 303–304

dots (..), using with value constructors, 113–114

double colon (::)using in record syntax, 116using with type annotations, 30, 118using with types, 24

double equal sign (==), 3using with Eq type class, 28using with type instances, 139–140

Double type, 26drop function, using with lists, 12

E

Either, kind of, 151Either a b type, 130–132, 149–150Either e a type, 321–322elem function

using recursively, 55–56using with lists, 12

end-of-file character, issuing, 170Enum type class, 31, 126–127equal (=) sign

using with data keyword, 109using with data types, 122using with functions, 5

equality (== and /=) operators, 3equality testing, 28Eq type class, 28, 122–124, 138–139,

141, 250erroneous computation, representing, 247error function

calling, 178using in pattern matching, 39

Error instance, 322error messages, 3Euclid’s algorithm, 304–305exceptions, raising, 178, 247–248exponentiation (**), using with RPN func-

tions, 207–208exporting

functions, 104shapes in modules, 113–114

expressionsdetermining types of, 24equivalent examples of, 71–72lambdas as, 71using operations in, 2

F

factorial function, 25, 36failure, adding context of, 321False Boolean value, 2–3

Learn You a Haskell for Great Good! © 2011 by Miran Lipovača

Page 5: Learn You a Haskell for Great Good! - nostarch.com · INDEX 365 birds ignoring in Pierre example, 278–280 representing in Pierre example, 275–278 BMI (body mass index) calculation

INDEX 367

Fibonacci sequence, specifying recur-sively, 51–52

file contents vs. handles, 177files

copying with bytestrings, 201–202processing as strings, 199reading and writing, 175–180

filesystemmanipulating, 357–358moving up and down in, 356–357representing via zippers, 353–358

filter function, 67–70vs. takeWhile, 80using fold with, 77

filtering over lists, 198–199FilterM monadic function, 328–331fixity declaration, 134flip function, 65–66, 78floating-point numbers, precision of, 337Floating type class, 32Float type, 25–26fmap function

concept of, 223as function composition, 222as infix function, 221vs. liftM, 324–325using over functions, 221using with newtype, 246

folding functionusing with monoids, 262–265using with RPN, 206–207

foldl function, 74, 76vs. scanl, 79stack overflow errors, 94–95

FoldM monadic function, 331–332fold pattern, example of, 99foldr function, 75–76, 78–79. See also right

fold functionvs. scanr, 79using binary search tree with, 137

foldsaccumulators, 73binary functions, 73concept of, 77–78examples, 76–77left vs. right, 75

forever I/O function, 165–166for loops, 198forM I/O function, 166–167fromListWith function, 103fst function

type of, 27using with pairs, 20

function application operator ($), 80–81, 83

function composition, 82–84fmap as, 222module functions, 91with multiple parameters, 83–84performing, 89point-free style, 84–85right-associative, 82

function f, mapping over function g, 310–311

function parameters, pattern matching on, 48–49

functional programming, pattern in, 22functions

. (period) symbol used with, 89accessing, 88as applicatives, 235–236applying for monads, 275–276applying to lists, 66–67applying with - (minus) operator, 347behavior of, 153–154calling, 3–6combining, 6concept of, 61creating, 5–7, 310–311defining, 35–36as definitions, 7exporting from modules, 104filter, 67–70as functors, 220–223, 311importing from modules, 89infix, 3–4lifting, 222loading, 6in local scope, 46map, 66–70mapping with multiple parameters,

70–71as monads, 311optimal path, 212–215partially applied, 60, 64, 71polymorphic, 27prefix, 3–4printing, 63referencing from modules, 89relating to people, 115searching for, 88for shapes, 112–113with side effects, 153–154syntax, 5type declarations, 205types of, 24–25

Learn You a Haskell for Great Good! © 2011 by Miran Lipovača

Page 6: Learn You a Haskell for Great Good! - nostarch.com · INDEX 365 birds ignoring in Pierre example, 278–280 representing in Pierre example, 275–278 BMI (body mass index) calculation

368 INDEX

functions (continued)using, 6–7using once, 71–73value constructors as, 110, 112, 114values returned by, 6–7for vectors, 121–122in where blocks, 45

functor laws1 and 2, 223–225breaking, 225–227

functors, 218, 323. See also applicative functors

converting maps into, 149–150functions as, 220–223I/O actions as, 218–220

Functor type class, 146–150, 227definition of, 152Either a type constructor, 149–150Maybe type constructor, 147–148Tree type constructor, 148–149

functor values, functions in, 227

G

gcd function, 304–306gcdReverse function, efficiency of, 309generics vs. type variables, 27gen generator example, 313Geometry module, 104–107getContents I/O action, 171–173get function, using with state, 318–319getStdGen I/O action, 195–196GHC compiler, invoking, 155GHCi, let expressions in, 47ghci, typing, 1ghci> prompt, 1girlfriend.txt file

caps-locked version of, 180opening, 175

global generator, implementing, 195greater-than (>) operator, using with lists,

9–10greatest common divisor, calculating,

304–305group function, using with words function,

90–91guard function, using with monads, 289guards. See also functions

vs. if/else trees, 41vs. if expressions, 40–41otherwise, 41vs. patterns, 40–41using, 41–42

H

haiku.txt input, 170handles vs. file contents, 177Haskell

laziness of, 247as pure language, 313

haystack and needle lists, 91–92head function, using with lists, 10–11Heathrow to London example

optimal path function, 212–215quickest path, 209–211road system, 211–212road system from input, 215–216stack overflow errors, 216

Hello, world! programcompiling, 154–155defining main, 154function types, 155printed output, 155running, 155

hierarchical modules, 104–106higher-order functions. See also functions

curried functions, 59–64flip, 65–66map, 66–70type declaration, 63zipWith, 64–65

Hoogle search engine, 88

I

id function, 144, 223–224if else statements vs. case expressions, 48if/else trees vs. guards, 41if expressions, 40–41, 143, 145if statement, 6–7I’ll Fly Away example, 276–278importing modules, 88–89infinite lists, using, 14infix functions, 3–5, 12, 27. See also

functionsapplying, 62–63defining automatically, 133–134

init function, using with lists, 10–11input, transforming, 173–175input redirection, 170input streams, getting strings from,

171–173instance declarations, 142instance keyword, 139Integer type, 25Integral type class, 33interactive mode, starting, 1Int type, 25

Learn You a Haskell for Great Good! © 2011 by Miran Lipovača

Page 7: Learn You a Haskell for Great Good! - nostarch.com · INDEX 365 birds ignoring in Pierre example, 278–280 representing in Pierre example, 275–278 BMI (body mass index) calculation

INDEX 369

I/O (input and output)appendFile function, 180bracket function, 178–179files and streams, 169–175and randomness, 195–198readFile function, 179withFile function, 177–178writeFile function, 179–180

I/O actions<- vs. let bindings, 159binding names, 158–159do blocks, 219do notation, 156–161as functors, 218–220getArgs, 184–185getContents, 171–173getLine type, 156getProgName, 184–185gluing together, 156–161let syntax, 158–159making from pure value, 160vs. normal values, 157performing, 155, 157results yielded by, 153, 157return function, 160–161reverseWords function, 159–161review, 167in System.Environment module, 184–185tellFortune function, 157using sequenceA function with, 242using with monads, 293

I/O functionsforever, 165–166forM, 166–167mapM, 165print, 162–163putChar, 162putStr, 161–162sequence, 164–165when, 163–164

IO instance of Applicative, 234–235isPrefixOf function, using with strings, 92

J

join monadic function, 326–328

K

:k command, identifying kinds with, 150–151

key/value mappings, achieving, 98–104Knight’s Quest, A (example), 290–292

L

lambdas, 71–73. See also functionsdeclaring, 71in function composition, 82in Heathrow to London example, 216using with folds, 74

landLeft and landRight functions, 276–277last function, using with lists, 10–11less-than (<) operator, using with lists, 9–10left fold function, 74. See also foldl function

in Heathrow to London example, 213–215

using with RPN function, 205Left value, feeding to functions, 322length function, using with lists, 11, 17–18let expressions

vs. case expressions, 48in GHCi, 47in list comprehensions, 46–47pattern matching with, 46using, 45–46vs. where bindings, 45–46

let keywordusing with lists, 16using with names, 8

liftA2 function, using with applicative functors, 238–239

liftM monadic function, 323–326list comprehensions, 15–18

and do notation, 288pattern matching with, 38–40using with tuples, 21–22

list monad, 285–287. See also monadslist operations

cycle function, 14drop function, 12elem function, 12head function, 10–11init function, 10–11last function, 10–11length function, 11maximum function, 12null function, 11odd function, 16repeat function, 14replicate function, 15reverse function, 11sum function, 12tail function, 10–11take function, 12

list ranges, using Enum type in, 29. See also ranges

Learn You a Haskell for Great Good! © 2011 by Miran Lipovača

Page 8: Learn You a Haskell for Great Good! - nostarch.com · INDEX 365 birds ignoring in Pierre example, 278–280 representing in Pierre example, 275–278 BMI (body mass index) calculation

370 INDEX

lists. See also association lists; bytestrings; Data.List module; task list program; zip lists

accessing elements of, 9adding to, 8and function, 78as applicative functors, 232–234,

237–238, 243–244, 285–287applying functions to, 66–67binding elements from, 15checking empty status of, 11combining, 15–18comparing, 9–10concatenation, 8–9construction of, 306–307converting trees to, 265drawing elements from, 15efficiency of, 306–307filtering, 15–18, 198–199folding, 73–74getting last elements of, 77including predicates in, 16–17infinite, 14inside lists, 9managing via module functions, 91–92mapping over, 198–199as monoids, 253–254, 300as nondeterministic computations, 233number ranges in, 13–15pattern matching with, 38–40promise of, 199recursive functions on, 99replacing odd numbers in, 16sorting, 56–58square brackets ([]) used with, 7transforming, 15–18vs. tuples, 18, 20, 24using applicative style on, 233using with filter function, 67using with RPN functions, 205–206using zippers with, 352–353

locker codes, looking up, 132logging, adding to programs, 304–306logical or (||), using with monoids, 256log type, changing type of, 300log values. See also values

applyLog function, 299–300implementing, 305–306using Writer monad for, 298

M

maindefining for Hello, world!, 154–155defining for task list, 186

map function, 66–70, 73, 75mapM I/O function, 165mappend function

using with folds and monoids, 263using with Maybe and Monoid, 260using with Monoid type class, 252, 254using with Ordering values, 258–259using with Writer monad, 300using with Writer type, 303

mapping over lists, 198–199maps. See also Data.Map module

vs. association lists, 100converting association lists to, 100converting into functors, 149–150type of keys in, 120

maxBound function, using with Bounded type, 31

max function, curried, 60maximum function

in recursion example, 52–53using with lists, 12

max prefix function, calling, 4Maybe instance, using with Monad type class,

273–280Maybe monad

using with trees, 358vs. Writer monad, 299

Maybe type, 118–119Applicative implementation, 229–230for folds and monoids, 262as functor, 147–148identifying, 151implementation of >>=, 280as instance of Monoid, 260–261as monad, 269–271wrapping with newtype, 261

mconcat function, using with Monoid type class, 252–254, 261

mempty functionusing with Monoid type class, 252, 254–255using with Writer type, 303vs. mzero, 288–289

messagesdecoding, 94encoding, 93

minBound function, using with Bounded type, 31

min prefix function, calling, 4minus (-) operator, using with sections, 62module functions

Caesar cipher, 93–94counting words, 90–91finding numbers, 95–98list management, 91–92on strict left folds, 94–95

Learn You a Haskell for Great Good! © 2011 by Miran Lipovača

Page 9: Learn You a Haskell for Great Good! - nostarch.com · INDEX 365 birds ignoring in Pierre example, 278–280 representing in Pierre example, 275–278 BMI (body mass index) calculation

INDEX 371

modules. See also functionsaccessing from GHCi, 88advantages of, 87exporting functions, 104exporting shapes in, 113–114geometry, 104–106hierarchical, 106–107importing, 88–89loosely coupled, 87qualified imports of, 89reading source code for, 89referencing functions from, 89

monadic functionscomposing, 335–336FilterM, 328–331FoldM, 331–332join, 326–328liftM, 323–326

Monad instance, 311monad laws, 292–293, 339–340MonadPlus type class, 288monads, 323. See also do expressions; list

monad; monoids; Reader monad; State monad; Writer monad

applying functions, 275–276associativity, 294–296do notation, 280–285functions as, 311guard function, 289left identity, 293making, 336–341Maybe types as, 269–271as monoids, 288in mtl package, 297nested use of >>=, 280nondeterministic values, 285–287purpose of, 268–269right identity, 294using with trees, 358–359

MonadState type class, 318–319Monad type class

>> function, 273, 279>>= (bind) function, 272–273fail function, 273, 278, 284Maybe instance, 273return function, 272

monoids. See also monadsAll type, 257Any newtype constructor, 256–257attaching to values, 302Bool type, 256–257bytestrings as, 300comparing strings, 258–259composition of, 252Data.Monoid module, 255

defined, 252folding with, 262–265laws, 253, 255lists as, 253–254, 300monads as, 288newtype keyword, 243–244numbers as, 254–255Ordering type, 257–259type class, 252using with Writer monad, 306–307

Monoid type classdefining, 252mappend function, 252, 254, 263mconcat function, 252–254, 261mempty function, 252, 254–255newtype keyword, 243–244

monoid values, including, 304mtl package, monads in, 297multiplication (*) function, 3mzero vs. mempty, 288–289

N

"\n" (newline) character, adding, 180names

defining, 8functions as, 7

needle and haystack lists, 91–92negative number constants, 2newline ("\n") character, adding, 180newStdGen action, 196newtype declarations, using record syntax

in, 250newtype keyword, 249–250

vs. data keyword, 244–245, 248–249using, 247–249using with monoids, 243–244using with Product and Sum types, 255–256using with type class instances, 246–247using with Writer type, 302wrapping Maybe with, 261

newtype wrapper, using with State monad, 317

NO! alert, 143, 145nondeterministic values

representing, 336using with monads, 285–287

not Boolean operator, 2not-equal-to (/=) operator, 3, 28Nothing value

in do notation, 281in pattern matching, 284–285producing in Banana on a Wire, 278–279

null function, using with lists, 11number constants, negative, 2

Learn You a Haskell for Great Good! © 2011 by Miran Lipovača

Page 10: Learn You a Haskell for Great Good! - nostarch.com · INDEX 365 birds ignoring in Pierre example, 278–280 representing in Pierre example, 275–278 BMI (body mass index) calculation

372 INDEX

number ranges, listing, 13–15numbers. See also random generators; RPN

expressionsconverting characters into, 96filtering, 288finding via modules, 95–98getting chain of, 69–70guessing, 196–197inserting in phoneBook, 101–102as monoids, 254–255

Num type class, 32, 140

O

odd function, using with lists, 16operations

precedence of, 4using in expressions, 2

or (||) Boolean operator, 2Ordering type, using with monoids, 257–260order of operations, specifying, 2Ord type class, 28–29, 125–126, 250otherwise guards, 41output, filtering via list

comprehensions, 288

P

package, defined, 297pairs, storing data in, 20parameterized types, 120–122parameters, using = operator with, 5parentheses, ()

minimizing use of, 81, 83placement with functions, 7using with operations, 2, 5using with sections, 62

pattern matching, 35–37as-pattern, 40error function, 39failure in do notation, 284–285failure of, 37on function parameters, 48–49with let expressions, 46with list comprehensions, 38–40with lists, 38–40tell function, 39with tuples, 37–38using with constructors, 111using with monads, 338using with newtype keywords, 247using with type class instances, 140with where keyword, 44–45x:xs pattern, 38

patternsvs. guards, 40–41using with RPN functions, 206

people, describing via data types, 123–124performance

comparing via Writer monad, 309–310enhancing via bytestrings, 202

period (.), using with functions, 89phoneBook

association list, 99, 101–104using type synonyms with, 128–129

Pierre exampleof do notation, 282–284of monads, 274–280

plus (+) operator, 3, 5Point data type, using with shapes, 112–113point-free style

converting function to, 206defining functions in, 84–85

pole, representing in Pierre example, 274–277

polymorphic functions, 27pop function, using with stacks,

314–315, 317powerset, getting, 330predicates

adding to list comprehensions, 16–17using with filter function, 67

prefix functions, calling, 3–4Prelude> prompt, 1printing

functions, 63text files to terminal, 180–181

print I/O function, 162–163probabilities, expressing, 337–339problems, implementing solutions to, 205Product type, using with monoids, 255–256programs, 87

adding logging to, 304–306exiting, 174

prompt, changing, 1pure method

using with applicative functors, 228–230, 232

using with zip lists, 237push function, using with stacks, 314–315putChar I/O function, 162put function, using with state, 318–319putStr I/O function, 161–162putStrLn function, type of, 155

Q

quicksort algorithm, 56–58

Learn You a Haskell for Great Good! © 2011 by Miran Lipovača

Page 11: Learn You a Haskell for Great Good! - nostarch.com · INDEX 365 birds ignoring in Pierre example, 278–280 representing in Pierre example, 275–278 BMI (body mass index) calculation

INDEX 373

R

-> r, as functor and monad, 311random data, getting, 190–198random function, 320. See also functions

RandomGen type class, 191Random type class, 191StdGen type, 192type signature, 191using, 192

random generators, 313. See also numbersmaking, 192regenerating, 196

randomness and I/O, 195–198randoms function, 194–195random string, generating, 195–196ranges. See also list ranges

using with floating-point numbers, 15using with lists, 13–15

Rational data type, 337readability, improving via where keyword, 43Reader monad, 312. See also monadsreadFile function, 179reading files, 175–180Read type class, 29–31record syntax

using in newtype declarations, 250using to create data types, 116–117

rectangles, representing, 110–112recursion, 51

approaching, 58base case, 51in Heathrow to London example, 215in mathematics, 51–52using with applicative functors, 239using with Functor type class, 148–149

recursive data structures, 132–137. See also data types

algebraic data types, 132–133binary search tree, 135–137infix functions, 133–135

recursive definition, 194recursive functions, 36, 38. See also

functionsdefining, 51elem, 55–56maximum, 52–53operating on lists, 99repeat, 55replicate, 53–54reverse, 55take, 54–55writing, 52–53zip, 55–56

repeat functionusing recursively, 55using with lists, 14

replicate functionusing recursively, 53–54using with lists, 15

return functionin Monad type class, 272using with Writer type, 303

reverse functionusing fold with, 76–77using recursively, 55using with lists, 11

reverse polish notation (RPN), 203–208right fold function, 75–76. See also foldr

functionright triangle, finding, 21–22Right value, feeding to functions, 322road system

getting from input, 215–216representing, 211–212

RPN (reverse polish notation), 203–208RPN calculator

failures, 334folding function, 333–334making safe, 332–334reads function, 333

RPN expressions, calculating, 204. See also expressions; numbers

RPN functions. See also functionssketching, 205–206writing, 205–207

RPN operators, 207–208

S

scanl function, 79–80scanr function, 79–80sections, using with infix functions, 62–63semicolon (;), using with let expressions, 46sequenceA function, using with applicative

functors, 239–242sequence I/O function, 164–165set comprehensions, 15shapes

exporting in modules, 113–114improving with Point data type, 112–113representing, 110–112

shortlinesonly.hs program, compiling, 173shortlines.txt file

redirecting contents of, 173saving, 172

Show type class, 29side effects, 153–154

Learn You a Haskell for Great Good! © 2011 by Miran Lipovača

Page 12: Learn You a Haskell for Great Good! - nostarch.com · INDEX 365 birds ignoring in Pierre example, 278–280 representing in Pierre example, 275–278 BMI (body mass index) calculation

374 INDEX

snd function, using with pairs, 20sorting lists, 56–58source code, reading for modules, 89Sphere.hs file, in Geometry module, 106square brackets ([]), using with lists, 7, 24square roots, getting for natural

numbers, 80stack overflow errors, 94, 216stacks

keeping for RPN functions, 205–206modeling for stateful computations,

314–315popping elements from, 314pushing elements to, 314

state, getting and setting, 318–319stateful computations, 313–314

assigning types to, 314stack modeling, 314–315

State monad. See also monadsand randomness, 320using, 315–318

steps, using with ranges in lists, 13–14String and [Char] type, 30, 127–128strings, 8

comparing via monoids, 258–259converting to uppercase, 128encoding, 93getting, 196getting from input streams, 171–173isPrefixOf function, 92processing files as, 199representing values as, 29

String type, using with type synonyms, 129, 131–132

subclassing type classes, 140subtrees, focusing on, 346–347succ: function, calling, 4sum function

using with fold, 74using with lists, 12, 17–18

Sum type, using with monoids, 255–256System.Environment module

getArgs I/O action, 184–185getProgName I/O action, 184–185

System.IO, openTempFile function, 182System.Random module

getStdGen I/O action, 195mkStdGen function, 192random function, 191–192

T

:t (type) command, 24, 26, 65tail function, using with lists, 10–11

tails function, 91–92take function

using recursively, 54–55using with lists, 12

takeWhile function, 69, 80task list program, 188–189. See also lists

add function, 186–187, 190bad input, 190calling, 186–187dispatch function, 189–190implementing functions, 186–187list-viewing functionality, 187remove function, 187–188running, 189view function, 187

tasks. See to-do listtell function, using with log values,

305–306terminal

printing text files to, 180–181reading from, 175writing to, 175

text files, printing to terminal, 180–181threeCoins stateful computation, 320thunk, defined, 199to-do list

adding tasks to, 185appendFile function, 180bracketOnError function, 183cleaning up, 183–184deleting items from, 181–183functionality, 185removing tasks from, 186viewing tasks, 186

traffic light, defining states of, 139–140, 144–145

trees. See also zippersbalancing, 135converting to lists, 265going to tops of, 351manipulating under focus, 350–351mapping, 148moving up in, 348–350nodes for monoids, 265nonempty node for monoids, 264providing safety nets for, 358–360representing breadcrumbs, 346–348subtrees of, 346–347using monads with, 358–359using with folds and monoids, 263in zippers example, 344–346

Tree type constructor, as instance of Func-tor, 148–149

triangle, right, 21–22

Learn You a Haskell for Great Good! © 2011 by Miran Lipovača

Page 13: Learn You a Haskell for Great Good! - nostarch.com · INDEX 365 birds ignoring in Pierre example, 278–280 representing in Pierre example, 275–278 BMI (body mass index) calculation

INDEX 375

triplespattern matching, 38using with road system, 212

True Boolean value, 2–3tuples

changing vectors to, 19fixed size of, 19–20vs. lists, 18, 20, 24pairs, 19–20pattern matching with, 37–38triples, 19, 21–22as types, 26using, 19–20using commas with, 19using parentheses with, 19using with list comprehensions, 21–22using with road system, 212using with shapes, 110

two-dimensional vector, representing, 19–20

type annotations, 29type class constraints, 120–121type classes, 27, 33, 122–123. See also

derived instancesBounded, 31–32, 126–127displaying instances of, 142–143Enum, 31, 126–127Eq, 28, 123–124, 138–139, 141Floating, 32Functor, 146–150instances of, 141–143Integral, 33minimum complete definition of, 139Monad, 272–273Num, 32open quality of, 217Ord, 28–29, 125–126Read, 29–31, 124–125reviewing, 138Show, 29, 124–125subclassing, 140using, 250YesNo, 143–146

type class instances, using newtype with, 246–247

type constructors, 117. See also data typesapplying types to, 150–152as instances of Functor type class, 218,

225–226parameters, 150type parameters for, 141vs. value constructors, 122, 130

type declarations, 24–25, 205in higher-order functions, 63for zipWith function, 64

type inference, 23type instances, making, 139–140type keyword, 128, 249type names, capitalization of, 24, 26type parameters, 117–119. See also

data typespassing types as, 118using, 119–121

types. See also data typesBool, 26Char, 26Double, 26Float, 25–26of functions, 24Int, 25Integer, 25tuples as, 26

type signatures, 110type synonyms, 127–132, 249–250

Either a b type, 130–132for knight’s position, 290parameterizing, 129–130for zipper in filesystem, 355

type system, 23type variables, 26–27, 231

U

undefined value, 247–248underscore (_)

in pattern matching, 38using with lists, 18

V

value constructorsfor Either a b type, 130–131exporting, 113–114as functions, 110, 112, 114parameters, 117vs. type constructors, 122, 130using .. (dots) with, 113–114using with shapes, 110

values. See also log valuesadding context of failure to, 321applying functions to, 347attaching monoids to, 302concept of, 343expressing as strings, 29mapping keys to, 98–104reducing data structures to, 73returning in functions, 6–7testing for equality, 3using Ord type class with, 28–29

Learn You a Haskell for Great Good! © 2011 by Miran Lipovača

Page 14: Learn You a Haskell for Great Good! - nostarch.com · INDEX 365 birds ignoring in Pierre example, 278–280 representing in Pierre example, 275–278 BMI (body mass index) calculation

376 INDEX

values with contexts, using monads with, 268–269

variablesbinding to, 39binding via let expressions, 45

vectorschanging to tuples, 19implementing types for, 121–122

vertical pipe (|)using with data keyword, 109using with data types, 122using with guards, 41

W

when I/O function, 163–164where bindings vs. let expressions, 45–46where blocks, functions in, 45where keyword, 42–43

pattern matching with, 44–45scope of, 44

while loops, 198withFile function, using in I/O, 177–178words, counting, 90–91words.txt file, creating and saving, 175writeFile function, 179–180Writer monad, 298–300. See also monads

adding logging to programs, 304–306applyLog function, 299changing log type, 300comparing performance, 309–310difference lists, 307–309inefficient list construction, 306–307vs. State monad, 316using do notation with, 303–304using monoids with, 300–302, 306–307

Writer type, 302–303writing files, 175–180

X

x:xs pattern, using, 38

Y

YEAH! alert, 143, 145YesNo type class, 143–146

Z

zip functionusing recursively, 55–56using with pairs, 20

zip lists, 237, 244. See also listszippers. See also data structures; trees

defined, 350filesystem example, 353–358focus of, 350–351for lists, 352–353using with data structures, 352

zipWith function, 64–65, 73

Learn You a Haskell for Great Good! © 2011 by Miran Lipovača