Haskell Language
#haskell
www.dbooks.org
Table of Contents
About 1
Chapter 1: Getting started with Haskell Language 2
Remarks 2
Features: 2
Versions 2
Examples 3
Hello, World! 3
Explanation: 4
Factorial 5
Variation 1 5
Variation 2 5
Fibonacci, Using Lazy Evaluation 6
Getting started 7
Online REPL 7
GHC(i) 7
More advanced tools 9
Primes 9
Below 100 9
Unlimited 10
Traditional 10
Optimal trial division 10
Transitional 10
The Shortest Code 10
Declaring Values 10
Chapter 2: Applicative Functor 12
Introduction 12
Remarks 12
Definition 12
Examples 12
Alternative definition 12
Common instances of Applicative 13
Maybe 13
Lists 13
Infinite streams and zip-lists 13
Functions 14
Chapter 3: Arbitrary-rank polymorphism with RankNTypes 16
Introduction 16
Syntax 16
Examples 16
RankNTypes 16
Chapter 4: Arithmetic 17
Introduction 17
Remarks 17
The numeric typeclass hierarchy 17
Examples 19
Basic examples 19
`Could not deduce (Fractional Int) ...` 19
Function examples 20
Chapter 5: Arrows 21
Examples 21
Function compositions with multiple channels 21
Chapter 6: Attoparsec 23
Introduction 23
Parameters 23
Examples 23
Combinators 23
Bitmap - Parsing Binary Data 24
Chapter 7: Bifunctor 26
Syntax 26
Remarks 26
www.dbooks.org
Examples 26
Common instances of Bifunctor 26
Two-element tuples 26
Either 26
first and second 27
Definition of Bifunctor 27
Chapter 8: Cabal 28
Syntax 28
Examples 29
Install packages 29
Working with sandboxes 29
Chapter 9: Category Theory 31
Examples 31
Category theory as a system for organizing abstraction 31
An example 31
A hint of Category Theory 31
Definition of a Category 32
Haskell types as a category 33
Definition of the category 33
Isomorphisms 33
Functors 33
Monads 34
Product of types in Hask 34
Categorical products 34
Products in Hask 35
Uniqueness up to isomorphism 35
Uniqueness of the decomposition 36
Coproduct of types in Hask 36
Intuition 36
Categorical coproducts 36
Coproducts in Hask 36
Haskell Applicative in terms of Category Theory 37
Chapter 10: Common functors as the base of cofree comonads 38
Examples 38
Cofree Empty ~~ Empty 38
Cofree (Const c) ~~ Writer c 38
Cofree Identity ~~ Stream 38
Cofree Maybe ~~ NonEmpty 39
Cofree (Writer w) ~~ WriterT w Stream 39
Cofree (Either e) ~~ NonEmptyT (Writer e) 39
Cofree (Reader x) ~~ Moore x 40
Chapter 11: Common GHC Language Extensions 41
Remarks 41
Examples 41
MultiParamTypeClasses 41
FlexibleInstances 41
OverloadedStrings 42
TupleSections 42
N-tuples 42
Mapping 43
UnicodeSyntax 43
BinaryLiterals 44
ExistentialQuantification 44
LambdaCase 45
RankNTypes 46
OverloadedLists 47
FunctionalDependencies 47
GADTs 48
ScopedTypeVariables 49
PatternSynonyms 49
RecordWildCards 50
Chapter 12: Common monads as free monads 51
www.dbooks.org
Examples 51
Free Empty ~~ Identity 51
Free Identity ~~ (Nat,) ~~ Writer Nat 51
Free Maybe ~~ MaybeT (Writer Nat) 52
Free (Writer w) ~~ Writer [w] 52
Free (Const c) ~~ Either c 52
Free (Reader x) ~~ Reader (Stream x) 53
Chapter 13: Concurrency 54
Remarks 54
Examples 54
Spawning Threads with `forkIO` 54
Communicating between Threads with `MVar` 54
Atomic Blocks with Software Transactional Memory 55
atomically :: STM a -> IO a 56
readTVar :: TVar a -> STM a 56
writeTVar :: TVar a -> a -> STM () 56
Chapter 14: Containers - Data.Map 57
Examples 57
Constructing 57
Checking If Empty 57
Finding Values 57
Inserting Elements 58
Deleting Elements 58
Importing the Module 58
Monoid instance 58
Chapter 15: Creating Custom Data Types 60
Examples 60
Creating a simple data type 60
Creating variables of our custom type 60
Creating a data type with value constructor parameters 60
Creating variables of our custom type 61
Creating a data type with type parameters 61
Creating variables of our custom type 61
Custom data type with record parameters 61
Chapter 16: Data.Aeson - JSON in Haskell 63
Examples 63
Smart Encoding and Decoding using Generics 63
A quick way to generate a Data.Aeson.Value 64
Optional Fields 64
Chapter 17: Data.Text 65
Remarks 65
Examples 65
Text Literals 65
Stripping whitespace 65
Splitting Text Values 66
Encoding and Decoding Text 66
Checking if a Text is a substring of another Text 67
Indexing Text 67
Chapter 18: Databases 69
Examples 69
Postgres 69
Parameter substitution 69
Executing inserts or updates 69
Chapter 19: Date and Time 70
Syntax 70
Remarks 70
Examples 70
Finding Today's Date 70
Adding, Subtracting and Comparing Days 70
Chapter 20: Fixity declarations 72
Syntax 72
Parameters 72
Remarks 72
Examples 73
www.dbooks.org
Associativity 73
Binding precedence 73
Remarks 73
Example declarations 74
Chapter 21: Foldable 75
Introduction 75
Remarks 75
Examples 75
Counting the elements of a Foldable structure 75
Folding a structure in reverse 75
An instance of Foldable for a binary tree 76
Flattening a Foldable structure into a list 77
Performing a side-effect for each element of a Foldable structure 77
Flattening a Foldable structure into a Monoid 78
Definition of Foldable 79
Checking if a Foldable structure is empty 79
Chapter 22: Foreign Function Interface 80
Syntax 80
Remarks 80
Examples 80
Calling C from Haskell 80
Passing Haskell functions as callbacks to C code. 81
Chapter 23: Free Monads 83
Examples 83
Free monads split monadic computations into data structures and interpreters 83
Free Monads are like fixed points 84
How do foldFree and iterM work? 84
The Freer monad 85
Chapter 24: Function call syntax 87
Introduction 87
Remarks 87
Examples 87
Parentheses in a basic function call 87
Parentheses in embedded function calls 87
Partial application - Part 1 88
Partial application - Part 2 88
Chapter 25: Function composition 90
Remarks 90
Examples 91
Right-to-left composition 91
Left-to-right composition 91
Composition with binary function 91
Chapter 26: Functor 93
Introduction 93
Remarks 93
Identity 93
Composition 93
Examples 93
Common instances of Functor 93
Maybe 93
Lists 94
Functions 95
Class Definition of Functor and Laws 95
Replacing all elements of a Functor with a single value 96
Polynomial functors 96
The identity functor 96
The constant functor 97
Functor products 97
Functor coproducts 97
Functor composition 98
Polynomial functors for generic programming 98
Functors in Category Theory 99
Deriving Functor 100
www.dbooks.org
Chapter 27: Generalized Algebraic Data Types 101
Examples 101
Basic Usage 101
Chapter 28: GHCJS 102
Introduction 102
Examples 102
Running "Hello World!" with Node.js 102
Chapter 29: Google Protocol Buffers 103
Remarks 103
Examples 103
Creating, building and using a simple .proto file 103
Chapter 30: Graphics with Gloss 105
Examples 105
Installing Gloss 105
Getting something on the screen 105
Chapter 31: Gtk3 107
Syntax 107
Remarks 107
Examples 107
Hello World in Gtk 107
Chapter 32: Higher-order functions 109
Remarks 109
Examples 109
Basics of Higher Order Functions 109
Lambda Expressions 110
Currying 110
Chapter 33: Infix operators 112
Remarks 112
Examples 112
Prelude 112
Logical 112
Arithmetic operators 112
Lists 112
Control flow 113
Custom operators 113
Finding information about infix operators 114
Chapter 34: IO 115
Examples 115
Reading all contents of standard input into a string 115
Reading a line from standard input 115
Parsing and constructing an object from standard input 115
Reading from file handles 116
Checking for end-of-file conditions 117
Reading words from an entire file 117
IO defines your program's `main` action 118
Role and Purpose of IO 119
Manipulating IO values 119
IO semantics 120
Lazy IO 121
IO and do notation 121
Getting the 'a' "out of" 'IO a' 122
Writing to stdout 122
putChar :: Char -> IO () - writes a char to stdout 122
putStr :: String -> IO () - writes a String to stdout 122
putStrLn :: String -> IO () - writes a String to stdout and adds a new line 122
print :: Show a => a -> IO () - writes a an instance of Show to stdout 123
Reading from `stdin` 123
getChar :: IO Char - read a Char from stdin 123
getLine :: IO String - read a String from stdin, sans new line character 123
read :: Read a => String -> a - convert a String to a value 124
Chapter 35: Lens 125
Introduction 125
www.dbooks.org
Remarks 125
What is a Lens? 125
Focusing 125
Other Optics 125
Composition 126
In Haskell 126
Examples 126
Manipulating tuples with Lens 126
Lenses for records 127
Simple record 127
Managing records with repeating fields names 127
Stateful Lenses 128
Getting rid of & chains 128
Imperative code with structured state 128
Writing a lens without Template Haskell 129
Lens and Prism 129
Traversals 130
Lenses compose 130
Classy Lenses 131
Fields with makeFields 131
Chapter 36: List Comprehensions 134
Examples 134
Basic List Comprehensions 134
Patterns in Generator Expressions 134
Guards 135
Nested Generators 135
Parallel Comprehensions 135
Local Bindings 136
Do Notation 136
Chapter 37: Lists 137
Syntax 137
Remarks 137
Examples 138
List Literals 138
List Concatenation 138
List basics 138
Processing lists 139
Accessing elements in lists 139
Ranges 140
Basic Functions on Lists 141
foldl 141
foldr 142
Transforming with `map` 142
Filtering with `filter` 143
Zipping and Unzipping Lists 143
Chapter 38: Logging 145
Introduction 145
Examples 145
Logging with hslogger 145
Chapter 39: Modules 146
Syntax 146
Remarks 146
Examples 146
Defining Your Own Module 146
Exporting Constructors 147
Importing Specific Members of a Module 147
Hiding Imports 147
Qualifying Imports 148
Hierarchical module names 148
Chapter 40: Monad Transformers 149
Examples 149
A monadic counter 149
Adding an environment 149
www.dbooks.org
The requirements changed: we need logging! 150
Doing everything in one go 151
Chapter 41: Monads 153
Introduction 153
Examples 153
The Maybe monad 153
IO monad 155
List Monad 156
Monad as a Subclass of Applicative 157
No general way to extract value from a monadic computation 157
do-notation 157
Definition of Monad 158
Chapter 42: Monoid 160
Examples 160
An instance of Monoid for lists 160
Collapsing a list of Monoids into a single value 160
Numeric Monoids 160
An instance of Monoid for () 161
Chapter 43: Optimization 162
Examples 162
Compiling your Program for Profiling 162
Cost Centers 163
Chapter 44: Overloaded Literals 164
Remarks 164
Integer Literals 164
Fractional Literals 164
String Literals 164
List Literals 164
Examples 165
Integer Numeral 165
The type of the literal 165
choosing a concrete type with annotations 165
Floating Numeral 165
The type of the literal 165
Choosing a concrete type with annotations 165
Strings 166
The type of the literal 166
Using string literals 166
List Literals 167
Chapter 45: Parallelism 168
Parameters 168
Remarks 168
Examples 169
The Eval Monad 169
rpar 169
rseq 170
Chapter 46: Parsing HTML with taggy-lens and lens 171
Examples 171
Extract the text contents from a div with a particular id 171
Filtering elements from the tree 171
Chapter 47: Partial Application 173
Remarks 173
Examples 173
Partially Applied Adding Function 173
Returning a Partially Applied Function 174
Sections 174
A Note on Subtraction 174
Chapter 48: Phantom types 176
Examples 176
Use Case for Phantom Types: Currencies 176
Chapter 49: Pipes 177
Remarks 177
Examples 177
www.dbooks.org
Producers 177
Consumers 177
Pipes 178
Running Pipes with runEffect 178
Connecting Pipes 178
The Proxy monad transformer 179
Combining Pipes and Network communication 179
Chapter 50: Profunctor 182
Introduction 182
Syntax 182
Remarks 182
Examples 182
(->) Profunctor 183
Chapter 51: Proxies 184
Examples 184
Using Proxy 184
The "polymorphic proxy" idiom 184
Proxy is like () 185
Chapter 52: QuickCheck 186
Examples 186
Declaring a property 186
Checking a single property 186
Checking all the properties in a file 186
Randomly generating data for custom types 187
Using implication (==>) to check properties with preconditions 187
Limiting the size of test data 187
Chapter 53: Reactive-banana 189
Examples 189
Injecting external events into the library 189
Event type 189
Behavior type 190
Actuating EventNetworks 191