This action might not be possible to undo. Are you sure you want to continue?
https://pt.scribd.com/doc/61390861/Haskell98Report
08/01/2011
text
original
Simon Peyton Jones (editor)
Copyright notice. The authors and publisher intend this Report to belong to the entire Haskell community, and grant permission to copy and distribute it for any purpose, provided that it is reproduced in its entirety, including this Notice. Modiﬁed versions of this Report may also be copied and distributed for any purpose, provided that the modiﬁed version is clearly presented as such, and that it does not claim to be a deﬁnition of the language Haskell 98.
Contents
I The Haskell 98 Language
1 Introduction 1.1 Program Structure . 1.2 The Haskell Kernel 1.3 Values and Types . 1.4 Namespaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1
3 3 4 4 5 7 7 8 9 9 11 12 13 15 17 17 19 19 20 21 21 22 22 23 23 24 25 26 27 27 28 29
2
Lexical Structure 2.1 Notational Conventions . . . 2.2 Lexical Program Structure . 2.3 Comments . . . . . . . . . . 2.4 Identiﬁers and Operators . . 2.5 Numeric Literals . . . . . . 2.6 Character and String Literals 2.7 Layout . . . . . . . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
3
Expressions 3.1 Errors . . . . . . . . . . . . . . . . . . . . . . 3.2 Variables, Constructors, Operators, and Literals 3.3 Curried Applications and Lambda Abstractions 3.4 Operator Applications . . . . . . . . . . . . . . 3.5 Sections . . . . . . . . . . . . . . . . . . . . . 3.6 Conditionals . . . . . . . . . . . . . . . . . . . 3.7 Lists . . . . . . . . . . . . . . . . . . . . . . . 3.8 Tuples . . . . . . . . . . . . . . . . . . . . . . 3.9 Unit Expressions and Parenthesized Expressions 3.10 Arithmetic Sequences . . . . . . . . . . . . . . 3.11 List Comprehensions . . . . . . . . . . . . . . 3.12 Let Expressions . . . . . . . . . . . . . . . . . 3.13 Case Expressions . . . . . . . . . . . . . . . . 3.14 Do Expressions . . . . . . . . . . . . . . . . . 3.15 Datatypes with Field Labels . . . . . . . . . . 3.15.1 Field Selection . . . . . . . . . . . . . 3.15.2 Construction Using Field Labels . . . . 3.15.3 Updates Using Field Labels . . . . . . i
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
ii 3.16 Expression TypeSignatures . . . . . . . . . . 3.17 Pattern Matching . . . . . . . . . . . . . . . . 3.17.1 Patterns . . . . . . . . . . . . . . . . . 3.17.2 Informal Semantics of Pattern Matching 3.17.3 Formal Semantics of Pattern Matching . 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
CONTENTS
. . . . . . . . . . . . . . . . . . . . 30 30 30 31 34 37 38 39 39 41 42 43 43 45 46 47 47 49 51 51 53 53 54 55 56 57 58 58 59 59 60 61 64 65 66 66 69 69 70 70 71 71 72
Declarations and Bindings 4.1 Overview of Types and Classes . . . . . . . . . . . . . . . . . . . . . . . . . 4.1.1 Kinds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.1.2 Syntax of Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.1.3 Syntax of Class Assertions and Contexts . . . . . . . . . . . . . . . . 4.1.4 Semantics of Types and Classes . . . . . . . . . . . . . . . . . . . . 4.2 UserDeﬁned Datatypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.2.1 Algebraic Datatype Declarations . . . . . . . . . . . . . . . . . . . . 4.2.2 Type Synonym Declarations . . . . . . . . . . . . . . . . . . . . . . 4.2.3 Datatype Renamings . . . . . . . . . . . . . . . . . . . . . . . . . . 4.3 Type Classes and Overloading . . . . . . . . . . . . . . . . . . . . . . . . . 4.3.1 Class Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.3.2 Instance Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . 4.3.3 Derived Instances . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.3.4 Ambiguous Types, and Defaults for Overloaded Numeric Operations 4.4 Nested Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.4.1 Type Signatures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.4.2 Fixity Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.4.3 Function and Pattern Bindings . . . . . . . . . . . . . . . . . . . . . 4.4.3.1 Function bindings . . . . . . . . . . . . . . . . . . . . . . 4.4.3.2 Pattern bindings . . . . . . . . . . . . . . . . . . . . . . . 4.5 Static Semantics of Function and Pattern Bindings . . . . . . . . . . . . . . . 4.5.1 Dependency Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . 4.5.2 Generalization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.5.3 Context Reduction Errors . . . . . . . . . . . . . . . . . . . . . . . 4.5.4 Monomorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.5.5 The Monomorphism Restriction . . . . . . . . . . . . . . . . . . . . 4.6 Kind Inference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Modules 5.1 Module Structure . . . . . . . . . . . . . . . . 5.2 Export Lists . . . . . . . . . . . . . . . . . . . 5.3 Import Declarations . . . . . . . . . . . . . . . 5.3.1 What is imported . . . . . . . . . . . . 5.3.2 Qualiﬁed import . . . . . . . . . . . . 5.3.3 Local aliases . . . . . . . . . . . . . . 5.3.4 Examples . . . . . . . . . . . . . . . . 5.4 Importing and Exporting Instance Declarations 5.5 Name Clashes and Closure . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . .
5
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
CONTENTS
5.5.1 Qualiﬁed names . . . . . 5.5.2 Name clashes . . . . . . . 5.5.3 Closure . . . . . . . . . . Standard Prelude . . . . . . . . . 5.6.1 The Prelude Module . . 5.6.2 Shadowing Prelude Names Separate Compilation . . . . . . . Abstract Datatypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
iii 72 72 74 74 75 75 76 76 79 79 79 79 80 80 81 81 81 81 81 82 82 84 85 86 87 88 89 89 90 90 91 92 93 93 95 95 97 98
5.6
5.7 5.8 6
Predeﬁned Types and Classes 6.1 Standard Haskell Types . . . . . . . . . . . . . . . . 6.1.1 Booleans . . . . . . . . . . . . . . . . . . . 6.1.2 Characters and Strings . . . . . . . . . . . . 6.1.3 Lists . . . . . . . . . . . . . . . . . . . . . . 6.1.4 Tuples . . . . . . . . . . . . . . . . . . . . . 6.1.5 The Unit Datatype . . . . . . . . . . . . . . 6.1.6 Function Types . . . . . . . . . . . . . . . . 6.1.7 The IO and IOError Types . . . . . . . . . . 6.1.8 Other Types . . . . . . . . . . . . . . . . . . 6.2 Strict Evaluation . . . . . . . . . . . . . . . . . . . 6.3 Standard Haskell Classes . . . . . . . . . . . . . . . 6.3.1 The Eq Class . . . . . . . . . . . . . . . . . 6.3.2 The Ord Class . . . . . . . . . . . . . . . . 6.3.3 The Read and Show Classes . . . . . . . . . 6.3.4 The Enum Class . . . . . . . . . . . . . . . 6.3.5 The Functor Class . . . . . . . . . . . . . . 6.3.6 The Monad Class . . . . . . . . . . . . . . . 6.3.7 The Bounded Class . . . . . . . . . . . . . . 6.4 Numbers . . . . . . . . . . . . . . . . . . . . . . . . 6.4.1 Numeric Literals . . . . . . . . . . . . . . . 6.4.2 Arithmetic and NumberTheoretic Operations 6.4.3 Exponentiation and Logarithms . . . . . . . 6.4.4 Magnitude and Sign . . . . . . . . . . . . . 6.4.5 Trigonometric Functions . . . . . . . . . . . 6.4.6 Coercions and Component Extraction . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
7
Basic Input/Output 7.1 Standard I/O Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7.2 Sequencing I/O Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7.3 Exception Handling in the I/O Monad . . . . . . . . . . . . . . . . . . . . . . . .
8
Standard Prelude 101 8.1 Prelude PreludeList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 8.2 Prelude PreludeText . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 8.3 Prelude PreludeIO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
. . . . .1 Array Construction . 10 Speciﬁcation of Derived Instances 10. . . . . . . . . . . . . . . . . . . . . . . . . . . . 9. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4 Derived instances of Read and Show 10. . . . . . . . . . . 14. . . . . . . . . . . . . . 9. . . . . . .3 Layout . . . . 16. . . . . .5 An Example . . . . . . . . . . . . . . . . . . . . . . . . . . 10. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Showing functions 14. . . . . . . . . . . . . . . . .2 Incremental Array Updates . . . . . . . . . 153 13 Complex Numbers 155 13. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 Specialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4 Library Array .1 Library Complex . . . . . . . . . . .2 Library Ix . . . . . . . . . . . . . . .3 Derived instances of Bounded . . . . . . . . . .1 Notational Conventions 9. . . . . . . . . . . .1 Derived instances of Eq and Ord . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .iv 9 Syntax Reference 9. . . . . . . . . . . . . . 172 16 Arrays 16. . . . . . . .1 Accumulated Arrays 16. .3 Miscellaneous . . . . . . . . . . . . . . . .3 Derived Arrays . . . . . . . . . . . . . . . . . . . . . . . . . 16. . . . . . . . . . . . . . . . . . . . . .5 ContextFree Syntax . . . . . . . 15 Indexing Operations 169 15. . . . . . . . . . . . . . .2 Lexical Syntax . . 156 14 Numeric 14. . . . . .1 Inlining . . . . . . . 173 174 174 175 176 176 . . . . . 147 II The Haskell 98 Libraries 149 12 Rational Numbers 151 12. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10. . .2 Reading functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Library Ratio . . . . . 170 15. 9. . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Deriving Instances of Ix . . . . . . . . . . . . . . . . CONTENTS 127 127 128 130 134 136 141 142 142 143 143 145 . . 14. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 Derived instances of Enum . . . . . . . . . . . . . . . . . . 16. . . . . . . . . . . . . 10. . . . . . . .1. . . . . .4 Literate comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4 Library Numeric . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 Compiler Pragmas 147 11. . . . . . . . 159 160 161 161 161 . . . . . . 147 11. . .
. . . . . . . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . 21. . . 21. . . . . . . . . . . . . . . . . . .1 Library Maybe . . . . . . . .2. . . . . . . . . . . . . 21. . . . .3 Reading Ahead . . . . . . . . . . . . . . . . . . . . . . . . . . .2 Reading Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5 Predicates . . . .2 “Set” operations . . . . 21. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2. 21. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21. . . . . .2 Files and Handles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Checking for Input . . . . . . . . . . . . . . .6.7 The “generic” operations 17. . . . . . . .1 Indexing lists . . . . . . . . . . . . . . 21. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197 20 Monad Utilities 20. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8 Handle Properties . . . . . . 21. . . 21. . . . . . . . . . . . . .3 Functions . 17. . . . .7. . . . .CONTENTS 17 List Utilities 17. . . . . . . . . . . . . . . . . . . .7 Repositioning Handles . . . . . . . . .3. . . . . . . . 17. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17. . . . . . . . . . . . . . . . . . . 21 Input/Output 21. . . 21. 20. . . . . . . . . . 17. . . . . . . . . . . . . .1 Flushing Buffers . . . . . . . . . . . . . . . . . . . . . . . 21. . . 194 19 Character Utilities 195 19. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5 Detecting the End of Input . . . . . . . . . . . . . . . . . . . . . . . . . .9. .4 unfoldr . . . . . . . . . . . .9. . . . . . . . . . .1 Opening Files . . . . . . . . . . . . . . . . . .9. . . . . . .3 List transformations . 21. . . . . . . . . . . . . . . . . . . . . . .7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 I/O Errors . . . . . . . . . . . . . . . . . . . .3 Opening and Closing Files . . . . . 21. . . . . . 20. . . . . . . . . . . . . . . . . .1 Revisiting an I/O Position 21. . . . . . . . . . 21. . . . . . . . . . . . . . .2 Seeking to a new Position 21. .2 Class MonadPlus . . . . . . . . . . . . . . . . . 21. . . . . . . . v 179 182 182 183 183 184 184 185 185 186 . 18 Maybe Utilities 193 18.9. . . . . . . . . 201 203 203 204 206 209 212 213 213 214 214 214 214 215 215 215 215 217 217 217 217 218 218 218 218 219 219 219 . . . . . . . . . . .3. . . . . . . 17. . . . . . . . . . . . . . 21. . . . . . .9 Library List .2 SemiClosed Handles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21. . .8 Further “zip” operations . . . . . . . . . . . . . . . . . . . . . . . 21. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17. . . . . . . . . . . . . . . . . . . . . . . . . . . .2 Closing Files . . . . . 17. .5 Text Output . . . . . . .4 Reading The Entire Input . . . . . .4 Determining the Size of a File . . . . .9. . . . . . . . . . . . . .3 File locking . . . . . . . . . . . . . . . .4 Library Monad . . . . . . . . . . . . . . . . . . .9 Text Input and Output . . . . . . . . . . 21. .1 Library Char . . . . . . . . . . . . . .6 The “By” operations . . . . . . . . . . . .1 Standard Handles . . . . . .1 Naming conventions 20.6 Buffering Operations . . . . . . .
. . . . . . . . . . . . . . . . . 240 26 CPU Time 27 Random Numbers 27. . . . . . . . . . . . . . . . . . . . . . . . .2 Copying Files . . . 22 Directory Functions 23 System Functions . . . . . .3 The global random number generator . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241 243 245 247 248 249 251 . . .10Examples . . . . . . . . . . . . . . .2 The Random class . . . . . 219 219 220 221 223 229 24 Dates and Times 231 24. . . . . . . . . . 21. .10. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .vi 21. . . . . . . . . . . . . . . . . . . . . . . . . . Index . . . . . . . . . . . . . . . . . . .1 Library Locale . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234 25 Locale 239 25. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21. . . . . . . . . . . . . . . .11Library IO . . . . . . .1 Summing Two Numbers 21. . CONTENTS . . . . . . . . and the StdGen generator 27. . . . . . .10. . . . . . . .1 The RandomGen class. . . .1 Library Time . . . . . . . . . . . . . . . . References . . . . . 27. . . . . . . . . . . . . . . . . .
It should be suitable for teaching. a stable foundation for real applications development. It should be completely described via the publication of a formal syntax and semantics. May 31. It should be freely available. Curry and Robert Feys in the Preface to Combinatory Logic [2]. all similar in expressive power and semantic underpinnings. 3. research. have published something erroneous.PREFACE vii Preface “Some half dozen persons have written technically on combinatory logic. Goals The committee’s primary goal was to design a language that satisﬁed these constraints: 1. 4. purely functional programming languages. . There was a strong consensus at this meeting that more widespread use of this class of functional languages was being hampered by the lack of a common language. Thus fullness of exposition is necessary for accuracy. It should be based on ideas that enjoy a wide consensus. Curry whose work provides the logical basis for much of ours. 5. named after the logician Haskell B. It should reduce unnecessary diversity in functional programming languages. 2. It was decided that a committee should be formed to design such a language. This document describes the result of that committee’s efforts: a purely functional programming language called Haskell. Anyone should be permitted to implement the language and distribute it to whomever they please. we regard this as evidence that the subject is refractory. and a vehicle through which others would be encouraged to use functional languages. providing faster communication of new ideas.” Haskell B. and applications. and excessive condensation would be false economy here. Oregon. including ourselves. and most of these. Since some of our fellow sinners are among the most careful and competent logicians on the contemporary scene. to discuss an unfortunate situation in the functional programming community: there had come into being more than a dozen nonstrict. including building large systems. 1956 In September of 1987 a meeting was held at the conference on Functional Programming Languages and Computer Architecture (FPCA ’87) in Portland. even more than it is ordinarily.
It is not a . it was decided that a stable variant of Haskell was needed. incorporating experimental features. much larger than I had anticipated. As Haskell becomes more widely used. Resolve ambiguities. This document is the outcome of this process of reﬁnement. It includes both the Haskell 98 Language Report and the Libraries Report. it had become clear that many programs need access to a larger set of library functions (notably concerning input/output and simple interaction with the operating system). The original Haskell Report covered only the language. Haskell has indeed evolved continuously since its original publication.viii PREFACE Haskell 98: language and libraries The committee intended that Haskell would serve as a basis for future research in language design. many typographical errors and infelicities had been spotted. With reluctance. making some simpliﬁcations. Haskell 98 was conceived as a relatively minor tidyup of Haskell 1. so every change was instead proposed to the entire Haskell mailing list. The original committees ceased to exist when the original Haskell 98 Reports were published. this stable language is the subject of this Report. By the middle of 1997. This task turned out to be much. and is called “Haskell 98”. A separate effort was therefore begun by a distinct (but overlapping) committee to ﬁx the Haskell 98 Libraries. and I have adopted hundreds of (mostly small) changes as a result of their feedback. If these program were to be portable. I took on the role of gathering and acting on these corrections. The Haskell 98 Language and Library Reports were published in February 1999.4). and constitutes the ofﬁcial speciﬁcation of both. with the following goals: Correct typographical errors. together with a standard library called the Prelude. and hoped that extensions or variants of the language would appear. the Report has been scrutinised by more and more people. and removing some pitfalls for the unwary. make small changes to make the overall language more consistent. there had been four iterations of the language design (the latest at that point being Haskell 1. Revising the Haskell 98 Reports After a year or two.4. At the 1997 Haskell Workshop in Amsterdam. Clarify obscure passages. for the foreseeable future. It is intended to be a “stable” language in sense the implementors are committed to supporting Haskell 98 exactly as speciﬁed. a set of libraries would have to be standardised too. By the time Haskell 98 was stabilised.
Haskell Resources The Haskell web site http://haskell. including: pattern guards.org gives access to many useful resources. There is more besides. or use Haskell for teaching. The entire text of both Reports is available online (see “Haskell resources” below). functional dependencies. and some familiarity with functional languages is assumed. it provides a stable point of reference. Haskell 98 does not impede these developments. Instead. including: monadic state. Type system innovations. local universal polymorphism and arbitrary ranktypes. so that those who wish to write text books. can do so in the knowledge that Haskell 98 will continue to exist. going well beyond Haskell 98. Control extensions. including: . For example. existential types. including: multiparameter type classes.PREFACE ix tutorial on programming in Haskell such as the ‘Gentle Introduction’ [6]. metaprogramming facilities. at the time of writing there are Haskell implementations that support: Syntactic sugar. concurrency. lexically scoped type variables. exceptions. recursive donotation. Extensions to Haskell 98 Haskell continues to evolve.
x PREFACE Online versions of the language and library deﬁnitions. including a complete list of all the differences between Haskell 98 as published in February 1999 and this revised version. by an active community of researchers and application programmers. via the Haskell mailing list. and continues to be sustained. suggest improvements to. Details of the Haskell mailing list. Implementations of Haskell. Those who served on the Language and Library committees. Here they are. You are welcome to comment on. in particular. and criticise the language or its presentation in the report. Chalmers University) Thomas Johnsson (Chalmers University) Mark Jones (Yale University. Applications of Haskell. devoted a huge amount of time and energy to the language. Contributed Haskell tools and libraries. Tutorial material on Haskell. University of Nottingham. Oregon Graduate Institute) Erik Meijer (Utrecht University) Rishiyur Nikhil (MIT) John Peterson (Yale University) Simon Peyton Jones [editor] (University of Glasgow. with their afﬁliation(s) for the relevant period: Arvind (MIT) Lennart Augustsson (Chalmers University) Dave Barton (Mitre Corp) Brian Boutel (Victoria University of Wellington) Warren Burton (Simon Fraser University) Jon Fairbairn (University of Cambridge) Joseph Fasel (Los Alamos National Laboratory) Andy Gordon (University of Cambridge) Maria Guzman (Yale University) Kevin Hammond (Uniiversity of Glasgow) Ralf Hinze (University of Bonn) Paul Hudak [editor] (Yale University) John Hughes [editor] (University of Glasgow. Building the language Haskell was created. Microsoft Research Ltd) . Oregon Graduate Institute) Dick Kieburtz (Oregon Graduate Institute) John Launchbury (University of Glasgow.
Andreas Rossberg. John Meacham. Jose Labra. . Ross Paterson. Nimish Shah. Thomas Hallgren. APL. Gofer. Manuel Chakravarty. Stephen Price. Dylan Thurston. Henrik Nilsson. Ketil Malde. Michael Fryers. Bjarte M. Graeme Moss. Klemens Hemm. Jones. Østvold. Ian Lynagh. Tony Warnock. Satish Thatte. Pradeep Varma. Chris Okasaki. Chris Clack. and Bonnie Yantis. Arthur Norman. Guy Cousineau. Carl Witty. Stefan Kahrs. Patrick Sansom. Christian Sievers. Feliks Kluzniak. Mike Gunter. Laura Dutton. Andy Gill. Hope and Hope . Cordy Hall. Jim Mattson. Although it is difﬁcult to pinpoint the origin of many ideas. Id. George Russell. Randy Michelsen. Simon Thompson. Michael Webber. Rosser. Chris Fasel. Tom Thomson. Randy Hudson. Simon Marlow. Stuart Wray. dozens of other people made helpful contributions. Dean Herington. Ken Takusagawa. Keith Wansbrough. Larne Pekowsky. Michael Schneider. Craig Dickson. Richard Bird. Simon B. Josef Svenningsson. Sigbjorn Finne. Sten Anderson. Mark Tullsen. Curry. and others on the lambda calculus. Olaf Chitil. Jan Skibinski. Lauren Smith. SiauCheng Khoo. Nick North. Mike Thyer. Ian Holyer. Tom Blenko. David Tweed. 1 Miranda is a trademark of Research Software Ltd. Amir Kishon. Landin’s ISWIM. John Robson. Malcolm Wallace. Kent Karlsson. Magnus Carlsson. some small but many substantial. They are as follows: Kris Aerts. Paul Callaghan. Andy Moran. ML and Standard ML. Bjorn Lisper. Marcin Kowalczyk. Matt Harden. AnttiJuhani Kaijanaho. Jan Kort. Chris Dornan. In addition. Duke Briscoe. Raman Sundaresh. Mike Joy. Michael Marte. the following languages were particularly inﬂuential: Lisp (and its modernday incarnations Common Lisp and Scheme). Tony Davie. Olaf Lubeck. Paul Otto. Mark Hall. Backus’s FP [1]. Finally. Sisal. Stephen Blott. Julian Seward. Felix Schroeter. Stef Joosten. Mark Carroll. Fergus Henderson. Alexander Jacobson. Gary Memovich. Robert Jeschofnik. it is right to acknowledge the inﬂuence of many noteworthy programming languages developed over the years. Ralf Hinze. Orjan Johansen. Franklin Chen. Ian Poole. Patrik Jansson. Sergey Mechveliani. Tommy Thorn. Pat Fasel. Sven Panne. Hans Aberg. Bob Hiromoto. Rinus Plasmeijer. Jeff Lewis.PREFACE Mike Reeve (Imperial College) Alastair Reid (University of Glasgow) Colin Runciman (University of York) Philip Wadler [editor] (University of Glasgow) David Wise (Indiana University) Jonathan Young (Yale University) xi Those marked [editor] served as the coordinating editor for one or more revisions of the language. Mark Lillibridge. Wolfram Kahl. Christian Maeder. Without these forerunners Haskell would not have been possible. Libor Skarvada. Nic Holt. Richard Kelsey. Pablo Lopez. and Turner’s series of languages culminating in Miranda 1 . Jerzy Karczmarczuk. Clean. Dave Parrott. aside from the important foundational work laid by Church. Rick Mohr. Sandra Loosemore.
September 2002 PREFACE .xii Simon Peyton Jones Cambridge.
Part I The Haskell 98 Language 1 .
.
At the topmost level a Haskell program is a set of modules. we describe the abstract syntactic and semantic structure of Haskell. and ﬂoatingpoint numbers. including lists. interpreted. Haskell is both the culmination and solidiﬁcation of many years of research on nonstrict functional languages. nonstrict semantics. deﬁned in Chapter 2. This report deﬁnes the syntax for Haskell programs and an informal abstract semantics for the meaning of such programs. We leave as implementation dependent the ways in which Haskell programs are to be manipulated.” 4. of which there are several kinds. Declarations deﬁne things such as ordinary values. patternmatching. list comprehensions. arrays. 3 . This includes such issues as the nature of programming environments and the error messages returned for undeﬁned programs (i. compiled. expressions are at the heart of Haskell programming “in the small. etc. datatypes. purely functional programming language incorporating many recent innovations in programming language design. as well as how it relates to the organization of the rest of the report. static polymorphic typing. 1.1 Program Structure In this section. 3. and ﬁxity information. a module system.e. userdeﬁned algebraic datatypes. An expression denotes a value and has a static type. type classes. The lexical structure captures the concrete representation of Haskell programs in text ﬁles. The top level of a module consists of a collection of declarations.Chapter 1 Introduction Haskell is a general purpose. 1. 2. and a rich set of primitive datatypes. Haskell provides higherorder functions. a monadic I/O system. arbitrary and ﬁxed precision integers. described in Chapter 3. Modules provide a way to control namespaces and to reuse software in large programs. At the next lower level are expressions. programs that formally evaluate to ). all described in Chapter 4. described in Chapter 5. At the bottom level is Haskell’s lexical structure.
Values and types are not mixed in Haskell. If these translations are applied exhaustively. 1. as then else . for types. However. and Chapter 7. INTRODUCTION This report proceeds bottomup with respect to Haskell’s syntactic structure. ¥ ¢ § £ ¤ ¡ ¢ ¦ 1. it is essentially a slightly sugared variant of the lambda calculus with a straightforward denotational semantics. In this Report. However. such as for expresin if sions. Examples of Haskell program fragments in running text are given in typewriter font: let x = 1 z = x+y in z+1 “Holes” in program fragments representing arbitrary pieces of Haskell code are written in italics. literate programming. they are not distinguishable from nontermination. the concrete syntax. and permits not only parametric polymorphism (using a traditional HindleyMilner type structure) but also ad hoc polymorphism. which describes the standard builtin datatypes and classes in Haskell. the speciﬁcation of derived instances. etc. See Section 3.3 Values and Types An expression evaluates to a value and has a static type.e. the type system allows userdeﬁned datatypes of various sorts.2 The Haskell Kernel Haskell has adopted many of the convenient syntactic structures that have become popular in functional programming.4 CHAPTER 1.1. so the language includes no mechanism for detecting or acting upon errors. implementations will probably try to provide useful information about errors. and pragmas supported by most Haskell compilers. the meaning of such syntactic sugar is given by translation into simpler constructs. or overloading (using type classes). Although the kernel is not formally speciﬁed. . Technically. The translation of each syntactic structure into the kernel is given as the syntax is introduced. This modular design facilitates reasoning about Haskell programs and provides useful guidelines for implementors of the language. for declarations. The chapters not mentioned above are Chapter 6. the result is a program written in a small subset of Haskell that we call the Haskell kernel. there are several chapters describing the Prelude. Also. Generally the italicized names are mnemonic. which discusses the I/O facility in Haskell (i. how Haskell programs communicate with the outside world). Errors in Haskell are semantically equivalent to .
type constructors. .4. Names for variables and type variables are identiﬁers beginning with lowercase letters or underscore. 2. NAMESPACES 5 1. These are the only constraints. There are two constraints on naming: 1. An identiﬁer must not be used as the name of a type constructor and a class in the same scope. the other four kinds of names are identiﬁers beginning with uppercase letters. for example. and module names refer to modules.1. those for type variables. and constructor within a single scope. and type classes refer to entities related to the type system. class.4 Namespaces There are six kinds of names in Haskell: those for variables and constructors denote values. Int may simultaneously be the name of a module.
INTRODUCTION .6 CHAPTER 1.
1 Notational Conventions These notational conventions are used for presenting syntax: optional zero or more repetitions grouping choice difference—elements generated by except those generated by fibonacci terminal syntax in typewriter font Because the syntax in this section describes lexical syntax. there is no implicit space between juxtaposed symbols. This syntax depends on properties of the Unicode characters as deﬁned by the Unicode consortium. 2. Haskell uses the Unicode [11] character set..]. we describe the lowlevel lexical structure of Haskell. 7 § ¢ £¡ ¨ ¥¥8 8 8 1 &§ ¢ £¡ A !§ 7 3¢ 8 8 8 @¥¥9 £ § )'% $ " 0(&§#!§ £§ ¢§ ¡ £¡ ¢ ¢ ¦ £¤ ¡ §¥ § § £¡ §¥ § § £ ¦¤ ¢ ¡ ¨ ¦¤ ¢ ¡ ©§¥ § § £ ¢ £ ¡ 7 3¢ ¡§ 7 3¢ 6 4¤ ¦ 2 5 § 3©¦ . all whitespace is expressed explicitly. with productions having the form: Care must be taken in distinguishing metalogical syntax such as and from concrete terminal syntax (given in typewriter font) such as  and [. However. Haskell compilers are expected to make use of new versions of Unicode as they are made available. source programs are currently biased toward the ASCII character set used in earlier versions of Haskell.Chapter 2 Lexical Structure In this chapter. Most of the details may be skipped in a ﬁrst reading of the report.. BNFlike syntax is used throughout. although usually the context makes the distinction clear.
.{} a carriage return a line feed a vertical tab a form feed a space a horizontal tab any Unicode character deﬁned as whitespace CHAPTER 2.2 Lexical Program Structure 8 ( ) .§§ § § ¦ £$ § § § © ¢ 6 6 7 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 §§ § t § 6 7 2 ' 4 3 ' ¦ £$ © ¦ ) 4 2 B2 © ¦§ 7 £ ¦ ¨ 3¦ ¢ )A 98 7 64 #"@¦"%5 3¦ ¢ ¦ 1§¤ 0 0 4 2 ¦ § ¨)§ § ¥ ( § ¦£$ ¦ ¥ 0% ¦ § §£%¢ ¤ % ¦ § 5¤ %§ ¤ ¦¤ $§ 0 ¦ $ ¦ 7 7 § © § ¤ ¤ ¦ § £ ¦ ¡ ' ¢ 7 4 '#4 ¢ 2 ¦ ¤§ ¢ 4 ¨32 ¤ ¦ 4 & $ © § ¥ %§ § ¨¦£ ¥ § ¨¦£ § ¥ ¢ & $ © § ¥ %§ § ¨¦£ ¦ ¦ § #¦ § ¢ ¤ ¤ © 2 4 © ¦ 332 ¡ 2. [ ] ` { } ¤ ¤© ¤ ¥ § 2 " § ! ¢ §¢ © ¥¢ ¤ ¤ © ¦ 7 ¦ 43¤ 3§ ¢ 32 ¡ © ¢ § ¦ ¨¦¤ © § ¥ £ ¤¢ ¡ ¤¥ § ¦ § ¤ § § 7 3§ ¢ ¤ 7 4¦ ¢ ¡ ¢ 7 .˜ any Unicode symbol or punctuation y B 2 4 3 t ¢ h h h h A v f 4 x"$ wg " 5 7 2 ' 4 3 t § ¦ £$ § 7 2 ' 4 3 t © ¢ A B Z any uppercase or titlecase Unicode letter _ : " ’ %¤ ¢ u 8 8 8 @¥¥9 ¦ £$ 2¤ ¢ u ¢ © 2 3© 4 7 ' § £$ 2¤ ¦ ¢u © %¤ ¢ ¢ u ¢7 %¤ S¢RQFP§ 4 32 ¦ © G E C ¦ 4 _ a b z any Unicode lowercase letter 77 !3¢ 4 t § 8 8 8 @¥¥9 ¦ £$ 4 © 77 03¢ ¢ t 4 § £$ ¦ 703¢ 7 4 t © 77 !3¢ §¢© t 4 77 !3¢ § #¥ ¡3 §¢ ¦ ¤ G E QFC © G E S¢RQFC ¢ © G E C 4 ¡ IHFD32 © ¥ © ¢ ¦ § ¦¥ 4 32 ¦ 4 4 2 B2 © 4 2 ¥ ¥2 ¦ 7 ¡ © ¥ © ¦ ¦ ¥ 4 4 ¢ 2 § § ¨)§ § ¥ ( ¦ £$ ' ¨¢ § © ¤ ¥ § ¨¦£ § ¥ ¢ & $ § © § ¥ %¤ § ¨¦£ ¢ ¤£¡ © § ¥ § ¨¦£ § ¤¢ ¡ 1§3¥0 0 4 ¤ 2 ¦ § ¥ ¤ ' #¢ ¢2 ¦ § 0 ¦ ¦¤ $§ §£%¢ ¤7 ¦§ £ ¦ 7 6 6 6 6 7 ¤ 3¢ ¥ § ¡ § 7 3¢ 7 © ¥ ¡ 4 ¢ 4 ¤ ¡&¤ 7 2 ¢ ¡ . LEXICAL STRUCTURE : " ’ 7 ¥ 4 §© § © § § § 2 43© 2¤ ¦ 7 ' 7 3¢ ¡ ¢ 7 § !3¢ ¤ 77 § © ¨¥ '¨ ¡ ¤ ¢ ¥ § ¨¢£¡ ¤ ¨¥ §¢ ¤ § ¥ ¨¦£ § ¢ ¡T ) cRasY`WXrpq7"9 g 24"9 A g hi7¡9 gA " 3¦db`XV GH§¢ C U f f 9 e c a Y W U E ¦ 2 ¡ ! # $ % & * + . / < = > ? \ ˆ  .
If some code is commented out using a nested comment. terminated by “}”. Similarly. == and ˜= are not. for example. “{” starts a nested comment despite the trailing dashes. Instead. and. the ﬁrst unmatched occurrence of the string “}” terminates the nested comment. the longest possible lexeme satisfying the production is read.2. although case is a reserved word. are not valid in Haskell programs and should result in a lexing G E HTC Characters not in the category error. Within a nested comment. A nested comment begins with “{” and ends with “}”. hence. COMMENTS 9 Lexical analysis should use the “maximal munch” rule: at each point. In an ordinary comment. 2. “>” or “” do not begin a comment. then any occurrence of {. as explained in Chapter 11. because both of these are legal lexemes. Nested comments may be nested to any depth: any occurrence of the string “{” within the nested comment starts a new nested comment. although = is reserved. ) and extends to the following newline. cases is not. © § ¥ § ¨¦£ Any kind of is also a proper delimiter for lexemes. a sequence of dashes has no special signiﬁcance. the character sequences “{” and “}” have no special signiﬁcance.4 Identiﬁers and Operators ) ¥ v ¥ £ f ¦f ¤¢24 f ¡ §§ 8 8 8 @¥¥9 § ¦ %¤ ¢7 8¥8¥8 § § § ¦ 8 8 8 @¥¥9 77 !3¢ 4 §© 77 !3¢ ¢ ¤£¡ 8 8 8 @¥¥9 4 §© 4 ¢ ¥ S 7 6 6 6 6 6 §§ § ¦ § §§ § § § S ¥ ¢ §§§ § ¤ 2 ¦ £$ ¢ © ¢ 0 1 9 any Unicode decimal digit 0 1 7 A F a f ’ .3 Comments Comments are valid whitespace. The comment itself is not lexically analysed. No legal lexeme starts with “{”. The sequence of dashes must not form part of a legal lexeme. Nested comments are also used for compiler pragmas.or } within a string or within an endofline comment in that code will interfere with the nested comments. An ordinary comment begins with a sequence of two or more consecutive dashes (e. 2. each “{” is matched by a corresponding occurrence of “}”. For example. however “foo” does start a comment.g. in a nested comment. So.3.
10 CHAPTER 2.> @ ˜ => Operator symbols are formed from one or more symbol characters.5). such as “[]” and “[a. Identiﬁers are case sensitive: name. and Name are three distinct identiﬁers (the ﬁrst two are variable identiﬁers. used as wild card in patterns. In the remainder of the report six different kinds of names will be used: variables constructors type variables type constructors type classes modules ) 4 f ¡$ 4 ¡ ¥ h " 9 f £ f 4 f S¥ X¤¢%w5 §§ ) " 9¡¦fX¤ f24w5¡§ 2 3© ¥ £ f 4 4 ©7 ' 2 4 © 7 ' § @ ¦ %¤ 7 2 ¢7 ' 77 !3¢ 4 §© ¦ ¤ § ¦32 ¦ ¦32 ¦ 32 ¦ ¦ 2¤ § § § ¢ ¢7 6 6 6 6 6 6 6 6 6 2 ¥¢ ¤ ¤ © ¡ ¦ 43¦ 2 © 4 S¤ © ¢ ¦ ¦ § ¥¢ ¤ © ¦ ¦ ¦ ¦ ¤ § ¦ 72 3¥ %§ ¦ © § § § ¢¦ 2 ¤ ¦ 2 2 4 %§ ¢ %§ ¤ . : : : .b]”. Compilers that offer warnings for unused identiﬁers are encouraged to suppress such warnings for identiﬁers beginning with underscore. An operator symbol starting with any other character is an ordinary identiﬁer. this makes its treatment uniform with other parts of list syntax. digits. “_”. Notice that a colon by itself. as deﬁned above. All of the standard inﬁx operators are just predeﬁned symbols and may be rebound. : :: = \  <. although each inﬁx operator can be used in a section to yield partially applied operators (see Section 3. Other than the special syntax for preﬁx negation. However. Identiﬁers are lexically distinguished into two namespaces (Section 1. and single quotes. is treated as a lowercase letter.4): An operator symbol starting with a colon is a constructor. and can occur wherever a lowercase letter can. Underscore. all operators are inﬁx. LEXICAL STRUCTURE ’ case class data default deriving do else if import in infix infixl infixr instance let module newtype of then type where _ An identiﬁer consists of a letter followed by zero or more letters. naMe. This allows programmers to use “_foo” for a parameter that they expect to be unused. the last is a constructor identiﬁer). “:”. and are lexically distinguished into two namespaces (Section 1.4): those that begin with a lowercase letter (variable identiﬁers) and those that begin with an uppercase letter (constructor identiﬁers). is reserved solely for use as the Haskell list constructor. underscores.. “_” all by itself is a reserved identiﬁer.
. . . also. the other four do not. Lexes as this f .g f. (two tokens) F. Qualiﬁed names are discussed in detail in Chapter 5.+ is an inﬁx operator with the same ﬁxity as the deﬁnition of + in the Prelude (Section 4. NUMERIC LITERALS 11 Variables and type variables are represented by identiﬁers beginning with small letters. 4§ ¢ ¡ ¥ 0X 7 ¢ ¦ ¢ ¡ 7 3¢ 3¢ 7 § ¦ 32 ¡ ¦ ¢ 4§ ¦ 7 4 § ¡ 3¢ 4 § ¦ 7 3¢ ¦ § 7 ¢2 ¦ 4§ ¢ ¡ ¥ 0o 0x 0O 7 3¢ 43332 ¨ © ¦ 4 © 3¤ `¨ ¦ 72 3¥ %§ ¨ © § ¦ 32 ¨ ¢ %§ ¨ § § S ¢ . . for example.4.g F. variables and constructors have inﬁx forms. F. g (three tokens) F. 2. F. ¦ ¢ ¦ ¢ § 2 7 ¢ 4§ 7 3¢ ¦ ¥ ¦ ¦ § ¦ ¦ § ¦ ¦ § ¦ ¦ § ¦ ¦ § ¦ ¦ § § § ¡ ¥ ¢ 2 4 2 4 2 4 2 4 2 4 2 4 6 6 6 6 6 6 6 6 4§ 7 6 3¢ 6 6 § ¦ ¦ ¥ 32 4 4 © 3¤ ¤ § ¦ § © ¦ 32 ¦ ¤ ¦ 37 2 © ¦ § § § ¦ 32 ¢ ¢ %§ ¢ ¡ 2 ¢ S ¥ %§ ¢ ¡ ¦ ! .’) F . (two tokens) The qualiﬁer does not change the syntactic treatment of a name. no spaces are allowed between the qualiﬁer and the name. Prelude.5.. This applies to variable.4. . Namespaces are also discussed in Section 1. constructor. ¦ ¤ § `¨ Since a qualiﬁed name is a lexeme. Sample lexical analyses are shown below.. and the other four by identiﬁers beginning with capitals.g (qualiﬁed ‘g’) f . This f.2.5 Numeric Literals §§ § § 2 § § § 2 §§ § § § § § ¦ ¦ 6 7 ¢ ¦ ¢ § 2 73§ ¢ 4 4§ ¨ e E +  ¨ § 32 ¦ ¦ ¢ ¡ .2). type constructor and type class names. but not type variables or module names. . (qualiﬁed ‘.. A name may optionally be qualiﬁed in certain circumstances by prepending them with a module identiﬁer.
“carriage return” (\r).6 Character and String Literals ’ ’ \ \& ’ " " " \ \ o x a b f n r t v \ " ’ & ˆ NUL SOH STX ETX EOT ENQ ACK BEL BS HT LF VT FF CR SO SI DLE DC1 DC2 DC3 DC4 NAK SYN ETB CAN EM SUB ESC FS GS RS US SP DEL [ \ ] ˆ _ \ \ ¢ ) h ) h §§ Character literals are written between single quotes. octal (e. a double quote " may be used in a character. Thus "\&" is equivalent to "" and the character ’\&’ is disallowed. numeric escape characters in strings consist of all consecutive digits and may be of arbitrary length. Similarly.4. but must be escaped in a character. octal (preﬁxed by 0o or 0O) or hexadecimal notation (preﬁxed by 0x or 0X).g. this ensures that a decimal point cannot be mistaken for another use of the dot character. “new line” (\n). as in ’a’. Negative numeric literals are discussed in Section 3. © 7 3¢ 4§ ¤ ¥ ¢ 4§ ¢¡ ¥ § 2 ¦ ¢ 7 3¢ ¦ 7 ¢ © © ¡5¢ ¡ 5¢ ¢ ¨£¡ ) © © ¡ 5¢ ¢ ¨£¡ § §#¥¦£ ¤ ¥ § ¨¦£ § ¥ © y ¢ 2¤ ¢ u ¢ ¤§ ¦ © © § ¨¥ § ¨¥ ¤ ¢ ¦ ¤ ¡§¢ ¤ ¡ §¢ 7 ¥ 6 6 6 6 6 6 6 § @§ © ¢ © ¤ ¥ ¢ © ¡ §¢ #¦ § ¤ § © 7 ¤ ¤ ¡ ¤ § 5¢¦ ¢ ¢ ¥ ¥ .12 CHAPTER 2. Escape codes may be used in characters and strings to represent special characters.g. \o137) and hexadecimal (e. is parsed as a string of length 1. Integer literals may be given in decimal (the default). “form feed” (\f). For example. similarly. “backspace” (\b). the one ambiguous ASCII escape code. Note that a single quote ’ may be used in a string. This allows one to write long strings on more than one line by writing a backslant at the end of one line and at the start of the next. Numeric escapes such as \137 are used to designate the character with decimal representation 137. “horizontal tab” (\t). "\SOH". A ﬂoating literal must contain digits both before and after the decimal point. A string may include a “gap”—two backslants enclosing white characters—which is ignored. are also provided. and “vertical tab” (\v). Further equivalences of characters are deﬁned in Section 6. \x37) representations are also allowed.2. and strings between double quotes. as in "Hello". The category also includes portable representations for the characters “alert” (\a). LEXICAL STRUCTURE There are two distinct kinds of numeric literals: integer and ﬂoating.1.1. The typing of numeric literals is discussed in Section 6. \ must always be escaped. The escape character \& is provided as a “null character” to allow strings such as "\137\&9" and "\SO\&H" to be constructed (both of length two). Floating literals are always decimal.4. Consistent with the “maximal munch” rule. including control characters such as \ˆX. but must be escaped in a string. 2. Escape characters for the Unicode character set.
Within these explicit open braces. if an illegal lexeme is encountered at a point where a close brace would be legal. A close brace is also inserted whenever the syntactic category containing the layout list ends. For each subsequent line. which can be freely mixed within one program. b and g all part of the same layout list.7. if it is indented the same amount. Figure 2. As an example. then the layout list ends (a close brace is inserted). a close brace is inserted. a single newline may actually terminate several layout lists. and \ˆX.3 gives a more precise deﬁnition of the layout rules. The effect of layout on the meaning of a Haskell program can be completely speciﬁed by adding braces and semicolons in places determined by the layout. 2. LAYOUT 13 "Here is a backslant \\ as well as \137. Haskell programs can be straightforwardly produced by other programs. b = 2 g y = exp2 in exp1 making a." String literals are actually abbreviations for lists of characters (see Section 3. that is.7). then a new item begins (a semicolon is inserted). and if it is indented less. The layout rule matches only those open braces that it has inserted. Note in particular: (a) the line beginning }}. When this happens. if it contains only whitespace or is indented more.2. insert a semicolon or close brace). an empty list “{}” is inserted. then instead of starting a layout. do.pop. The meaning of this augmented program is now layout insensitive. let. \ \a numeric escape character. let. then the previous item is continued (nothing is inserted). the indentation of the next lexeme (whether or not on a new line) is remembered and the omitted open brace is inserted (the whitespace preceding the lexeme may include comments). Section 9. a control character. where the . and layout processing occurs for the current level (i. Informally stated.e. If the indentation of the nonbrace lexeme immediately following a where. The layout (or “offside”) rule takes effect whenever the open brace is omitted after the keyword where. by using layout to convey the same information.7 Layout Haskell permits the omission of the braces and semicolons used in several grammar productions. Because layout is not required. Given these rules. even if a line is indented to the left of an earlier implicit open brace. these rules permit: f x = let a = 1. Also.2 shows the result of applying the layout rule to it. the braces and semicolons are inserted as follows. or of. no layout processing is performed for constructs outside the braces. This allows both layoutsensitive and layoutinsensitive styles of coding.1 shows a (somewhat contrived) module and Figure 2. an explicit open brace must be matched by an explicit close brace. do or of is less than or equal to the current indentation level.
14 CHAPTER 2. (b) the close braces in the where clause nested within the tuple and case expression. corresponding to the depth (3) of the nested where clauses. Stack a) .(top Empty) is an error Figure 2.push :: a > Stack a > Stack a . size ) where data Stack a = Empty  MkStack a (Stack a) push :: a > Stack a > Stack a push x s = MkStack x s size :: Stack a > Int size s = length (stkToLst s) where stkToLst Empty = [] stkToLst (MkStack x s) = x:xs where xs = stkToLst s pop :: Stack a > (a.size s = length (stkToLst s) where {stkToLst Empty = [] .stkToLst (MkStack x s) = x:xs where {xs = stkToLst s }}.(top Empty) is an error Figure 2. case s of r > i r where i x = x) .(pop Empty) is an error . LEXICAL STRUCTURE module AStack( Stack. inserted because the end of the tuple was detected. Stack a) pop (MkStack x s) = (x.(pop Empty) is an error top :: Stack a > a top (MkStack x s) = x . case s of {r > i r where {i x = x}}) .pop :: Stack a > (a. push. inserted because of the column 0 indentation of the endofﬁle token. .pop (MkStack x s) = (x.top :: Stack a > a . push. and (c) the close brace at the very end. pop. top.1: A sample program module AStack( Stack. size ) where {data Stack a = Empty  MkStack a (Stack a) .size :: Stack a > Int .2: Sample program with layout expanded termination of the previous line invokes three applications of the layout rule. top.push x s = MkStack x s . pop.top (MkStack x s) = x } .
these translations preserve both the static and dynamic semantics. we describe the syntax and informal semantics of Haskell expressions. For example. or for left. and may have a double (written as a superscript). with 10 substitutions for and 3 for .Chapter 3 Expressions In this chapter. there are some families of nonterminals indexed by precedence levels . In the syntax that follows. where appropriate. Similarly. ::  15 ¢ ¡ else } ¦ ¡ ¢ ¡ © @§ \ let in if then case of { ¢ S > lambda abstraction let expression conditional case expression ¡ ¡ v v ¡ ¡ ¢ ¡ ¢ S ¡ ¨ ¡ %§ => expression type signature ¢ § ¡ p v §e ¢© v ¨ v 7 ¢ 3¢ S ¡ ¡ ¢ ¡ ¡ ¢¡ © ¦ A!¡ § 8¥8¥8 7 ¡ § ¢ £¡5¢ ¢ ¡ ¢ ¢¡ ¤ 2 ¡ £v §¢ ¡ ¢ ¡ p v §e ¡ ¡ ¢ ¡ ¢ ¥¡ S ¡ ¡ 2 ¢ ¡ s § S § ¢ p v ¨§e ¢ ¦ ¡ ¦ 32 v 2 ¡ ¡ V 2 ¢ S ¡ v v v ¤ ¥¡ ¤ v ¡ 7 ¢ S ¤ ¡ S ¢ ¢ ¡ ( ) ¦ ¤ ¡ 2 ¦ ©32 ¡7 ¡ 2¤ ¢ ¢ ¡ 2 p v £!e ¢ $ ¡ ¡ v ¡ ¦ ¡ ¡ ¡ ¡ ¢ ¢ ¡ ¢ ¡ 7 ¤ 7 § 6 6 6 6 6 6 6 ¤ v ¡ v ¡ v ¡ ¡ ¡ ¢ S ¡ ¡ ¡ ¤ ¢ ¡ ¢ ¡ ¢ ¡ ¢ ¡ ¢ ¡ ¢ ¡ ¢ 7 7 . and (if it is in scope) what it is bound to. index: a letter .11) means the concatMap deﬁned by the Prelude. Free variables and constructors used in these translations always refer to entities deﬁned by the Prelude. “concatMap” used in the translation of list comprehensions (Section 3. . right.or nonassociativity and a precedence level. Except in the case of let expressions. the nonterminals . For example actually stands for 30 productions. including their translations into the Haskell kernel. an associativity variable varies over . A precedencelevel variable ranges from 0 to 9. regardless of whether or not the identiﬁer “concatMap” is in scope where the list comprehension is used.
Negation is the only preﬁx operator in Haskell. .. .. The grammar is ambiguous regarding the extent of lambda abstractions. This f x . it has the same precedence as the inﬁx . ) ] ¤ ¥ £ ¢ Q¢ ( ( [ [ [ ( ( ( ) . } in (x + y) z + (let { .2. ] ¢ £ .. EXPRESSIONS Expressions involving inﬁx operators are disambiguated by the operator’s ﬁxity (see Section 4.4.. Given an unparenthesized expression “ ”. } ¦ . } in x + y y :: Int > a+b :: Int A note about parsing. For example. Sample parses are shown below. ¦ 2 ' . } in x + y let { .2). Consecutive unparenthesized operators with the same precedence must both be either left or right associative to avoid a syntax error.f let z + f x \ x Parses as (f x) + (g y) (.. .16 © @§ CHAPTER 3.(f x)) + y let { . parentheses must be added around either “ ” or “ ” when unless or . ] . the expression p ¢ 8 @e § 2 ¡ ¦ p v £!e ¢ $ ¡ 2 ¢ %e p 8 Q¢ ¡ 2 p v £!e ¢ $ A ¦ ¡ § { .operator deﬁned in the Prelude (see Section 4.1). Figure 4. and conditionals. .. } ¦ § { ( )  right section labeled construction labeled update ) ) ) ¦ .. } in (x + y)) (f x y) :: Int \ x > ((a+b) :: Int) + g y x + y { . .. let expressions.4.. The ambiguity is resolved by the metarule that each of these constructs extends as far to the right as possible. Expressions that involve the interaction of ﬁxities with the let/lambda metarule may be hard to parse.  parenthesized expression tuple list arithmetic sequence list comprehension left section left section right section variable general constructor function application 0 ¡ ¦§ 0 ) A 9 g © ¡ ¨ ¢ 8 8 ¥¥8 ¦ ¦¡ 2 ¢ A ¦ § 0 8¥¥8 ' ¡ ¦ § 0 8 ¦ ¦ ' ' ¢ S ¤ ) 2 v ¡ p v ¢ ¡e ¡ ¢ S ) 2 ¡ v ¡ p v ¢ $0e ¡ 2 ¢ S v p v ¢ 5e A 2 ¡ ¡ v ¡ ¡ 7 ¢ p v £!e ¡ ¢ $ ¡ ¡ $ $ ¢ A ¥8¥8 8 ¡ 7 3¢ ¨ ¥ ¢¡ ¢ ¡¢ ¨ £ 7 ¡ ¢ ¡ ¡ ¡ ¢ S ¢ 8¡ ¥¥8 ¡ ¡ ¡ 8 ¡¡ ¢S ¥8¥8 ¡¢ ¡ ¡ 8 ¡¡ ¡ ¡ ¢ ¡ § § ¤ 7 3¢ ¦ 2 7 ¡ ¢ S 4§ ¢ © do { } do expression ¨ ¤ ¡ ¡ ¢ S¢0 ¢ ¢ S¢0 ' ¢ 6 6 ' ¡ ¡ ¢ S ¢ ¡ 0 ¢ ¢ .
are indistinguishable by a Haskell program from nontermination. when demanded. a value of any type may be bound to a computation that.3. all Haskell types include . That is. Since Haskell is a nonstrict language. denoted by .1 Errors Errors during expression evaluation. so the expression must parse thus: (let x = True in (x == x)) == True 17 However. so they may well incorrectly deliver the former parse. the error message is created by the compiler. The actual program behavior when an error occurs is up to the implementation. implementations may well use a postparsing pass to deal with ﬁxities.2 Variables. results in an error. 3. The messages passed to the error function in these translations are only suggestions. 3. implementations may choose to display more or less information when an error occurs. For the sake of clarity. Programmers are advised to avoid constructs whose parsing involves an interaction of (lack of) associativity with the let/lambda metarule. It should also display the string in some systemdependent manner. errors cause immediate program termination and cannot be caught by the user. ERRORS let x = True in x == x == True cannot possibly mean let x = True in (x == x == True) because (==) is a nonassociative operator. Operators. Constructors.1. The Prelude provides two functions to directly cause such errors: error :: String > a undefined :: a A call to error terminates execution of the program and returns an appropriate error indication to the operating system. When evaluated. and Literals ¤ ¢ ¤ § § 7 3¢ ¦ 2 7 6 ¡ ¢ S ¢ variable general constructor . the rest of this section shows the syntax of expressions without their precedences. When undefined is used. Translations of Haskell expressions use error and undefined to explicitly indicate where execution time errors may occur.
as found in the and .1. as deﬁned in the Ratio library.18 CHAPTER 3. (+) x y is equivalent to x + y. Similarly. an operator symbol can be converted to an ordinary identiﬁer by enclosing it in parentheses. and foldr (*) 1 xs is equivalent to foldr (\x y > x*y) 1 xs.% ). where fromRational is a method in class Fractional and Ratio. a ﬂoating point literal stands for an application of fromRational to a value of type Rational (that is. For example. An operator is a function that can be applied using inﬁx syntax (Section 3. ¦ ¦ ¦ § ¦ ` ` ` ` ) ) ) ( ( ( ( ` ` ` ` ) 4 © ¦ 3332 2 ¦ ©32 2 ¤ ¡ ©¦ 2 ¡ &¤¢ 2 2 ¦ ¡ 4 ©¡ ¢ § 32 3¦ 2 ¦ ¦ 4 © ¦ § 32 33 2 ¦ 4 S¤ © § ¤ ¦ ¢ 4 © 3¤¢ § ¤ ¦ 4 32 ¢ § ¦ 2 ¢ © ¦ ¦ 4 © ¦ 3332 ¦ § 3 2 43¤ § ¦ ¤ © ¦ 4 © 3¢S¤ § ¤¢ ¦ ¢ ¢ § 7 3¢ 0 ¤ § § 7 ¦ 2 ¦ 2 6 6 6 6 6 6 6 6 6 6 6 6 0 4 32 © ¦ 2 ¡ 2 2 ¦ ©32 ¡ ¡ ©¦ 2 2 ¡ &¤ 2 ¡ 2 ¤¢ ¡ ¦32 ¢ ¦ 2 ¦ ¤ ¦ 32 ¡¦ ¤¢ ¢ variable qualiﬁed variable constructor qualiﬁed constructor variable operator qualiﬁed variable operator constructor operator qualiﬁed constructor operator operator qualiﬁed operator . The integers and are chosen so that .4. If no ﬁxity declaration is given for `op ` ` then it defaults to highest precedence and left associativity (see Section 4. EXPRESSIONS () [] (.4). Dually. instead of writing the preﬁx application op op x y. These are described in Section 6. An operator is either an operator symbol. ) : Haskell provides special syntax to support inﬁx notation. or is an ordinary identiﬁer enclosed in grave accents (backquotes).2). such as ` `. one can write the inﬁx application x `op y. The ﬂoating point literal is equivalent to fromRational ( Ratio.4.5). Translation: The integer literal is equivalent to fromInteger . or partially applied using a section (Section 3. Ratio Integer).1). For example. production for An integer literal represents the application of the function fromInteger to the appropriate value of type Integer.% constructs a rational from two integers. Special syntax is used to name some constructors for some of the builtin types. . such as + or $$. where fromInteger is a method in class Num (see Section 6.
However. if the pattern fails to match. where the are patterns. £ ¤ ¡ 2 £ ¤ 2 3 ¡ ¢ The form is the inﬁx application of binary operator to expressions and ¡ ¡  2 ¦ ©32 ¡ ¢ ¡ 2 ¤ ¡ ¡¢ ¢ 2 ¡ ¡ ¡ ¢ ¡ ¡ ¡ 6 6 where the are new identiﬁers. CURRIED APPLICATIONS AND LAMBDA ABSTRACTIONS 19 3.denotes preﬁx negation.4 Operator Applications £ The special form . () is syntax for (\ x y > xy). it may be rebound by the module system.will always refer to the negate function deﬁned in the Prelude. The binary .17.3 Curried Applications and Lambda Abstractions > . page 55).3. then the result is . ¨ ££ ¥¦£ ¡ ¨ ££ ¥¦£ ¡ ¨ £££ ¡ ¦¥ ¨ £££ ¡ ©§¦¥¤¢ \ > \ > case ( . 3. one must write e1(e2) for the alternative parsing.operator and unary negation. Application associates to the left.in the Prelude. . Because tors are allowed.1. Preﬁx negation has the same precedence as the inﬁx operator . the only preﬁx operator in Haskell. .operator does not necessarily refer to the deﬁnition of .3. An expression such Lambda abstractions are written \ as \x:xs>x is syntactically incorrect. and is syntax for negate . Because e1e2 parses as an inﬁx application of the binary operator . it may legally be written as \(x:xs)>x. There is no link between the local meaning of the . partial applications of data construc ) of ( . ) > ¦ ¢ ¡ A !§ ¡ 8 8 ¥¥8 ¡ § \ > ¡ ¢ ¡ £5¢ ¡ ¢ S ¢ ¢ ¡ ¢¢ ¨ £§S¢0 ¡ 6 6 ¡ ¡ ¡ function application lambda abstraction ¡ ¡ ¢ 2 ¢ ¡ ¢ ¡ 0 . The set of patterns must be linear—no variable may appear more than once in the set. v Translation: The following identity holds: Given this translation combined with the semantics of case expressions and pattern matching described in Section 3. and does not denote (\ x > x)—one must use negate for that. unary . as with any inﬁx operator. Similarly. preﬁx negation qualiﬁed operator .deﬁned in the Prelude (see Table 4. ¡ A ¡ 8 8 ¥¥8 ¡ ¡ £ ¡ Function application is written omitted in (f x) y. . so the parentheses may be could be a data constructor.3.
(*a+b) is synparses in the same way as (x tactically invalid. the latter may legally be written as (+(a+b)). there is a subtract function deﬁned in the Prelude such that (subtract ) is equivalent to the disallowed section.  £ ¡ ¤ ¢ ( ) negate ¡ 2 £ ¤ ¡ 2 ¢ ¡ p v £!e ¢ $ ¡ ¡ 2 ) 2 p v ¢ ¡e ¡ ) 2 p v ¢ 0e ¡ $ 2 v S ¢ ¡ ¡ 7 ¢ ¡ ¡ ¡ 2 v 6 ¡ ¢ ¡ ¡ ¢ S ¢ . ( )  right section ) ¡ 2 ¡ 2 ¡ 2 ¡ ¡ ¡ 2 ¢ ¡ ( ( ( ) ) left section left section right section is an expression. by the let/lambda metarule (Section 3). For example.20 Translation: The following identities hold: CHAPTER 3. EXPRESSIONS 3. the expression (let n = 10 in n + x) parses as (let n = 10 in (n + x)) rather than ((let n = 10 in n) + x) Because . (a+b+) is syntactically correct.5 Sections ¢ S ¤ v ¡ ¢ S ¡ v ¡ p v ¢ A5e ¡ 2  Syntactic precedence rules apply to sections as follows. ( ) is legal if and only if (x ) ( )). However. but (+a+b) is not. as described in the preceding section.is treated specially in the grammar. Because (+) is left associative. and similarly for ( ). where is a binary operator and Sections are a convenient syntax for partial application of binary operators. but (+a*b) and (*(a+b)) are valid. () is not a section. but an application of preﬁx negation. the expression (let n = 10 in n +) is invalid because. The expression (+ ()) can serve the same purpose. As another example. ¢ S ¡ 2 Sections are written as ( ) or ( ).
£ ¡ £ ¢ S ¡ ¤ ¡ ¢ ¡ if then else ¢ ¡ ¡ ¡ ¥ ¢ ¡ ¡ ¢ ¡ 6 6 6 6 6 6 6 6 ¡ 2 where .6. denoted [].1). Standard operations on lists are given in the Prelude (see Section 6. and is a variable that does not occur free in ¢ ¡2 2 ¢ ¢ ¢ ¡ 2 2 ( ( ) ) \ \ > > ¡ ¡ ¡ 4 ¡ © ¦ 32 2 ¦ ©32 ¦ 32 ¦ 3¡2 ¡ ¢ S ¡ ¡ 2 ¢ ¡ ¢ ¡ and returns the value of if the ¢ . CONDITIONALS Translation: The following identities hold: 21 3.3. is an expression. . is a binary operator.3.7 Lists [] ( ) : . ¥ £ ¡ 3. ] ¢ ¡¡ £ ¥ ¢ ¡ ¢ ¡ ¡ 2 ¡¡ £ ¤ if then else case of { True > . The list constructor is :.6 Conditionals ¥ ¢ ¡ Translation: ¡ ¢ The following identity holds: ¥ ¢ £ ¢ ¡ ¤ where True and False are the two nullary constructors from the type Bool. and Chapter 8 notably Section 8. and the empty list is Lists are written [ . where . False > } £ ¥ A conditional expression has the form if then else value of is True. ]. which is also the Prelude. ¢ ¢ S 8 8 ¥¥8 4 © 3¦ 2 2 ©¦ 2 4 © ¦ 3¡ 32 8 8 ¥¥8 ¡ ¦ 2 ¦ 2 ¢ ¡ [ . The type of type of the entire conditional expression. and must have the same type. as deﬁned in the must be Bool.1. if is False. and otherwise.
1. Translation: ( ) is equivalent to .). ) ¤ ¢ 8 8 ¥¥8 £ ¡ ¢ ¡¡ 8 8 ¥¥8 ¡ ¡ ¤ [ .) a b c tuple is denoted by (.1.2). . EXPRESSIONS where : and [] are constructors for lists. . and may be of arbitrary length .1. ).2). and is equivalent to .4. Thus (a.b. ) for is an instance of a tuple as deﬁned in the Prelude. The types of through must all be the same (call it ). respectively. and can be thought of as the “nullary tuple” (see Section 6.9 Unit Expressions and Parenthesized Expressions ¡¦ 2 The form ( ) is simply a parenthesized expression. The constructor for an commas.1. ¢ ¡ ( () ) ¦ ¤ ¢ ¡ ¢ ¡¦ § § 8 8 ¥¥8 ¤ ¢ ¡§ ¡§ 8 8 ¥¥8 8 8 ¥¥8 8 8 ¥¥8 ¡ ¦ 2 ¢ ¡ ( . § 3. Standard operations on tuples are given in the Prelude (see Section 6. as deﬁned in the Prelude (see Section 6. ] : ( : ( ( : []))) ¡ ¡ ¢ 6 6 6 6 ¡ ¦ 32 ¦ 32 ¡ ¡ § ¢ S ¢ S ¢ ¢ . it is considered part of the language syntax. . and requires no translation.c) and (. where there are denote the same value.4 and Chapter 8). .3). 3. and cannot be hidden or redeﬁned.1. like [].5).22 Translation: The following identity holds: CHAPTER 3. .2). .. Translation: ( . then the type of the resulting tuple is ( . The unit expression () has type () (see Section 4. If through are the types of through . ) Tuples are written ( . and the type of the overall expression is [ ] (see Section 4. .1..2). It is the only member of that type apart from . . ) (see Section 4. It is a rightassociative operator. The constructor “:” is reserved solely for list construction. with precedence level 5 (Section 4. .8 Tuples ¢ S (.
. § ¥ ¢ £ ¤ ¡ § § ¨ £ ¢ ¡ ¡ ¡ ¢ ¡ [ . ] enumFrom enumFromThen enumFromTo enumFromThenTo v The arithmetic sequence [ .3. ] denotes a list of values of type . where is a pattern (see Section 3. ¡ ¡ ¡ ¡ ¢ £¡ ¢ ¡ 6 6 6 7 ¢ 3¢ S ¡ ¢ ¡ ¢ S $ ¢ ] . § 3... ] .11 List Comprehensions ¦ A 8 8 ¥¥8 ¡ guards. enumFromThen. .10.... and is an instance of class Enum. § generators of the form expression of type [ ] § <. See Section 6.10 Arithmetic Sequences ¨ ¥ ¡ $ ¢ ¡ Translation: Arithmetic sequences satisfy these identities: ¡ where enumFrom.1.3. ] . ] list comprehension generator local declaration guard ¥¤ £ ¡ ¥ ¢ ¡ £ ¡ 7 3¢ ¥ ¢ 7 ¢ ¥ ¢ £ ¤ £ ¤ ¡¢ ¡¢ ¡¢ ¡ ¢ [ [ [ [ .17) of type v ¦ A ¥ 8 8 ¥¥8 ¡ A list comprehension has the form [  . and enumFromThenTo are class methods in the class Enum as deﬁned in the Prelude (see Figure 6. ] .4 for more details of which Prelude types are in Enum and their semantics.. . ] where the qualiﬁers are either and is an ¡ ¡ $ © ¢ ¡ 7 ¦ ¢ ¡ [  <let § . The semantics of arithmetic sequences therefore depends entirely on the instance declaration for the type .. ARITHMETIC SEQUENCES 23 3. enumFromTo. Such a list comprehension returns the list of elements produced by evaluating in the successive environments created by the nested. . depthﬁrst evaluation of the generators in the qualiﬁer list. . which are arbitrary expressions of type Bool local bindings that provide new deﬁnitions for use in the generated expression or subsequent guards and generators. . page 83). where each of the has type .
3.y] ] else [] ] ] 6 ¡ ¢ ¡ . z <. and over sequences of qualiﬁers.(3. . lexicallyscoped. Declarations are described in Chapter 4. over patterns. A ¦ 8 8 ¥¥8 ¡ ¦ let in ' © 7 ¡ ¡ © 7 ¦ © 7 ¥ ¦ [  let .4). (3.2). and introduce a nested. The function concatMap.xs ] yields the list [4. over qualiﬁers. mutuallyrecursive list of declarations (let is often called letrec in other languages). an implicit ˜ makes these patterns irrefutable.[ [(1. over boolean over declaration lists.x) <. For example.x.12 Let Expressions ¢ ¡ © Let expressions have the general form let { .24 CHAPTER 3.. ok is a fresh variable. EXPRESSIONS Binding of variables occurs according to the normal pattern matching rules (see Section 3. over listvalued expressions.17).(3.2]. are deﬁned in the Prelude. and boolean value True. bindings in list comprehensions can shadow those in outer scopes. The scope of the declarations is the expression and the right hand side of the declarations. As usual.2)] ]. x <. for example: Translation: List comprehensions satisfy these identities. let (x. which may be used as a translation into the kernel: where ranges over expressions. it must evaluate to True for the previous pattern match to succeed. ] = 7 ] ¡ 7 ¥ ¦ ' 7 ¥ ¦ 7 ' ¡ [ [ [ [  True ]  ]  .x ] [ z  y <. Pattern bindings are matched lazily.4). True ] if then [  let ok = [  ok _ = [] in concatMap ok let in [  [ x  x <.x. ]  <.y) = undefined in does not cause an executiontime error until x or y is evaluated.4)]. = = = = [ ] [  . variables bound by let have fully polymorphic types while those deﬁned by <.5. If a qualiﬁer is a guard.are lambda bound and are thus monomorphic (see Section 4. Thus: [ x  xs <. and if a match fails then that element of the list is simply skipped over. As indicated by the translation of list comprehensions. expressions. [(5. } in .
. these identities hold. ... where and are patterns and expressions respectively. > ¦§ of { } . which may be used as a translation into the kernel: ¡ where fix is the least ﬁxpoint operator. not the syntactic metasymbol for alternation. Once done. .13 Case Expressions A case expression has the general form (Notice that in the syntax rule for .˜ ) = ( . 3. ¥ § ¢ ¡ ¢ ¡ ¢ ¡  ¨ § ¢ ¡ > ¤ } 3 § § ¢ ¦¤ 5 § 7 3¢ %§ ¡ 4 ¦ ¨ © ¨ 5© 7 ¦ 7 ¥ ¦ © @§ ¢ £¡ ¦ ¡ A§ 7 3¢ £¡ ¦ ¢ ¢ £¡ ¢ ¡ § ¡ ¥8¥8 ¢ £¡ ¡§ 8 7 3¢ § ¢ S case . ..3. An alternative of the form > where ¢ ¡  True > where © ¡ 7 ¥ ¦ § ¢ ¡ is treated as shorthand for: v ¨¥ § ¢ 4 v v ¡ © 7 ¥ ¦ ¤ v ¦7 v v © 7 ¥ ¦  > where ¤ ¥7 v ¡ v ¡ ¡v ¢ S 8 8 ¥¥8 v ¨¥ § § ¢ ¢ £¡ 4 ¦ v ¡ v © 7 ¦ 4 where each is of the general form  > A 4 A 8 8 ¥¥8 ¡ ¥ § 4 ¡ case v ¥ § of { . . .) Each alternative consists of a pattern and its matches.. The static semantics of the bindings in a let expression are described in Section 4. followed by optional bindings ( ) that scope over all of the guards and expressions of the alternative.13. the “” is a terminal symbol. using the translation in Section 4. ) in case of ˜ > where no variable in appears free in let = fix ( \ ˜ > ) in ¡ ¢ ¨ ££ ¦¥£ ¡ § ¢ £¡ ¦ © @§ ¡ § 7 3¢ 7¡ 3 ¢ ¢ ¦ . each declaration is translated into an equation of the form = .4.3. where where ¡ £ ¡ 7 3¢ ¡ ¡ ¢ ¡ ¦ ¡ ¢ 6 6 6 6 6 let = in = ¨ ¡ ¡ ¥ ¡ ¢ ¨ © ¡ ¡ ¡ ¨ ¨ © ¡ ¢ ¡ ¡ ¡ ¥ ¢ let { = let = . . This translation does not preserve the static semantics because the use of case precludes a fully polymorphic typing of the bound variables.. Each match in turn consists of a sequence of pairs of guards and bodies (expressions). in = } in = = let (˜ . . CASE EXPRESSIONS Translation: The dynamic semantics of the expression let { 25 . Note the use of the irrefutable patterns ˜ .3..4. . } in are captured by this translation: After removing all type signatures.
namely case x of { (a.26 CHAPTER 3. The alternatives are tried sequentially. EXPRESSIONS A case expression must have at least one alternative and each alternative must have at least one body. If all the guards evaluate to False._)  (let b = not a in b :: Bool) > a } However. and parsers with limited lookahead may incorrectly commit to this choice._)  let b = not a in b :: Bool > a } is tricky to parse correctly. A case expression is evaluated by pattern matching the expression against the individual alternatives. ¦ § ¡ 7 ¦ ¢ ¡ § ¡ ¢¡ £ ¡ ¢ ¡ ¢S A § 4 §¤© 8¥8¥8 ¡ § 4 § © 4§ © © @§ do { } do expression v © 7 ¥ ¦ ¡ ¢ S 6 6 6 ¤ ¥¡ © @§ ¢ ¡ § ¡ 4§ 4§ © © ¢ ¡ . ¦ 3. A note about parsing. ¦ ¨ . It has a single unambiguous parse. The expression case x of { (a. . Programmers are advised.17.14 Do Expressions A do expression provides a more conventional syntax for monadic programming. and then by the guards evaluates to True. If no match succeeds.17. the phrase Bool > a is syntactically valid as a type. from top to bottom. to avoid guards that end with a type signature — indeed that is why a contains an not an . . the result is . It allows an expression such as putStr "x: " >> getLine >>= \l > return (words l) to be written in a more traditional way as: do putStr "x: " l <. Each body must have the same type. matching continues with the next alternative. and the type of the whole expression is that type.3. therefore. and hence reject the program. If matches the pattern in the alternative. Pattern matching is described in Section 3. <let . If one of the pattern. the guards for that alternative are tried sequentially from top to bottom.getLine return (words l) § § § ¦ 4 ¢ © %§ ¡ 4 ¥ © . the corresponding righthand side is evaluated in the same environment as the guard. in the environment of the case expression extended ﬁrst by the bindings created during the matching of the in the where clause associated with that alternative. with the formal semantics of case expressions in Section 3.
the functions >>. A ﬁeld label can be used at most once in a constructor. because y is given inconsistent typings in the latter.. 3. } = © @§ 4 ¤© § } © @§ 4 ¤© ¡ § >> do let ok ok in let 7 ¥ ¦ © @§ 4§ 7 © @§ do { } do { . after eliminating empty : } . variables bound by let have fully polymorphic types while those deﬁned by <.2.1 Field Selection ¤ ¢ Field labels are used as selector functions.15 Datatypes with Field Labels A datatype declaration may optionally deﬁne ﬁeld labels (see Section 4.BAD Here S is legal but T is not. DATATYPES WITH FIELD LABELS 27 Translation: Do expressions satisfy these identities.1). consider: data S = S1 { x :: Int }  S2 { x :: Int } data T = T1 { y :: Int }  T2 { y :: Bool } . which may be used as a translation into the kernel. Within a datatype. select from.15.15... Selectors are top level bindings and so they may be shadowed by local variables but cannot conﬂict with other top level bindings of the same name.3). This shadowing only affects selector functions. and fail are operations in the class Monad. do { < © @§ 4 ¤© § = = = ¦ 4 ¤© § } = do { } _ = fail "..are lambda bound and are thus monomorphic. >>=. Different datatypes cannot share common ﬁeld labels in the same scope. preferably giving some indication of the location of the patternmatch failure.15. 3. passed to fail. © @§ 4§ © © © @§ 4§ © © do {let . To illustrate the last point.2) and update (Section 3. in record construction (Section 3. as deﬁned in the Prelude. a ﬁeld label serves as a function that extracts the ﬁeld from an object. When used as a variable.15. As indicated by the translation of do.OK ." stands for a compilergenerated error message. © The ellipsis ". however. These ﬁeld labels can be used to construct. a ﬁeld label can be used in more than one constructor provided the ﬁeld has the same typing in all constructors. ﬁeld labels cannot be confused with ordinary variables. and ok is a fresh identiﬁer.3." >>= ok in do { } { ¡ 6 ¡ ¢ S ¢ . and update ﬁelds in a manner that is independent of the overall structure of the datatype.
is the default © § 8 8 ¥¥8 © ¡ § © { } = undefined ' ¡ £¢ ¡ 0 ' ¡ ¢¢ 0 Translation: ' In the binding = . where F is a data constructor. 0 ¦ © ' ¡ ¢ v 0 § ¡ ¦ If the th component of a constructor in the binding list . undefined A 8 8 ¥¥8 ¡ 8 8 ¥¥8 ¡ ¡ ¦ ¡§ ¢ ¡ 0 { = . EXPRESSIONS A ﬁeld label 0 ' introduces a selector function deﬁned as: 3. and is y when some ﬁeld in has a label of or undefined otherwise. The expression F {}. the { and } characters must be explicit. Unlike the braces used in declaration lists. is legal whether or not F was declared with record syntax (provided F has no strict ﬁelds — see the third bullet above). where is the arity of F. these are not subject to layout. and if appears is . } labeled construction . .) Construction using ﬁeld labels is subject to the following constraints: Only ﬁeld labels declared with the speciﬁed constructor may be mentioned. is y when labels the th component of or _ otherwise.2.2 Construction Using Field Labels ¦ A ¦§ 0 A constructor with labeled ﬁelds may be used to construct a value in which the components are speciﬁed by name rather than by position. (This is also true of ﬁeld updates and ﬁeld patterns. . the ﬁeld labels .1. ¦ § v ¦ v where are all the constructors of the datatype containing a ﬁeld labeled with .28 Translation: x 0 CHAPTER 3. A ﬁeld label may not be mentioned more than once. 0 v v P ¡ A 8 8 ¥¥8 ¡ ¢ ¦ ¡ ' 8 8 ¥¥8 ¡ ¡ ¡ = case x of { > . is deﬁned as follows: has the ﬁeld label . © ' ¡ ¢ v § ¡ ¦ © ¡ ¢ v © ' § ¡ where is the arity of The auxiliary function § . then value . Fields not mentioned are initialized to A compiletime error occurs when any strict ﬁelds (ﬁelds whose declared types are preﬁxed by !) are omitted during construction. A ¥¥8 ¡ A A 8 8 ¡ ¡ ¡ ¡ > } ¦ ' ¤ ¦ ¢2 A 8 8 ¥¥8 ¡ 0 ¦ 6 6 0 ¢ ¦ ¦ ¡ ¦§ ¢ S ' ¢ 0 . Strict ﬁelds are discussed in Section 4.15. it denotes F . Otherwise.
15. and is the arity of £ F© £ ¢ § 8 8 ¥¥8 ¡ > _ > error "Update error" T© ' £ ¡ ¢ ¡ ' ' £ ¡ ¢ . This creates a new value in which the speciﬁed ﬁeld values replace those in the existing value. DATATYPES WITH FIELD LABELS 29 3. Updates are restricted in the following ways: All labels must be taken from the same datatype. T© § 8 8 ¥¥8 ¡ T© ¡ ¡ § § ¡ > ¢ ' ¢ ¡ ¢ ¡ ' ¡ ¢ { } ¡ ¡ = case of ¢ £ ¡ 8 8 ¥¥8 8 8 ¥¥8 ¡ 8 8 ¥¥8 ¡ ¡ ¡ ¦§ 0 { . such as x {f2 = 1. f3 = ’B’} x {f1 = 1} The ﬁeld f1 is common to both constructors in T. At least one constructor must deﬁne all of the labels mentioned in the update. v is the set of constructors containing all labels in .. A compiletime error will result if no single constructor deﬁnes the set of ﬁeld labels used in an update.. This example translates expressions using constructors in ﬁeldlabel notation into equivalent expressions using the same constructors without ﬁeld labels.3. f3. v © ¥¥8 ¡ 8 8 where .f2 :: Int}  C2 {f1 :: Int.15. ¦ ' ¦ ' ) A9g© ¨ ¡ ¢ ¡ ¢ 6 ' ¡ ¢ S ¢ . . f3 = ’x’}. No label may be mentioned more than once. f4 = ’A’. } labeled update .3 Updates Using Field Labels ¦ A ¦§ ¡ 0 § Values belonging to a datatype with ﬁeld labels may be nondestructively updated. An execution error occurs when the value being updated does not contain all of the speciﬁed labels.f4 :: Char} Translation C1 3 undefined C2 1 ’B’ ’A’ case x of C1 _ f2 > C1 1 f2 C2 _ f3 f4 > C2 1 f3 f4 Expression C1 {f1 = 3} C2 {f1 = 1. Translation: © Using the prior deﬁnition of Here are some examples using labeled ﬁelds: data T = C1 {f1.
EXPRESSIONS 3. As with normal type signatures (see Section 4. the ﬁrst ﬁve of these ultimately translate into case expressions. do expressions. function deﬁnitions.4.1 Patterns Patterns have this syntax: § 8 8 ¥¥8 ¡§ 0 { . the declared type may be more speciﬁc than the . } ¦§ ¢ ¦ as pattern arity labeled pattern ¦ 32 ¦ 32 arity ¢ ¢  negative literal £¡ ¢ ¤ ¥ § ¦ § + § ¦ 2 8 8 ¥¥8 ¡ § ¢ §¢ ¡ ¢£§¢ § ¡ ¢§ ¡ § 2 ©¦32 ¡ v £§¢ § ¤ ¡ v ¢ ¡ v £¡ p v §e ¡ ¢ ¢ ¢ § 2 ¡ ¥ § ¦ § £¡ ¤ ! § 2 ©¦32 s¢ ¡ v § § ¡ v © ¢ £¡ p v ¢§e ¡ ¢ ¡ v § £ 7¡ ¤ ¢ v £¡ ¢ § v ¢ ¨ ¡ v§ 2©32 ¡ v § £ 7¡ ¦ ¢ ¦ ¢£¡ p v ¨§e ¡ ¢ £¡ § ¢ ¤ £ ¡ ¢ § ¨§ § :: = let { :: . = } in successor pattern ¡ ¢ ¡ § § ¨ § S § ¢ ¡ ¢ ¡ ¦ 32 :: => ¡ ¢ ¡ £§¢ ¢ £¡ V y ¤ § § 7 3¢ ¦ 2 7 ¤ ¦ 2 ¤ ¡ ¢ ¢ ¡ 6 6 6 6 6 6 6 6 v ¤ v § § ¡ £¡ ¢ ¤ § ¢£¡ § ¢£ 7¡ ¢ £ 7¡ v § ¢ ¡ £§¢ § § ¡ ¢ £¡ ¢ £¡ ¢ ¡ .1). where is an expression and is a type (Section 4. However. so deﬁning the semantics of pattern matching for case expressions is sufﬁcient. or not principal type derivable from comparable to. they are used to type an expression explicitly and may be used to resolve ambiguous typings due to overloading (see Section 4.16 Expression TypeSignatures %§ 0 Expression typesignatures have the form :: .3. the principal type.2). The value of the expression is just that of . .17. and case expressions. Translation: 3. pattern bindings.4).30 CHAPTER 3.1.17 Pattern Matching Patterns appear in lambda abstractions. list comprehensions. 3. but it is an error to give a type that is more general than.
ILLEGAL. this deﬁnition is illegal: f (x. For example. Pattern matching proceeds from left to right.3._. ¢ § . case e of { [x. and allow one to use . . x used twice in pattern case e of { xs@(x:rest) > if x==0 then rest else xs } is equivalent to: let { xs = e } in case xs of { (x:rest) > if x==0 then rest else xs } Patterns of the form _ are wildcards and are useful when some part of a pattern is not referenced on the righthandside. return ). value being matched by § § ¢ ¢ § = as a name for the to . Matching the pattern against a value always succeeds and binds ¤ ¢ Patterns of the form @ are called aspatterns. For example. it may succeed. It is as if an identiﬁer not used elsewhere were put in its place.z] > if x==0 then True else False } > if x==0 then True else False } 3.y. ¢ ¡ ¢ £¡ ¢ £¡ ¤ § ¢£§¢ ¡ ¡§ ¢£¡ ¡§ ¢£¡ ¢ £¡ § _ ( ( [ ˜ wildcard parenthesized pattern tuple pattern list pattern irrefutable pattern ¢ ¤ ¢ 6 § ¢ £¡ 0 .e._] is equivalent to: case e of { [x.2 Informal Semantics of Pattern Matching Patterns are matched against values. For example. one cannot match against a partiallyapplied constructor.17. according to the following rules: ¤ ¤ 1. . PATTERN MATCHING 31 The arity of a constructor must match the number of subpatterns associated with it.17. Attempting to match a pattern can have one of three results: it may fail.x) = x . All patterns must be linear —no variable may appear more than once. returning a binding for each variable in the pattern. and outside to inside. ) ] ¤ ¢ £¡ ¢ § £¡ ¢ 8¥¥8 8 8 8 ¥¥8 ) . or it may diverge (i.
where == is overloaded based on the type of the pattern. where is a different constructor to ¦ 32 A 8 8 ¥¥8 ¡ A !§ 8 8 ¥¥8 ¡ § 5. depending on the type of the pattern. The match diverges if this test diverges. 8. ¦ 32 4.. constructors associated with newtype serve only to change the type of a value. the ﬁrst to fail or diverge causes the overall match to fail or diverge.32 CHAPTER 3. . so does the overall computation. where newtype. depends on the value: against a value.) Operationally. Matching against a constructor using labeled ﬁelds is the same as matching ordinary constructor patterns except that the ﬁelds are matched in the order they are named in the ﬁeld list. 7. The interpretation of numeric literals is exactly as described in Section 3. then is matched against . Matching an + pattern (where is a variable and is a positive integer literal) against a value succeeds if >= . that is. The interpretation of the literal integer literals are allowed. is the same as in numeric literal patterns. and no binding is done. (Binding does not imply evaluation. The match diverges if the comparison diverges. ﬁelds may not be named more than once. At that point the entire pattern is matched against the value. then is matched against . the overall match succeeds. The free variables in are bound to the appropriate values if matching against would otherwise succeed. . Matching the pattern against a value. If the value is of the form . and if the match fails or diverges. character. this means that no matching is done on a ˜ pattern until one of the variables in is used. subpatterns are matched lefttoright against the components of the data value. and fails otherwise.2. if all matches succeed. Fields not named by the pattern are ignored (matched against _). All ﬁelds listed must be declared by the constructor. depends on the value: is a constructor deﬁned by is a constructor deﬁned ¢ ¡ £5¢ ¢ ¡ £§¢ § ¢ ¡ £§¢ ¢ £¡ § ¢ £¡ ¢ ¡ § ¦ 2 ¢ ¡ £5¢ § ¢ ¡ £§¢ ¢ ¦ ¢ ¡ £§¢ . where ¢ £¡ ¦ 32 § ¢ £¡ ¦ 32 If the value is . Matching the wildcard pattern _ against any value always succeeds. or string literal pattern against a value succeeds if == .are overloaded. and to if matching against fails or diverges. the overloaded function fromInteger or fromRational is applied to an Integer or Rational literal (resp) to convert it to the appropriate type. respectively. 3. § § § That is. EXPRESSIONS 2. resulting in the binding of to . 1 ¦ 2 ¦ 32 7 ¦ 8 8 ¥¥8 ¡ r1 32 If the value is of the form the match fails. the match diverges. 6. the functions >= and . Matching the pattern by data. except that only ¢ ¢ ¢ ¦ ¢ ¢ ¦ ¢ ¢ ¢ If the value is . Again. Matching a numeric. Matching the pattern ˜ against a value always succeeds. § ¦ Q32 If the value is of the form .
But if [’a’. irrefutable matching: (\ ˜(x.˜(a. An + pattern can only be matched against a value in the class Integral.’x’]. It is sometimes helpful to distinguish two kinds of patterns. is irrefutable). All other patterns are refutable.’b’] is matched against [’x’. If the match of against fails or diverges. it is a static error to match a character against a boolean). Consider the following declarations: newtype N = N Bool data D = D !Bool (\ (x:xs) > x:x:xs) (\ ˜(x:xs) > x:x:xs) (\ ˜[x.y) > 0) (\ ˜[x] > 0) [] (\ ˜[x] > x) [] 0 0 : : 3.’b’] is matched against [ . a wildcard. where is a constructor deﬁned by newtype and is irrefutable @ where is irrefutable. The irrefutable patterns are as follows: a variable.17. then . then ’a’ to match against ’x’. A ﬂoating literal pattern can only be matched against a value in the class Fractional. then Aside from the obvious static type constraints (for example. Here are some examples: 1. ¢ ¡ £§¢ ¢ ¡ £§¢ E ¤ ¢ § ¢§ ¡ £§¢ ¢ ¡ £§¢ ¢ ¦ ¤ ¢E ¢ ¦ . to . and the result is a failed match. the following static class constraints hold: An integer literal pattern can only be matched against a value in the class Num. (a. ] (\ ˜[x.y) > 0) (\ (x.b)] > x) [(0. ] (0. PATTERN MATCHING § 33 against a value is the result of matching against .b)] > x) [(0. Matching an irrefutable pattern is nonstrict: the pattern matches even if the value to be matched is . attempting to match ’a’ against causes the match to 2. These patterns may be removed or changed in future versions of Haskell.3.1) § ¢ ¡ £5¢ § ¢ ¡ £§¢ © § 7 ¢ 0 § ¢ ¡ £§¢ %¥ § ¤ § ¢ §¢ ¡ ¦ § ¤ ¢ ¡ £§¢ § ¢ @ 9. These examples demonstrate refutable vs.1).3). Many people feel that + patterns should not be used. If the pattern [’a’. Matching a refutable pattern is strict: if the value to be matched is the match diverges.2. Matching an aspattern augmented with the binding of so does the overall match. or of the form ˜ (whether or not (see Section 4. ].1).
2. (j). 3. or pattern binding to which it is attached.1–3.17.Int. . an otherwise irrefutable pattern may be evaluated because of a guard.2 involves the overloaded operator ==. The semantics of case expressions themselves are in turn given as a series of identities. and it must be true for the overall pattern match to succeed. (q). Top level patterns in case expressions and the set of top level patterns in function or pattern bindings may have zero or more associated guards. in Figures 3. Any implementation should behave so that these identities hold.Int) > [Int] > Int f ˜(x. The environment of the guard is the same as the righthandside of the caseexpression alternative. since that would generate rather inefﬁcient code. EXPRESSIONS These examples illustrate the difference in pattern matching between types deﬁned by data and newtype: Additional examples may be found in Section 4. and are patterns. For example. Rules (d).2: . In particular. In Figures 3. this indicates that variables bound by case are monomorphically typed (Section 4. regardless of whether it actually includes guards—if no guards are written. and are expressions.2.4). then True is substituted for the guards in the forms. it is not expected that it will use them directly. Rule (h) in Figure 3. in f :: (Int. v ¥ § Rule (b) matches a general sourcelanguage case expression. ¢ ¡ 4 v ¢ 3 v ¤ 1 (\ (N True) > True) (\ (D True) > True) (\ ˜(D True) > True) True E v v ¤¢ 1 ¢ v ¡ . and is a newtype constructor.1–3. it is this rule that deﬁnes the meaning of pattern matching against overloaded constants.1. A guard is a boolean expression that is evaluated only after all of the arguments have been successfully matched.3 Formal Semantics of Pattern Matching The semantics of all pattern matching constructs other than case expressions are deﬁned by giving identities that relate those constructs to case expressions. and are variables. and are algebraic datatype (data) constructors (including tuple constructors). The guard semantics have an obvious inﬂuence on the strictness characteristics of a function or case expression. These identities all preserve the static semantics. . and are booleanvalued expressions.3. and (s) use a lambda rather than a let.z) [a]  (a == y) = 1 both a and y will be evaluated by == in the guard.y. (e). Subsequent identities manipulate the resulting case expression into simpler and simpler forms.34 CHAPTER 3. function deﬁnition.
PATTERN MATCHING 35 . > error "No match" } ¡ ! ¨ ££ ¥¦£ © £ ¡ © ¨ © ¡ © ¨ # $£ § § (b) .1: Semantics of Case Expressions. _ > } > ) (case of { > are all the variables in }) (case of { > A % ££ ¦¥£ case of { > (where is a new variable) case of { > let { } in if then _ > }} © ¥ ¢ 2 10 © % A B ¨ @ § A @ 6 _ else if ¥ ¢ 98 70 ££ ¥¦£ 6 © 4 © 1% 5% ¨ § (c) case of {   > > > . .3. _ > } @ § @ C ¨ ¨ C § § (e) case of { @ > . Part 1 G @ § (f) case of { _ > . } } . where { } } then 10 > where { # ¥ ¢ 32 ( & )' ¤# ( & )' ¤# % ££ ¦¥£ © & ¤# ¡ ! where each  > © & ¤# % has the form: . _ > } case of { > ( \ > ) . }) ¡ "£ § § £ ¡ (a) case of { } where is a new variable case of { case of { _ § (\ > case of { ¥ £ ¦¤¢ ¥ £ ¦¤¢ }) . Figure 3.  } else ££ ¥¦£ _ £ ¡ ! § ¨ ££ ¥¥£ > case of { .17. _ > } $C ¨ § ££ ¦¥£ © DC ¨ ¨ @ § ¨ $C¦E£¥¥¦FC ££E © ££ © ¥¦£ C C $3 § (d) case (\ where of { ˜ > . .
¦" C E £££ ¥¦¥E © C 28 ¨ E £££ ¥¦¥E @ © ¨ _ > at least one of } is not a variable. _ > } case of { _ _ > . _ otherwise case of { {} > .36 CHAPTER 3. ££ ¥¦£ @ ¨ C ££ ¦¥£ @ © C > case © ¨ of { > case _ > } @ ¨ ££ ¥¦£ © ¨ ¦ C ££ ¦¥£ © C § ¨ § (g) case of { case of { > . _ > is a data constructor of arity } @ C ££ ¥¦£ © © C ££ ¥¦£ © ££ ¥¦£ C © ££ ¦¥£ (q) case ( ) of { (\ > ) where is a data constructor of arity © C > . _ > } of { > . _ > } A @ ££ ¥¥£ ££ ¦¥£ ¥ ¥ §¨ ¨ A ¥ ¤ ¥ ¦¤ © ¨ © ¤ A § © ¨ © 5¤ ££ ¥¥£ ¥ ¤ § @ § (m) case of { { = . _ > } where and are distinct data constructors of arity and . _ > } . _ > } where is a newtype constructor ¢ } case § C C § (j) case of { > } ( \ > ) of { C § @ C § (i) case of { > . _ > } case of { > . _ > } case ( ) of { > . respectively @ @ ¨ ¨ ¤ ¨ ¤ ££ ¥¦£ § ¨ © ¨ § (n) case of { case of { # { = } > . _ > is a newtype constructor @ @ ¨ ¨ ¢ § § ¢ (k) case of { > .) else where is a numeric literal ¡ £ @ © C ££ ¥¦£ © C £ (r) case where of { > . _ > } if >= then (\ > ) ( . _ > } case of { > } > @ F ¡ § @ F ¡ § (h) ¡ case where of { > . } > . character. EXPRESSIONS Figure 3. _ > _ > }} where . are ﬁelds of constructor . } > .2: Semantics of Case Expressions. is a new variable © 7¤ A ¨ £ @ ¨ ¢ £ (l) ¢ case where of { > . _ > } where is if labels the th component of . or string literal. _ > case of { > case of { { = } > case of { { = . _ > } @ @ © $C ££ ¥¦£ © C ££ ¦¥£ @ © 4 @ (p) @ @ ' ££ ¥¥£ § § (o) > . are new variables else } } }. = . _ > } if ( == ) then is a numeric. Part 2 @ ¡ § @ C ¡ C ¡ § § (s) case of { + > . .
. we describe the syntax and informal semantics of Haskell declarations. . ¦ { . .¦ § 7 ¥ ¦ ¤ ¤ © ¥ £0 ¦ $ 8 8 ¥¥8 ¢ ¡ 7 § 7 ¥ ¦ ¤ ¤ ¢ 8 8 ¥¥8 ¤ © ¥ © ¦ § A 7 ¦ 7 ¥ ¦ © © ¥ ¤ § ¦ ¢ £¡ 7 ¦ § ) 7 7 ¦ 7 ¦ ¦ 8 8 A %§ ¥¥8 ¡ %§ ¦ § ¡ ¡ ¨ © § § ©¦ § © %§ ¨ § ¡ § ¦ 2 © ¢ 7 7 ¦ ¨ 5© ¤ ¥ %§ © %§ ¨ § S § 32 © ¢ ¦ 7§ © ¦ ¦ 7§ © ¨ ¦ § § ¤ ¥ 332 £ ¦ %¢§¢ 4 ¥ x¨ ¤ § ¡ § 32 ¢ ¦ ¦ V ¨ #¦ § § ¥ ©¤ § ©332 ¡ 7©¡ %§ 4 § © ¨ ¤ ¦ § S § 32 ¢ ¦ ¦ ¡ 7© ¡ %§ %¢ § 4 § V © A ¡ 2 § ¡ ¥¥8 ©¡ ¡ 2 § 8 8 7 7 ¥ ¦ ¡ 7 ¥ ¦ ¡ 7 ¦ ¡ © 2§ 7 ¥ ¦ ¡ 4 § © 7¥ ¦ ¡ 4 § 7 ¥ ¦ ¡ © ¦ ' ¡ ¦ ¦ Declarations and Bindings Chapter 4 In this chapter. } } ¦ ¡ 7 $ ¥ ¦£0 7 ¦ ¦ { . } ¦ A 8 8 ¥¥8 ¡ ¦ $ ¥ £0 7 ¦ ¦ { . module where 2 ¨ ©§ ¤ 5@¤32 ¢ ¡ § 2 4 ¦ ' { { { . type data newtype class instance default ( . } } © 2§ . } = = where where empty A § ¦ 37 6 6 © ¥ § ¦ § © 7 ¦ 7 6 6 © 7¥ ¦ 7 ¥ ¦ 6 6 © 7¥ ¦ 7 ¥ ¦ 6 6 © 2§ 7 ¥ ¦ ¡ 2 § 7 ¥ ¦ ¡ 6 6 2 ¦ ' 2 $ 7 ¦ 2 4 . . = => => => => .
but most “builtin” datatypes are deﬁned with normal Haskell code. whereas may be used either at the top level or in nested scopes (i. consisting of class. .3. and nested declarations. DECLARATIONS AND BINDINGS The declarations in the syntactic category are only allowed at the top level of a Haskell module (see Chapter 5). .e. infixl infixr infix ¦ ¦ 7 ¥ ¦ ¡ 2§ ¨ :: => © ¡ © 7 ¥ ¦ A¤ 2 ¨ ¥ § ¦ § ¤ ¡ § S § 32 ¢ ¦ V A¢ 2 ¡ 8¥¥8 8 8 8 ¥¥8 %§ § ¢ ¡ © ¤ ¡ ¤ ¢ ¢ 2 ¡ 6 6 6 6 7 ¥ ¦ © S¤ © type signature ﬁxity declaration empty declaration %§ § ¢ ¦ ¥ ¢ 2 ¡ . suppose we wish to overload the operations (+) and negate on types Int and Float.” We may then declare Int and Float to be instances of this class: .(Num is defined in the Prelude) This declaration may be read “a type a is an instance of the class Num if there are class methods (+) and negate.2) declares that a type is an instance of a class and includes the deﬁnitions of the overloaded operations—called class methods—instantiated on the named type. We introduce a new type class called Num: class Num a where (+) :: a > a > a negate :: a > a . An instance declaration (Section 4. we divide the declarations into three groups: userdeﬁned datatypes.1 Overview of Types and Classes Haskell uses a traditional HindleyMilner polymorphic type system to provide a static type semantics [3.2). 5]. . and ﬁxity declarations (Section 4. using normal type and data declarations.1. © 4. Haskell has several primitive datatypes that are “hardwired” (such as integers and ﬂoatingpoint numbers).3). These “builtin” datatypes are described in detail in Section 6.38 %§ CHAPTER 4.4). consisting of type.simplified class declaration for Num . of the given types. those within a let or where construct). For example. type signatures. and data declarations (Section 4. and default declarations (Section 4. newtype. instance. A class declaration (Section 4. but the type system has been extended with type classes (or just classes) that provide a structured way to introduce overloaded functions.1) introduces a new type class and the overloaded operations that must be supported by any type that is an instance of that class. consisting of value bindings. For exposition. type classes and overloading.3. deﬁned on it.
1.1 Kinds To ensure that they are valid.e. and negateFloat are assumed in this case to be primitive functions. ‘type class’ includes both the original Haskell type classes and the constructor classes introduced by Jones. then a type of kind . There is no longer any reason to use two different terms: in this report.simplified instance of Num Float x + y = addFloat x y negate x = negateFloat x where addInt. ¡ ¡ ¢ ¨ ¤ ¡ B%§ ¦ 32 ¢ %§ ¡ ¤ ¡ ¡ %§ %§ ' ' The symbol represents the kind of all nullary type constructors.1. negateInt.simplified instance of Num Int x + y = addInt x y negate x = negateInt x instance Num Float where . is the kind of types that take a type of kind and return ¤ ¥¡ 6 6 6 ¢ £¡ ¡ ¡ %§ %§ ¡ %§ ' ¢ . The term ‘type class’ was used to describe the original Haskell 1.” More examples of type classes can be found in the papers by Jones [7] or Wadler and Blott [12].2 Syntax of Types ¨ %§ > %§ function type %§ 8 8 ¥¥8 ¡ ¤ ¡ ¡ %§ %§ %§ ( [ ( . unlike types. ] ) . Kind inference is discussed in Section 4. addFloat. class methods) for (+) and negate. However. ) tuple type list type parenthesised constructor ¤ type application ¢ ©¡ ¢ ¤ ¡ ¨§6 ¦¡ ¢ ¡ If and are kinds. OVERVIEW OF TYPES AND CLASSES 39 instance Num Int where . kinds are entirely implicit and are not a visible part of the language. which take one of two possible forms: Kind inference checks the validity of type expressions in a similar way that type inference checks the validity of value expressions. 4. 4. type expressions are classiﬁed into different kinds.0 type system. ‘constructor class’ was used to describe an extension to the original type classes.4.1. but in general could be any userdeﬁned function. The ﬁrst declaration above may be read “Int is an instance of the class Num as witnessed by these deﬁnitions (i.6.
9 and 6. is identical to the type . Int. Type variables. The function type is written as (>) and has kind . IO. and so on. © S¤ Special syntax is provided for certain builtin type constructors: The trivial type is written as () and has kind .. add the type constructor T to the type vocabulary.. 2.). and so on.). also written () (see Sections 3. to the variable a. If is a type of kind type expression of kind . type values are built from . Special syntax is provided to allow certain type expressions to be written in a more traditional style: § § ¤ ¢ ¡ ¡ ¢ ¡ ¤ ¡ 6 ¤ ¡ 6 ¢ ¡ 3. DECLARATIONS AND BINDINGS The syntax for Haskell type expressions is given above. A parenthesized type. For example: Char. The main forms of type expression are as follows: 1. As with data constructors. Type constructors. Type application. In general. and classes. Float. and is a type of kind .40 CHAPTER 4. Just as data values are built using data constructors. a process of kind inference (see Section 4.5).. Use of the (>) and [] constants is described in more detail below. The tuple types are written as (. The kind of a variable is determined implicitly by the context in which it appears.. It denotes the “nullary tuple” type. the type expression IO a can be understood as the application of a constant. written as identiﬁers beginning with a lowercase letter. Double and Bool are type constants with kind . Since the IO type constructor has kind . . (. the names of type constructors start with uppercase letters. The list type is written as [] and has kind . Integer.. having form ( ). Most type constructors are written as an identiﬁer beginning with an uppercase letter.1. Their kinds are . then is a 6 6 6 6 6 () [] (>) (.6) is needed to determine appropriate kinds for userdeﬁned datatypes. . or newtype T . The kind of T is determined by kind inference. The declarations data T . and treated as types with kind . IO a. ) 6 2§ $ § © ¦ ¤ ¤32 ¡ %§ ¤ ¡ ¢ ¡ ¦ 32 6 %§ 6 6 6 ¦ 32 %§ unit type list constructor function constructor tupling constructors . For example. and has exactly one value. inﬁx type constructors are not allowed (other than (>)). Unlike data constructors. 4. must have kind . type synonyms. Maybe and IO are unary type constructors. it follows that both the variable a and the whole expression.
A list type has the form [ ]. A class identiﬁer begins with an uppercase letter. These special syntactic forms always denote the builtin type constructors for functions. Notice that expressions and types have a consistent syntax. (. and so on. tuples. nor mentioned in import or export lists (Chapter 5). When we write an explicitly quantiﬁed type. ) £§ ¢ 6 ¢ & 8 ¢ ¥ ¦ § § ¢ 6 ¤ ¢ 8 ¢ ¢ £ ¤ ¥ ¡ § ¡ ¢ § ¤ ¦ ¦¢ § 32 ¦ © %§ ¨ § 2 4 A 5 %§ 8¥8¥8 ¢ %§ 7¥ ¤ B%§ ¦ © ¦ %§ ¡ ¡ ¢ ¡ ¢ ¢ ¤ %§ © ¥ %§ 7 7 © 8 8 ¥¥8 ¢ ¡ S© ¥ ¢ ¥ 7 £ ¤ § 8 8 ¥¥8 ¡ ¢ ¢ ¢7 ¤ ¡§ ¢ £ ¤ %§ © § 7 ¥ ¡ %§ ¢ § 6 ¡ ¡ © S© ¢ 8 8 ¥¥8 ¢ 8 ¢ ¥ 7 ¢ ¥ ¡ ¢ 6 6 6 6 6 § ¡ § ¢ £§ © © ¤ 7 7 © © © ¥ ¢ 7 ¥ %§ ¡§ ¦ 2 %§ %§ ¢ ¥ 7 v %§ . A class assertion has form . In a similar way. the second component of type . respectively. 3..1. then the expressions (\ > ). the scope of the extends as far to the right as possible. means . there is no explicit syntax for universal quantiﬁcation [3]. and lists.4. for example. . and ).) where there are commas between the parenthesis. ) where . It denotes the type of tuples with the ﬁrst component of type . “gtycon”.7 and 6. []. the type variables in a Haskell type expression are all assumed to be universally quantiﬁed. and so on (see Sections 3.1.). A function type has the form Function arrows associate to the right. For example. their semantics is the same as the equivalent userdeﬁned algebraic data types. and has the general form A $ A 8 8 ¥¥8 ¡ $ ¡ ( ) ¤ ¢ %§ ¦ ( ) ¦ A © © ( .3. For clarity. A context consists of zero or more class assertions. [ ]. always denote the builtin type constructors. A tuple type has the form ( .3 Syntax of Class Assertions and Contexts . OVERVIEW OF TYPES AND CLASSES £§ ¡§ 41 £§ ¡§ > . ¡§ £§ ¡§ v § 4. above. we often write quantiﬁcation explicitly when denotes the type discussing the types of Haskell programs. It denotes the type of lists with elements of type (see Sections 3.4). the type expression a > a . If is the type of expression or pattern . the preﬁx type constructors (>). which is equivalent to the type [] .1)). Int > Int > Float means Int > (Int > Float). . . which is equivalent to the type (>) .) Although the list and tuple types have special syntax.1. [ ]. ( With one exception (that of the distinguished type variable in a class declaration (Section 4. . . they cannot be qualiﬁed.1. (Hence the special production. ().8 and 6. and ( ) have the types ( > ). 1. however. 2. and indicates the membership of the type in the class . which is equivalent to the type (. regardless of what is in scope.3). For example.
Therefore. In general.3. The context must only contain type variables referenced in . The type of an expression depends on a type environment that gives types for the free variables in . For example. Functor f) => (a > b) > f a > f b > Bool In the third type.4). Furthermore. here are some valid types: Eq a => a > a (Eq a. Haskell’s extended HindleyMilner type system can infer the principal type of all expressions. In general. a type is of the form .4 Semantics of Types and Classes In this section. £§ ¨ $ © ¢ © A value of type . Show a.3. the most general type. any of that are free in must also be free in . The outer parentheses may be omitted when . we provide informal details of the type system.4.) The Haskell type system attributes a type to each expression in the program. or the application of type variable to one or more types. £ ¢ 8 £ ¥ $ ¡§ t $ ¡ ¢ 8 t $ The type substitution ¥ is more general than the type whose domain is such that: if and only if there is a § A $ A ¢ $ 8 8 ¥¥8 8 8 ¥¥8 ¡ $ ¢ ¡ $ ¢ ¢ v r$ $ § ¢ ¢ § ¢ A ¢ 8 $ 8 8 ¥¥8 ¢ ¥ ¡ £§ ¦ . although in this case the concrete syntax contains no =>. we write => even if the context is empty. we use to denote a context and we write => to indicate the type restricted by the context . explicit typings (called type signatures) are usually optional (see Sections 3. where is a set of type variables .16 and 4. may be instantiated at types holds. including the proper use of overloaded class methods (although certain ambiguous overloadings could arise.1). as described in Section 4. (Wadler and Blott [12] and Jones [7] discuss type and constructor classes. In any such type. " t ¡§ is identical to . and a class environment that declares which types are instances of which classes (a type becomes an instance of a class only via the presence of an instance declaration or a deriving clause). Types are related by a generalization preorder (speciﬁed below). the universallyquantiﬁed type variables the context must be of the form given above in Section 4. Eq b) => [a] > [b] > String (Eq (f a). For example. and each of the is either a type variable. DECLARATIONS AND BINDINGS where are class identiﬁers. respectively. up to the equivalence induced by the generalization preorder. also holds. For convenience.42 CHAPTER 4. the constraint Eq (f a) cannot be made simpler because f is universally quantiﬁed. that can be assigned to a particular expression (in a given environment) is called its principal type. in more detail.1.1. § § § 4. consider the function double: § if and only if the context ¡ ¢ ¢ 8 £ ¢ Whenever ¥ holds in the class environment.
in which case double may indeed be applied to a Char. double may not normally be applied to values of type Char. 4.1 Algebraic Datatype Declarations ¨ #¦ § § The precedence for is the same as that for expressions—normal constructor application has higher precedence than inﬁx constructor application (thus a : Foo a parses as a : (Foo a)). since Num Int holds. The types of the data constructors are given by: A § ¥¥8 ¡ !§ A A 8 8 $ 8 8 ¥¥8 ¡ $ 6 ¡ ¡ ¢¢¡ ¤ v§ 6 ¢¢¡ ¡ ¡ ¡§ 8 8 ¥¥8 ¡ ¡ § ¡ 6 ¡ @§ v A v ¢ $ 8 8 ¥¥8 8 8 ¥¥8 ¡ 8 ¡ $ $ 8 8 ¥¥8 ¡ $ Q¥ §¦v ¥¥ ¢ data ¢ => =   £ ¤ A © S© ¡ 8 8 ¥¥8 © ¡ S© © S© deriving © ( . ! .2 UserDeﬁned Datatypes In this section. USERDEFINED DATATYPES double x = x + x 43 The most general type of double is Num . An algebraic datatype declaration has the form: where is a context.2. However. } 3 %§ ¢ ¥ ¦ 7 ! ! ¡ ¢ 7 ¦ ¦ 7 %§ ¡ %§ ¡ ¡ 7 ¥ %§ ¦ ¦ 7 ¡ ¢ ¡ ¢ %§ ! ! arity inﬁx ¦§ £ ¢ ¢ ¡ 3 %§ 8¡ 8 ¥¥8 ¢ 2 ¦ ©32 ' ¡ ¡ %§ ¨ 8 8 ¥¥8 A¢ § © ¦ §¤ ¤32 8 8 ¥¥¡8   ¦ ¦ § 2©¦ 2 ¡ ¦32 ¦ ¦ § ¢ ¤ ¥ © © ¦ ¤ § 332 %§ ¤ ¢ 4§ © ¨ %§ 8 8 ¥¥8 ¡ ¤ § S § ¢ ¢ ¦ 32 data => = ¦ ¢ 6 ¢ ¢ ¡ 7 ©¡ 8 ¢ ¥ %§ © ¤ ¦ 3¢ 2 %§ ¨ ¡ 32¡ ¦ ' ¢ ¡ ¤ ¤32 § © ¦ ¢ V ¤ § 332 © ¦ 7 ¥ ¦ 32 %§ %§ 6 6 6 6 6 6 6 ¡ 7 ¥ ¦ ¦ 7 § %¢ #¦ § § 7 ¥ ¦ ¡ © © ¤ § ¦ ¤ § ¦ 2 © © © 7 ©¡ ¢ 7¥ ¦ ¤ 4§ 2 2§ ¦ © . . This declaration introduces a new type constructor with one or more constituent data constructors .2. because Int is an instance of the class Num. These declarations may only appear at the top level of a module. because Char is not normally an instance of class Num. double may be applied to values of type Int (instantiating to Int). the unqualiﬁed term “constructor” always means “data constructor”. and type synonyms (type declarations). 4. The user may choose to declare such an instance. we describe algebraic datatypes (data declarations).4. renamed datatypes (newtype declarations). ) ¦ § ¦ ¢ ¥ ¦ 7 A ¢ ¥ ¦ 7 { :: . In this Report.
e. the overloaded type for ConsSet ensures that ConsSet can only be applied to values whose type is an instance of the class Eq. using the record syntax (C { . }). The context in the data declaration has no other effect whatsoever. Pattern matching against ConsSet also gives rise to an Eq a constraint.3. features using labels are simply a shorthand for operations using an underlying positional constructor. This allows For large datatypes it is useful to assign a speciﬁc ﬁeld to be referenced independently of its location within the constructor. f3 :: Bool } deﬁnes a type and constructor identical to the one produced by © ¢ 6 Set Set ¢ ¢ 6 ¢ 7 ' ¨¢ ¢ introduces a type constructor Set of kind types NilSet Set ConsSet Eq . to the components of a data object. DECLARATIONS AND BINDINGS is the largest subset of that constrains only those type variables free in the types ..8.3. the “abstractness” of the datatype) outside of the module in which the datatype is deﬁned is controlled by the form of the datatype’s name in the export list as described in Section 5. The new type constant has a kind of the form where the kinds of the argument variables are determined by kind inference as described in Section 4. Labelled Fields A data constructor of arity creates an object with components. This means that may be used in type expressions with anywhere between and arguments. For example. Constructors using ﬁeld labels may be freely mixed with constructors without them..6. the declaration data C = F { f1. These components are normally accessed positionally as arguments to the constructor in expressions or patterns. For example: f (ConsSet a s) = a the function f has inferred type Eq a => Set a > a. The arguments to the positional constructor occur in the same order as the labeled ﬁelds. The type variables through must be distinct and may appear in and the .f2 :: Int.44 ¢ v ¢ CHAPTER 4. the declaration data Eq a => Set a = NilSet  ConsSet a (Set a) In the example given. A constructor deﬁnition in a data declaration may assign labels to the ﬁelds of the constructor. The visibility of a datatype’s constructors (i. The optional deriving part of a data declaration has to do with derived instances. it is a static error for any other type variable to appear in or on the righthandside. and is described in Section 4. A constructor with associated ﬁeld labels may still be used as an ordinary constructor. and constructors NilSet and ConsSet with v § ¢ v I¡ ¢ ¢ 6 ¡ ¦ 6 ¥¥8 8 8 ¢ 6 $ 7 ¦7 ¢ 6 ¢ ¡ 8 8 ¢ ¢ ¥ §¥ ¥ ¥ §¥ ¥ ¡ $ ¤ v§ v $ where 8 8 ¥¥8 ¡ @§ v . For example.
2. replaces every occurrence of 8 8 ¥¥8 A 8 8 §© ¥¥8 ¡ © 8 8 ¥¥8 $ 8 8 ¥¥8 ¡ $ ¢ data => =   in an expression is the strict apply is not affected by 2 ¤ ¤ © ¡ ¦ 6 6 8 8 ¥¥8 %¢ § 4§ © 7 ©¡ 2 § 7 ¥ ¦ ¡ ¡ 2 ¡ $ ¡ # ¡ § § § . it is a static error for any other type variable to appear in .4.2. The type is equivalent to the type . “!” is an ordinary varsym not a . the following deﬁnition can be used to provide an alternative way of writing the list type constructor: § ¡ v $ § ¥¥8 ¡ § 8 8 § v I¡ 8 8 ¥¥8 ¡ $ $ type = ¦ § ¢ ¡ $ type %§ = v where is the nonstrict apply function $ if is of the form . Pattern matching on strictness ﬂags. whether or not F was declared with record syntax. each argument to the constructor is evaluated if and only if the corresponding type in the algebraic datatype declaration has a strictness ﬂag. USERDEFINED DATATYPES data C = F Int Int Bool 45 Operations using ﬁeld labels are described in Section 3. and function $! (see Section 6. The type variables through must be distinct and are scoped only over .2) if is of the form ! .2 Type Synonym Declarations A type synonym declaration introduces a new type that is equivalent to an old type. A label cannot be shared by more than one type in scope. Lexically. Translation: A declaration of the form 4. denoted by an exclamation point. Field names share the top level namespace with ordinary variables and class methods and must not conﬂict with other top level names in scope. The kind of the new type constructor is of the form where the kinds of the arguments and of the right hand side are determined by kind inference as described in Section 4. “!”. It has the form § $ which introduces a new type constructor. A data declaration may use the same ﬁeld label in multiple constructors as long as the typing of the ﬁeld is the same in all cases after type synonym expansion. For example.6. v 2§ v © v © v ¢ £ 2 ¡ ¢ ¡ 2 ¤ %§ ¥¥8 ¡ ¤ %§ 32 8 8 ¦ ¢%§ %¢ ¢ 4 § © § ¡ ¡ ©¡ 7 A 8 8 3¢ ¥¥8 ¡ ¡ 6 ¡ ¢ (\ > 2 v %§ ¡ 3¢ A 2 ¥¥8 £ A 8 8 ¡ ¡ ¡ v @§ & v 2§ 6 ¥¥8 8 8 ¨ $ # § 6 ¢ ¡ v © where each by is either of the form ! or .15. it has special signiﬁcance only in the context of the argument types of a data declaration. Strictness Flags Whenever a data constructor is applied. The pattern F {} matches any value built with constructor F. .
4. For example.invalid = = [Circ a] Tag [Rec a] is not. newtype does not change the underlying representation of an object. DECLARATIONS AND BINDINGS Type constructor symbols introduced by type synonym declarations cannot be partially applied. it is a static error to use without the full number of arguments. Unlike algebraic datatypes. so that is the same as .3.3 Datatype Renamings ¨ ¦§ § introduces a new type whose representation is the same as an existing type.2) can be deﬁned for a type deﬁned by newtype but may not be deﬁned for a type synonym. type Rec a data Circ a is allowed. A synonym and its deﬁnition are completely interchangeable. E $ 8 8 ¥¥8 ¡ § § $ $ 8 8 ¥¥8 ¡ $ § E $ 8 8 ¥¥8 ¡ $ E ¢ newtype => A declaration of the form = ¦ § ¢ ¤ ¢ %§ 8 8 ¥¥8 ¡ ¤ %§ ¢¤ %§ { :: } ¤ ¤ § 332 © ¦ £ ¦ § %¢ 4 § x¨ © § ¡ § ¢ ¡ ¦ 32 newtype => = ¦ ¡ 7 ©¡ V ¢ ¡ %§ E ¢ ¦ 32 § ¦32 ¦ 32 %§ E 6 6 6 $ 8 8 ¥¥8 ¡ ¤ ¤32 § © ¦ ¡ § %¢ 7 ¥ ¦ ¡ 7 ©¡ $ £ 4§ © 2§ ¦ . Although recursive and mutually recursive datatypes are allowed. Similarly. This difference may make access to the representation less efﬁcient.2. whereas type Rec a type Circ a = = [Circ a] [Rec a] . The difference is reﬂected in different rules for pattern matching (see Section 3. It differs from a type synonym in that it creates a distinct type that must be explicitly coerced to or from the original type. the newtype constructor is unlifted. New instances (see Section 4.17). These coercions may be implemented without execution time overhead.invalid . Type synonyms are a convenient. but strictly syntactic. The constructor in an expression coerces a value from type to type ( ). unless an algebraic datatype intervenes.2). Using in a pattern coerces a value from type ( ) to type . The type ( ) renames the datatype . this is not so for type synonyms.46 type List = [] CHAPTER 4. unlike type synonyms. newtype may be used to deﬁne recursive types. type Rec a = [Rec a] is not allowed. mechanism to make type signatures more readable. except in the instance type of an instance declaration (Section 4. Also. A type created by newtype differs from an algebraic datatype in that the representation of an algebraic datatype has an extra level of indirection.3.
1 Class Declarations ¨ 5© A class declaration introduces a new class and the operations (class methods) on it.4. © ¥ } ¦ § ¦ A© §S© 4§ © 7 8 8 ¥¥8 ¦ ( . A newtype declaration may use ﬁeldnaming syntax.3. whereas ( n ). The optional deriving part of a newtype declaration is treated in the same way as the deriving component of a data declaration.3. and newtype (renaming types. Thus: newtype Age = Age { unAge :: Int } brings into scope both a constructor and a deconstructor: Age :: Int > Age unAge :: Age > Int 4. ) ¦ § ¢7 ¤ %§ © 7 ©¡ %§ ¨ § S § ¢ class => where 7 ¥ ¦ ¢ 7 ¥ ¤ ¤ © ¥ £0 ¦ $ ¢ 7 ¦ 7 ¦ ¡ 8¥¥8 8 7 ¦ ¤ %§ ¥ © %§ ¢ ¥ § © 74 ¡ S© © ¢ ¥ © ¡ 4 § © 7 7 © S© 7 ¦ 32 © ¢ ¥ 7 ¡ 6 6 6 6 6 © © 7 ¥ © 7 ¥ ¢ ¥ ©¡ 7 7 § S § ¢ 7 ¥ ¦ ¡ ¦ 32 4§ ¦ ¦ 2§ © © . .3. see Section 4.3 Type Classes and Overloading 4. type (type synonyms). ( d2 ) and (d2 (D2 ) ) are all equivalent to . ( d1 ( D1 ) ) and ( s ) are all equivalent to 42. . ( n ( N ) ). TYPE CLASSES AND OVERLOADING 47 The following examples clarify the differences between data (algebraic datatypes). In particular. A class declaration has the general form: © $ ¢ class => where ¦ 7 ¥ ¦ A { . ( N ) is equivalent to while ( D1 ) is not equivalent to .) Given the declarations data D1 = D1 Int data D2 = D2 !Int type S = Int newtype N = N Int d1 (D1 i) = 42 d2 (D2 i) = 42 s i = 42 n (N i) = 42 the expressions ( d1 ). though of course there may only be one ﬁeld.3.
. it may mention type variables other than . whose scope extends outside the class declaration. they must not conﬂict with other top level bindings in scope.. Class methods share the top level namespace with variable bindings and ﬁeld names. The default class method for is used if no binding for it is given in a particular instance declaration (see Section 4. 6 7 ¥ ¦ 6 Foo Num 8 ¥ Here the type of op is © ¢ ' ¡ ¡ ¡ £ £ ¥ ¡ ¤¥ §¥ ¢ 8 ¨ © § ¥ ¦ ¢ ' ¢ ' ¢ 7 ¥ ¦ v 7 ¥ ¦ 7 ¥ ¦ The part of a class declaration contains three kinds of declarations: is: $ ¢ ¢ 7 ¦ . The class methods of a class declaration are precisely the for which there is an explicit type signature :: => in . i. © v © A class declaration with no where part may be useful for combining a collection of classes into a larger one that inherits all of the class methods in the original ones. For example: class Foo a where op :: Num b => a > b > a v #¢ £ $ £ v ¨¢ £ $ $ $ v§ v The may also contain a ﬁxity declaration for any of the class methods (but for no other values). op2 :: a > a (op1. no other declarations are permitted in . in which case the type of is polymorphic in both and . because the left hand side of the default declaration is a pattern. For example: class (Read a. The may constrain only . except that the left hand side may only be a variable or function deﬁnition. However.2). Lastly. in particular.3. the only type variable that may be referred to in is .e. © The class declaration introduces new class methods . v B v # v v @§ v ¢ v © The type of the toplevel class method The must mention . For example: class Foo a where op1. The context speciﬁes the superclasses of . a ﬁeld name. the may contain a default class method for any of the . op2) = . a class method can not have the same name as a top level deﬁnition. . That is. The superclass relation must not be cyclic. outside the class declaration. or another class method. the may not constrain . as described below. it must form a directed acyclic graph. DECLARATIONS AND BINDINGS $ This introduces a new class name . the type variable is scoped only over the class method signatures in the class body. is not permitted. Show a) => Textual a Other than these cases. since class methods declare toplevel values.48 CHAPTER 4. The default method declaration is a normal value deﬁnition. the ﬁxity declaration for a class method may alternatively appear at top level.
instance C [[a]] where .. it is not automatically an instance of the subclass.2 Instance Declarations ¨ © } § ¦ § © © %§ $ An instance declaration introduces an instance of a class. instance C (Int. if a type is an instance of all superclasses. TYPE CLASSES AND OVERLOADING 49 In such a case. even though range is in scope only with the qualiﬁed name Ix.3.a) where . module A where import qualified Ix instance Ix..) For example. (This rule is identical to that used for subordinate names in export lists — Section 5.. this is legal.. ) ) & & ( ( [ ( { ) ¦ ¦£©¨¦§¥££ ¤ B%§ £¡ ¤ %§ ¢ ¤ ¢ ¢ © §¢ ¦¥©¨§¦¥¤£¡S¤ %§ ¤ ¢ ¢ © ¦ ¢ ¢ © ¥©¨§¦¥¤£¡S¤ ¢¢ %§ § ¢¢ ¦ ¦ ' © ¥ ¤ ¤ © ¥ £0 ¦ $ A § ¥¥8 ¢ ¡ 7 § 8 8 7 ¥ ¦ 7 ¥ ¦ £ ¤ %§ ¡ ¤ %§ ¢ ¤ ¢ %§ ¢ ¤ %§ ¥¥8 8 8 ¡ ¤ %§ ¤ B%§ ¢ ¥¥8 ¡ ¤ %§ ¦ 2 ¢ %§ 8 8 ¢ ¢ ¨ § ¡ § ¢ ¦ 2 © instance => where 7 § ¦ 7 ¥ ¦ 32 8 8 ¥¥8 %§ ¦ ¡ $ 6 6 6 6 ¦ § ¢ 7 ¥ ¦ ¡ © 7 7 § ¦ § © 2§ § ¦ § ¦ .. it may be a qualiﬁed name. 4. The declarations may contain bindings only for the class methods of . It is illegal to give a binding for a class method that is not in scope. in particular. but the name under which it is in scope is immaterial.3.range.4. furthermore.. The instance declaration must be given explicitly with no where part..2. must take the form of a type constructor applied to simple . } . The declarations may not contain any type signatures or ﬁxity declarations. even though the subclass has no immediate class methods. must not be a type synonym. . The type type variables distinct.Ix T where range = .. ] > . since these have already v x$ $ 8 8 ¥¥8 ¡ $ $ where .a) where . The general form of the corresponding instance declaration is: This prohibits instance declarations such as: instance C (a. and the must all be $ 8 8 ¥¥8 ¡ $ 1 ¢ instance => where { ¦ 2 ¢ class => where { } £%§ ¡ 4 ¦ . Let be a class declaration.
. instance (Eq a.. Show a) => Bar [a] where . The second instance declaration is valid only if [a] is an ¨ $ # $ 8 8 ¥¥8 1. As in the case of default class methods (Section 4.. DECLARATIONS AND BINDINGS been given in the class declaration.. Show a) => Foo [a] where .. must be an instance of each of . Since Foo is a superclass of Bar.. but it is nevertheless mandatory to write an explicit instance context. the second instance declaration is only valid if [a] is an instance of Foo under the assumption Num a.1). Any constraints on the type variables in the instance type that are required for the class method declarations in to be welltyped must also be satisﬁed. if such a default does not exist then the class method of this instance is bound to undefined and no compiletime error results. the following two conditions must also be satisﬁed: 2. instance (Eq a. In fact. then the program would be invalid. If no binding is given for some class method then the corresponding default class method in the class declaration is used (if present).. This example is valid Haskell. The constraints expressed by the superclass context be satisﬁed. Assume that the type variables in the instance type satisfy the constraints in the instance context .. If the two instance declarations instead read like this: instance Num a => Foo [a] where . contexts of all superclass instances must be implied by $ of must ’s superclasses and the ¢ An instance declaration that makes the type to be an instance of class instance declaration and is subject to these static restrictions: is called a CT $ 1 ¢ 8 8 ¥¥8 ¡ ¢ $ 1 ¢ ¦ 1 ¢ . The following example illustrates the restrictions imposed by superclass instances: class Foo a => Bar a where . instance Num a => Bar [a] where ..6. this can be determined using kind inference as described in Section 4. Under this assumption. A type may not be declared as an instance of a particular class more than once in the program.3. In other words. The ﬁrst instance declaration does indeed say that [a] is an instance of Foo under this assumption. the method declarations must take the form of a variable or function deﬁnition. The class and type must have the same kind. except in pathological cases it is possible to infer from the instance declaration the most general instance context satisfying the above two constraints. because Eq and Show are superclasses of Num..50 CHAPTER 4.
Show. because the types for show and read. all mentioned in Figure 6. Bounded. But this does not hold. 4. The precise details of how the derived instances are generated for each of these classes are provided in Chapter 10. then the expression let x = read ". and supposing that just Int and Bool are members of Read and Show. data and newtype declarations contain an optional deriving form. instances for all superclasses of must exist for . omitting a deriving form is equivalent to including an empty deriving form: deriving ().3.4 Ambiguous Types.. and Defaults for Overloaded Numeric Operations ¦ A %§ A problem inherent with Haskellstyle overloading is the possibility of an ambiguous type. since [a] is only an instance of Foo under the stronger assumption Num a. These instances are subject to the same restrictions as userdeﬁned instances. A static error results if it is not possible to derive an instance declaration over a class named in a deriving form. It is also a static error to give an explicit instance declaration for a class that is also derived. For example.1. 4. TYPE CLASSES AND OVERLOADING 51 instance of Foo under the assumptions (Eq a. freeing the programmer from the need to deﬁne them.. When deriving a class for a type . For example. ) ¦ § ¡ ¡ 6 7 ¥ ¦ ¡ 2§ . using the read and show functions deﬁned in Chapter 10.1. If the form is included. .3.3. ¢ 6 6 ¢ 8 ¢ 8 ¥ §¥ ¥ ¥ §¥ ¥ show read Show Read String String ¢ ¢ 8 8 ¥¥8 ¢ ¡ ¢ %§ default ( . Enum. Further examples of instance declarations may be found in Chapter 8. not all datatypes can properly support class methods in Enum. and Read. The only classes in the Prelude for which derived instances are allowed are Eq. Derived instances provide convenient commonlyused operations for userdeﬁned datatypes. Show a). either via an explicit instance declaration or by including the superclass in the deriving clause.2. page 83. Ord. then derived instance declarations are automatically generated for the datatype in each of the named classes.invalid is ambiguous. Classes deﬁned by the standard libraries may also be derivable. including a speciﬁcation of when such derived instances are possible.4.3 Derived Instances As mentioned in Section 4. If the deriving form is omitted from a data or newtype declaration. For example. derived instances for datatypes in the class Eq deﬁne the operations == and /=. that is." in show x . then no instance declarations are derived for that datatype.
It is a static error if no such type is found. the earlier expression involving show and read has an ambiguous type since its type Show Read String. page 83.16. . is defaultable if: ¢ ¢ at least one of these classes is a numeric class. Only one default declaration is permitted per module. one could write: let x = read ".) Ambiguities in the class Num are most common. Such expressions are considered illtyped. Such types are invalid. and Figure 6. an ambiguous type variable. where is a class. ) where . a static error.1. and all of these classes are deﬁned in the Prelude or a standard library (Figures 6.52 CHAPTER 4. One way is through the use of expression typesignatures as described in Section 3. appears only in constraints of the form .. an otherwise ambiguous expression needs to be made the same type as some variable. so Haskell provides another way to resolve them— with a default declaration: default ( . shows the classes deﬁned in the Prelude. default (). or Bool.2–6. Occasionally. turns off all defaults in a module. in its type variable in that occurs in but not in . (that is. pages 91– 92 show the numeric classes. and its effect is limited to that module. § ¢ ¢ For example. is Ambiguous types can only be circumvented by input from the user. and each must be a type for which Num holds." in show (x::Bool) which disambiguates the type. For example. but and are forced to have the same type. This is the purpose of the function asTypeOf (Chapter 8): ‘asTypeOf‘ has the value of . Double) The empty default declaration. for the ambiguous expression given earlier. . Num or a subclass of Num). approxSqrt x = encodeFloat 1 (exponent x ‘div‘ 2) ‘asTypeOf‘ x (See Section 6. If no default declaration is given in a module then it assumed to be: default (Integer. rather than being given a ﬁxed type with an expression typesignature. DECLARATIONS AND BINDINGS could be satisﬁed by instantiating a as either Int in both cases. there is a type A !§ v § 8 8 ¥¥8 ¡§ ¢ v 2§ ¢ $ ¦ $ ¦ 8 ¢ ¥ . and 8 $ ¥ We say that an expression e has an ambiguous type if. § ¢ .) Each defaultable variable is replaced by the ﬁrst type in the default list that is an instance of all the ambiguous variable’s classes.6 for a description of encodeFloat and exponent. For example.3.4.. In situations where an ambiguous type is discovered.
then each use of outside its own declaration group (see Section 4. then each use of is treated as having the declared type. or principal type . (The type of x is dependent on the type of f. including the top level of a module. 4. Indeed. these declarations contain a static error.1.4. which allows applications such as sqr 5 or sqr 0. and all uses of within its declaration group must have the same monomorphic type (from which the principal type is obtained by generalization. Moreover. For example.e. to ensure that type inference is still possible. %§ ¨ § S § ¢ ¢ 8 ¦ 32 ¢ 8 8 ¥¥8 ¥ :: . every type variable appearing in a signature is universally quantiﬁed over that signature.4.4. If a variable is deﬁned without providing a corresponding type signature declaration.5) is treated as having the corresponding inferred.) If a given program includes a signature for a variable . i.1. this is explained in Section 4. it is invalid to give more than one type signature for one variable. It is also valid to declare a more speciﬁc type. However.2). As mentioned in Section 4. and hence the scope of a type variable is limited to the type signature that contains it. even if the signatures are identical.4 Nested Declarations The following declarations may be used in any declaration list. It is a static error if the same type cannot also be inferred for the deﬁning occurrence of .5. For example. Each must have a value binding in the same declaration list that contains the type signature. ¡ => ¡ V © ¤ ¤ ¢ ¢ 6 6 7 ¥ ¦ © S¤ ¦ ¥ ¢ . in the following declarations f :: a > a f x = x :: a v B the a’s in the two type signatures are quite distinct. NESTED DECLARATIONS 53 4.5.invalid A type signature speciﬁes types for variables. A type signature has the form: :: => which is equivalent to asserting :: => for each from to .1 Type Signatures . the deﬁning occurrence. . if we deﬁne sqr x = x*x 0 0 0 0 0 0 then the principal type is sqr Num . such as ¦ ¦ § ¢ § 6 ¢ ¢ A ¢ § 8 8 ¥¥8 ¢ 8 ¡ ¢ ¥ §¥ ¥ A §¤ v ¢ . it is invalid to give a type signature for a variable bound in an outer scope. there is currently since x does not have type no way in Haskell to specify a signature for a variable with a dependent type. possibly with respect to a context. as described in Section 4.4.2.
and infixr. declares a property of a particular operator.invalid . and level 9 binds most tightly). Type signatures can also be used to support polymorphic recursion. T a > a.1 lists the ﬁxities and precedences of the operators deﬁned in the Prelude. left. Type signatures such as sqr :: (Num a. .invalid are invalid. For example: §§ § ¦ ¤ § ¦ § ¦ infixl infixr infix . Fixity is a property of a particular entity (constructor or variable). The in a ﬁxity declaration must be in the range to . respectively). ﬁxity is not a property of that entity’s name. The following deﬁnition is pathological.54 sqr :: Int > Int CHAPTER 4. and at most one ﬁxity declaration may be given for any operator. level 9 is assumed. a ﬁxity declaration can only occur in the same sequence of declarations as the declaration of the operator itself. infixl. non. Also like a type signature.2 Fixity Declarations © A ﬁxity declaration gives the ﬁxity and binding precedence of one or more operators. Any operator lacking a ﬁxity declaration is assumed to be infixl 9 (See Section 3 for more on the use of ﬁxities). just like its type. and ten precedence levels. Table 4. ¦ ¡ 2 ©¦ 2 &¤ 2 A 2 ¡ ¥¥8 ¡ ¡ ¢ 2 8 8 ¡ ¡ 2 ¨ ¥ § ¦ § %§ § ¢ ¤ 6 6 6 6 7 ¥ ¦ © %§ § ¢ ¦ ¥ ¡ ¡2 2 . as they are more general than the principal type of sqr. 4. their ﬁxity declarations can occur either in the class declaration itself or at top level. the type of f will be inferred as T Int > Int due to the ﬁrst recursive call for which the argument to f is T Int.4. A ﬁxity declaration may appear anywhere that a type signature appears and. but illustrates how a type signature can be used to specify a type more general than the one that would be inferred: data T a = K (T Int) (T a) f :: T a > a f (K x y) = if f x == 1 then f y else undefined If we remove the signature declaration. Num b) => a > b sqr :: a > a . like a type signature. 0 to 9 inclusive (level 0 binds least tightly.and rightassociativity (infix. (Class methods are a minor exception. Polymorphic recursion allows the user to supply the more general type signature. DECLARATIONS AND BINDINGS but now applications such as sqr 0.) There are three kinds of ﬁxity. If the is omitted.1 are invalid.
ˆ.op‘ is infixr 7. /.op‘ is infix 3.4.1: Precedences and ﬁxities of prelude operators module Bar( op ) where infixr 7 ‘op‘ op = . ‘Foo.4..4. $!. ‘elem‘. ‘notElem‘ &&  >>.op‘ b) + 1 f x = let p ‘op‘ q = (p ‘Foo.. ‘seq‘ Table 4. Here. (It would also be possible to give a ﬁxity to the nested deﬁnition of ‘op‘ with a nested ﬁxity declaration. >. ‘Bar. <=. and the nested deﬁnition of op in f’s righthand side has the default ﬁxity of infixl 9.. NESTED DECLARATIONS 55 Precedence 9 8 7 6 5 4 3 2 1 0 Left associative operators !! *.3 Function and Pattern Bindings © ¥ § ¤ 2 v ¢£¡ § p v ¢ §e ¡ ¡ v © ¢ £¡ p v ¢ §e 2 § ¡ v £¡ p v ¢ 0e $ ¢ § ¡ ¢ ¡ £5¢ ¤ § ¤ ¢ £¡ ¤ ¡ v ¢ 2¢ &¤ v § £¡ ¢ ¤ ¡ ¢ ¡ v § £ 7¡ ¢ ¢ ¤ £ ¡ ¢ § ¢ ¡ £5¢ © ¥ 7 ¦ $ £0 § 6 6 © ¥ 7 ¦ 7 ¥ ¦ $ 0 . ˆˆ. >>= $. ‘mod‘. ‘quot‘ +. ** :. ‘div‘. /=. module Foo where import qualified Bar infix 3 ‘op‘ a ‘op‘ b = (a ‘Bar. ++ ==.op‘ q) * 2 in .. >=. ‘rem‘.) 4. <.  Nonassociative operators Right associative operators .
1 Function bindings A function binding binds a variable to a function value. Either binding may appear at the toplevel of a module or within a where or let construct.4.3. ¤ 4. . The general form of a function binding for variable is: ¡ ¥ § ¥ § or ¡ v ¡v   = Note that all clauses deﬁning a function must be contiguous. otherwise. these three function deﬁnitions are all equivalent: plus x y z = x+y+z x `plus y = \ z > x+y+z ` (x ` plus y) z = x+y+z ` v © v  True = where { 7 ¥ ¦ v 4 ¦ and where . Alternative syntax is provided for binding functional values to inﬁx operators. The former is treated as shorthand for a particular case of } v © 7 ¦ = where { ¤ ¥7 v v © ¤ ¦7 v v = where { 7 ¦ 8 8 ¥¥8 § ¡ v where each is a pattern. The set of patterns corresponding to each match must be linear—no variable is allowed to appear more than once in the entire set. and where each is of the general form: } } A ¢ ¢ 4 4 v ¥ § 4 ¢ A ¥¥8 ¡ A 8 8 ¡ ¡ ¡ ¡ 8 8 ¥¥8 ¡ ¡ ¡ 8 8 ¥¥8 ¢ ¢ ¢ ¡  ¨ © ¥ ¤ ¢ ¡ = ¦ ¦ ¡ ¤ © ¥ ¡ ¢ ¡ = ¦ where where 9§ ¨© ¨ 7 © ¥ 7 ¥ ¦ § © ¥ ¡ ¦ $ £0 ¤ ( ) ¢ §¢ ¡ ¢ ¡ £5¢ 7 ¦ 6 6 ¡ ¦ ¢ 6 © ¥ ¤ § © ¥ ¦ ¦ ¢ £¡ ¤ . and the number of patterns in each clause must be the same. For example. the binding is called a function binding. DECLARATIONS AND BINDINGS We distinguish two cases within this syntax: a pattern binding occurs when the left hand side is a . the latter. namely: .56 CHAPTER 4.
) of ( ) ¢ ¡ ¡ ¡ ¡ .e. It is usually straightforward to tell whether a binding is a pattern binding or a function binding.4. where a function bindings above. as if there were an implicit ˜ in front of it. The pattern is matched “lazily” as an irrefutable pattern. A 4 ¡ A ( ) ¥ § ¢ 4 A 8 8 ¥¥8 ¡ ¡ 8 8 ¥¥8 ¡ ¡ 8 8 ¥¡ ¥8 ¢ 8 8 ¥¥8 ¡ ¢ ¢ 8 8 ¥¥8 ¡ ¢ = \ ¢ > case ( . but the existence of n+k patterns sometimes confuses the issue.4.2 Pattern bindings A pattern binding binds variables to values. Here are four examples: 7 7 if then £ ¤ ¡ ¢ © £ ¡ = let if if in then then 7 ¦ Translation: ing: The pattern binding above is semantically equivalent to this simple pattern bind else else else error "Unmatched pattern" © 7 ¥ ¦ 7  = where { 7 £ ¡ ¢ £ ¡   = = } 4 The general form of a pattern binding is .4. A simple pattern binding has form . a pattern binding is: is the same structure as for ¡ ¥ § ¢ ¥ § ¢ 8 8 ¥¥8 4 ¡ ¡ 888 v ¢ where the are new identiﬁers. See the translation in Section 3. in other words. NESTED DECLARATIONS Translation: The general binding form for functions is semantically equivalent to the equation (i.3. . A note about syntax.12. simple pattern binding): ¡ ¥ § 57 4.
58 x + 1 = ... (x + 1) = ... (x + 1) * y = ... (x + 1) y = ...
CHAPTER 4. DECLARATIONS AND BINDINGS
 Function binding, defines (+)  Equivalent to (+) x 1 = ...  Pattern binding, defines x  Function binding, defines (*)  Equivalent to (*) (x+1) y = ...  Function binding, defines (+)  Equivalent to (+) x 1 y = ...
¤
4.5 Static Semantics of Function and Pattern Bindings
The static semantics of the function and pattern bindings of a let expression or where clause are discussed in this section.
4.5.1 Dependency Analysis
In general the static semantics are given by the normal HindleyMilner inference rules. A dependency analysis transformation is ﬁrst performed to increase polymorphism. Two variables bound by value declarations are in the same declaration group if either 1. they are bound by the same pattern binding, or 2. their bindings are mutually recursive (perhaps via some other declarations that are also part of the group). Application of the following rules causes each let or where construct (including the where deﬁning the top level bindings in a module) to bind only the variables of a single declaration group, thus capturing the required dependency analysis: 1 1. The order of declarations in where/let constructs is irrelevant.
£
} in = let { } in (let { 2. let { ; (when no identiﬁer bound in appears free in )
1
} in
A similar transformation is described in Peyton Jones’ book [10].
§
The ﬁrst two can be distinguished because a pattern binding has a — the former cannot be an unparenthesised n+k pattern.
§
¢ £¡
on the left hand side, not a
¦
¡
¦
¡
¦
£
¦
£
¦
¡
¦
¢ £¡
)
4.5. STATIC SEMANTICS OF FUNCTION AND PATTERN BINDINGS
59
4.5.2 Generalization
The HindleyMilner type system assigns types to a letexpression in two stages. First, the righthand side of the declaration is typed, giving a type with no universal quantiﬁcation. Second, all type variables that occur in this type are universally quantiﬁed unless they are associated with bound variables in the type environment; this is called generalization. Finally, the body of the letexpression is typed. For example, consider the declaration f x = let g y = (y,y) in ...
The type of g’s deﬁnition is . The generalization step attributes to g the polymorphic type , after which the typing of the “...” part can proceed. When typing overloaded deﬁnitions, all the overloading constraints from a single declaration group are collected together, to form the context for the type of each variable declared in the group. For example, in the deﬁnition: f x = let g1 x y = if x>y then show x else g2 y x g2 p q = g1 q p in ... String, and the accumulated The types of the deﬁnitions of g1 and g2 are both constraints are Ord (arising from the use of >), and Show (arising from the use of show). The type variables appearing in this collection of constraints are called the constrained type variables. The generalization step attributes to both g1 and g2 the type
Notice that g2 is overloaded in the same way as g1 even though the occurrences of > and show are in the deﬁnition of g1. If the programmer supplies explicit type signatures for more than one variable in a declaration group, the contexts of these signatures must be identical up to renaming of the type variables.
4.5.3 Context Reduction Errors
As mentioned in Section 4.1.4, the context of a type may constrain only a type variable, or the application of a type variable to one or more types. Hence, types produced by generalization must be expressed in a form in which all context constraints have be reduced to this “head normal form”. Consider, for example, the deﬁnition: f xs y = xs == [y]
6
6
Ord
Show
6 ¢
¢
¢
6
¢
¢
¢
¢ & ¢
¢
6
¢
8
¢
¥
¢ & ¢ ¢
6
¢
8
¢
¥
String
60 Its type is given by
CHAPTER 4. DECLARATIONS AND BINDINGS
f :: Eq a => [a] > a > Bool and not f :: Eq [a] => [a] > a > Bool Even though the equality is taken at the list type, the context must be simpliﬁed, using the instance declaration for Eq on lists, before generalization. If no such instance is in scope, a static error occurs. Here is an example that shows the need for a constraint of the form where m is one of the type variables being generalized; that is, where the class applies to a type expression that is not a type variable or a type constructor. Consider: f :: (Monad m, Eq (m a)) => a > m a > Bool f x y = return x == y The type of return is Monad m => a > m a; the type of (==) is Eq a => a > a > Bool. The type of f should be therefore (Monad m, Eq (m a)) => a > m a > Bool, and the context cannot be simpliﬁed further. The instance declaration derived from a data type deriving clause (see Section 4.3.3) must, like , any instance declaration, have a simple context; that is, all the constraints must be of the form where is a type variable. For example, in the type data Apply a b = App (a b) deriving Show
the derived Show instance will produce a context Show (a b), which cannot be reduced and is not simple; thus a static error results.
4.5.4 Monomorphism
Sometimes it is not possible to generalize over all the type variables used in the type of the deﬁnition. For example, consider the declaration f x = let g y z = ([x,y], z) in ... In an environment where x has type , the type of g’s deﬁnition is ([ ] ). The ([ ] ); only can be universally generalization step attributes to g the type quantiﬁed because occurs in the type environment. We say that the type of g is monomorphic in the type variable . The effect of such monomorphism is that the ﬁrst argument of all applications of g must be of a single type. For example, it would be valid for the “...” to be
'
¢
¢
6'
'
§
6
4
¢
'
¢
6
'
6
¢
8
'
¥
¢
¢
¢
¢
4.5. STATIC SEMANTICS OF FUNCTION AND PATTERN BINDINGS
(g True, g False) (which would, incidentally, force x to have type Bool) but invalid for it to be (g True, g ’c’)
§
61
It is worth noting that the explicit type signatures provided by Haskell are not powerful enough to express types that include monomorphic type variables. For example, we cannot write f x = let g :: a > b > ([a],b) g y z = ([x,y], z) in ... because that would claim that g was polymorphic in both a and b (Section 4.4.1). In this program, g can only be given a type signature if its ﬁrst argument is restricted to a type not involving type variables; for example g :: Int > b > ([Int],b) This signature would also cause x to have type Int.
4.5.5 The Monomorphism Restriction
Haskell places certain extra restrictions on the generalization step, beyond the standard HindleyMilner restriction described above, which further reduces polymorphism in particular cases. The monomorphism restriction depends on the binding syntax of a variable. Recall that a variable is bound by either a function binding or a pattern binding, and that a simple pattern binding is a pattern binding in which the pattern consists of only a single variable (Section 4.4.3). The following two rules deﬁne the monomorphism restriction:
¢
8
$
¥
In general, a type .
§
is said to be monomorphic in the type variable
if
¢
¢
is free in
¢
8
$
¥
62 The monomorphism restriction
CHAPTER 4. DECLARATIONS AND BINDINGS
Rule 1. We say that a given declaration group is unrestricted if and only if: (a): every variable in the group is bound by a function binding or a simple pattern binding (Section 4.4.3.2), and (b): an explicit type signature is given for every variable in the group that is bound by simple pattern binding. The usual HindleyMilner restriction on polymorphism is that only type variables that do not occur free in the environment may be generalized. In addition, the constrained type variables of a restricted declaration group may not be generalized in the generalization step for that group. (Recall that a type variable is constrained if it must belong to some type class; see Section 4.5.2.) Rule 2. Any monomorphic type variables that remain when type inference for an entire module is complete, are considered ambiguous, and are resolved to particular types using the defaulting rules (Section 4.3.4).
Motivation
Rule 1 is required for two reasons, both of which are fairly subtle.
Rule 1 prevents computations from being unexpectedly repeated. For example, genericLength is a standard function (in library List) whose type is given by genericLength :: Num a => [b] > a Now consider the following expression: let { len = genericLength xs } in (len, len) It looks as if len should be computed only once, but without Rule 1 it might be computed twice, once at each of two different overloadings. If the programmer does actually wish the computation to be repeated, an explicit type signature may be added: let { len :: Num a => a; len = genericLength xs } in (len, len)
Rule 1 prevents ambiguity. For example, consider the declaration group
[(n,s)] = reads t Recall that reads is a standard function whose type is given by the signature reads :: (Read a) => String > [(a,String)] Without Rule 1, n would be assigned the type Read and s the type Read String. The latter is an invalid type, because it is inherently ambiguous. It is not possible to determine at what overloading to use s, nor can this be solved by adding a type signature for s. Hence, when nonsimple pattern bindings are used (Section 4.4.3.2), the types inferred are always monomorphic in their constrained type variables, irrespective of whether a type signature is provided. In this case, both n and s are monomorphic in .
¢
8
¢
¥
¢
¢
¢
8
¢
¥
There is no danger of recomputation here. Consider module M where len1 = genericLength "Hello" len2 = (2*len1) :: Rational .5. Rule 2 now states that the monomorphic type variable a is ambiguous.4. the same function deﬁned with pattern syntax: f = \x > \y > x+y requires a type signature if f is to be fully overloaded. module M1(len1) where default( Int. and not by any modules that import it. len1 gets type Int. except by performing type inference on modules outside the current module. and must be resolved using the defaulting rules of Section 4. STATIC SEMANTICS OF FUNCTION AND PATTERN BINDINGS The same constraint applies to patternbound functions. and its use in len2 is typeincorrect.4. For example.3.) This issue does not arise for nested bindings. The standard prelude contains many examples of this: sum sum :: (Num a) => [a] > a = foldl (+) 0 Rule 1 applies to both toplevel and nested deﬁnitions. Many functions are most naturally deﬁned using simple pattern bindings. Hence. Anything deﬁned with function syntax usually generalizes as a function is expected to. Double ) len1 = genericLength "Hello" module M2 where import M1(len1) len2 = (2*len1) :: Rational When type inference on module M1 is complete. Rule 2 states that the exact types of all the variables bound in a module must be determined by that module alone. However. because their entire scope is visible to the compiler. 63 Rule 2 is required because there is no way to enforce monomorphic use of an exported binding. a type signature on len1 would solve the problem. Consequences The monomorphism rule has a number of consequences for the programmer.()) both f and g are monomorphic regardless of any type signatures supplied for f or g.g) = ((+). the user must be careful to afﬁx these with type signatures to retain full overloading. (If the above code is actually what is wanted. len1 has the monomorphic type Num a => a (by Rule 1). Thus in f x y = x+y the function f may be used at any overloading in class Num. in (f.
For example. and the type variable a is resolved to Rational when performing type inference on len2. This can be achieved in much the same way as the dependency analysis for value declarations that was described in Section 4.64 CHAPTER 4. and class deﬁnitions into dependency groups. and classes within each group are determined using standard techniques of type inference and kindpreserving uniﬁcation [7]. respectively. constructors. For example. For example. a default of is assumed. the actual kinds for these two constructors are and .5. Instead. i. The ﬁrst step in the kind inference process is to arrange the set of datatype. adding the following deﬁnition to those above does not inﬂuence the kind inferred for Tree (by changing it to . synonym. It follows that both D and S must have kind and that every instance of class C must have kind .invalid This is important because it ensures that each constructor and class are used consistently with the same kind whenever they are in scope. the following program fragment includes the deﬁnition of a datatype constructor D.6 Kind Inference This section describes the rules that are used to perform kind inference. using the default binding . For example. . a synonym S and a class C. we could assume an arbitrary kind for the a parameter in each of the following examples: data App f a = A (f a) data Tree a = Leaf  Fork (Tree a) (Tree a) This would give kinds and for App and Tree. for instance). It is possible that some parts of an inferred kind may not be fully determined by the corresponding deﬁnitions. to calculate a suitable kind for each type constructor and class appearing in a given program. 4. and instead generates a static error because the kind of []. in such cases. all of which would be included in the same dependency group: data C a => D a = Foo (S a) type S a = [D a] class C a where bar :: a > D a > Bool The kinds of variables. in the deﬁnitions above. and would require an extension to allow polymorphic kinds. Defaults are applied to each dependency group without consideration of the ways in which particular type constructor constants or classes are used in later dependency groups or elsewhere in the program. the parameter a appears as an argument of the function constructor (>) in the type of bar and hence must have kind . does not match the kind that is expected for an argument of Tree: type FunnyTree = Tree [] . type inference ﬁnds that len1 has the monomorphic type (Num a => a). 6 6 6 6 9 6 6 ¡ 6 6 6 ¡ 6 9 6 6 ¡ ¡ ¡ ¡ .e. for any kind . DECLARATIONS AND BINDINGS Here. respectively.
5. datatypes. in an environment created by a set of imports (resources brought into scope from other modules). We use the term entity to refer to a value. It is equivalent to the following singlemodule program: There are two minor exceptions to this statement.. which must be a computation of type IO for some type (see Chapter 7). 1 65 . default declarations scope over a single module (Section 4. one of which. Second.f module A where f = . module B where f = . here is a threemodule program: module Main where import A import B main = A.5) is affected by module boundaries. must be called Main and must export the value main.f >> B. For example. or class deﬁned in. Modules may reference other modules via explicit import declarations. and then concatenating all the module bodies1 . When the program is executed. changing all occurrences to refer to the appropriate unique name.. etc. each giving the name of a module to be imported and specifying its entities to be imported. A multimodule Haskell program can be converted into a singlemodule program by giving each entity a unique name. (see Chapter 4). type. type synonyms. The value of the program is the value of the identiﬁer main in module Main. and its result (of type ) is discarded. making them available to other modules.3. A Haskell program is a collection of modules.. Modules may be mutually recursive. the computation main is performed.Chapter 5 Modules A module deﬁnes a collection of values. It exports some of these resources.. by convention. or perhaps exported from a module. Modules are used for namespace control.4). First. classes. imported into. Rule 2 of the monomorphism restriction (Section 4. and are not ﬁrst class values.
3) that specify modules to be imported. . CHAPTER 5. If this is used. classes. . data types. Chapter 4). . i. the module name. .. } } } 2 ¨ ©§ ¤ 5@¤32 7 ¢ ¡ ¦ ¡ § 2 4 module ¦ where 2 4 ¦ ' ¡ ¦ ¦ 7 ¥ © 7¥ 7 ¥ ¡ ¦ ¡ ¦ ' 2 6 6 6 6 6 6 © © 2§ 7¥ ¦ ¡ 4 § © ¦ ¡ § 2 4 ¦ ¦ 7 ¥ ¦ ¡ 7 ©§ ¤ @¤32 $ 7 ¦ ¦ ' ¡ 2 4 2§ 2 ¢ ¡ . The namespace for modules themselves is ﬂat.2 Export Lists ¦ ¨ A§ ¤ !¤32 ¢ S 8 8 ¥¥8 ¡ ¤32 § ¤ ¢ ¡ ( . optionally restricting the imported bindings.. Section 5. ). and a list of entities (enclosed in round parentheses) to be exported.6). then the layout rule applies for the top level of the module. A module begins with a header: the keyword module. The header is followed by a possiblyempty list of import declarations ( . consisting only of the module body. (see Chapter 4). which is imported into all modules by default (see Section 5.66 module Main where main = af >> bf af = . . If the ﬁrst lexeme in the abbreviated module is not a {. with each module being associated with a unique module name (which are Haskell identiﬁers beginning with a capital letter. plus a set of standard library modules that may be imported as required (see Part II).1 Module Structure A module deﬁnes a mutually recursive scope containing declarations for value bindings. 7 ¦ © ¡ 2§ © © 4§ ¡ 2§ 7 ¥ ¦ ¡ 4 § ¡ 7 ¥ ¦ § ¡ 32 ¦ 2§ ¦ ¡ 4§ ¦ ¡ 4§ { { { .. modules allow a program to be partitioned freely without regard to dependencies. This is followed by a possiblyempty list of toplevel declarations . ) ¦ § ¦ ¦ A 2§ 7 A ¥ ¦ ¡ 4 § ¡ 7 ¥ ¦ ¡ 8 8 ¥¥8 8 8 ¥¥8 . © 5. MODULES Because they are allowed to be mutually recursive. bf = . ¦ ¦ § 5.. the header is assumed to be ‘module Main(main) where’. There is one distinguished module.e. Prelude. ( An abbreviated form of module. type synonyms. etc. is permitted.
. The abbreviated form (. one of these subordinate names is legal if and only if (a) it names a constructor or ﬁeld of . or that it imports from some other module. may . . but not those that are imported.. The constructor In all cases. Entities in an export list may be named as follows: 1. A type synonym is in scope.) ( (.8). ) ¦ ¦§ ¦ ¦ § ¢ ¢ ¢ ¡ ¢¨ ¦ ¦ § 2 4 ¦ 2 ¤ 3¥ %§ ¦ 72 ¨ © ¡ ¨ ¤ ¢ ¢ %§ 6 6 § ¤ ¤32 4 ¦ ¢ ¡ ¢ ¡ .2. For example. ). EXPORT LISTS 67 . If the export list is omitted.Maybe( Nothing. ﬁeld name. whether declared in the module body or imported. Operators be named by giving the name of the value as a s. all values. ) An export list identiﬁes the entities to be exported by a module declaration. ¦ declared by a type declaration may be named by the form ¡ £ 8 8 ¥¥8 ¢ £ 4. A class with operations of three ways: 8 8 ¥¥8 ¢ The form names. types and classes deﬁned in the module are exported. or class method. the (possiblyqualiﬁed) type constructor and ﬁeld names in the second form are unqualiﬁed.5. ( . . A value. the following is legal module A( Mb. The ability to export a type without its constructors allows the construction of abstract datatypes (see Section 5.. where ¨ ¦ § ¨ A ¤ ¥¥8 ¡ ¤ 8 8 ¢ ¥¥8 ¢ A 5 4 ¦ ¡ ¢ 4 ¦ 8 8 ¤ ¢ ¤ ¦ § (.) ( module .) names the type and all its constructors and ﬁeld names that are currently in scope (whether qualiﬁed or not). 3. must be in scope. A module implementation may only export an entity that it declares. which must be in scope. An algebraic datatype of three ways: declared by a data or newtype declaration may be named in one The form names the type but not the constructors or ﬁeld names. and (b) the constructor or ﬁeld is in scope in the module body regardless of whether it is in scope under a qualiﬁed or unqualiﬁed name.. because they cannot otherwise be distinguished from type constructors. names the type and some or all of its constructors and ﬁeld declared in a class declaration may be named in one . Just ) ) where import qualified Maybe as Mb Data constructors cannot be named in export lists except as subordinate names. should be enclosed in parentheses to turn them into 2.
¡ ¦ The form names the class but not the class methods. 5. A module can name its own local deﬁnitions in its export list using its own name in the “module M” syntax.e”. item (1) above). For example: module Queue( module Stack.) names the class and all its methods that are in scope (whether qualiﬁed or not). a ﬁeld name f from data type T may be exported individually (f. The unqualiﬁed names of the entities exported by a module must all be distinct (within their respective namespace).5.. item (5)). MODULES The abbreviated form (. module Mod2 ) where import Mod2 import Mod3 Here module Mod1 exports all local deﬁnitions as well as those imported from Mod2 but not those imported from Mod3.. module B ) where import B(f) import qualified C(f. ¡ £ .g. enqueue. In all cases. In the second form. names the class and some or all of its methods. must be in scope. dequeue ) where import Stack .f... It is an error to use module M in an export list unless M is the module bearing the export list. because a local declaration brings into scope both a qualiﬁed and unqualiﬁed name (Section 5. item (2)). or by exporting an entire module (module M.68 CHAPTER 5. . Exports lists are cumulative: the set of entities exported by an export list is the union of the entities exported by the individual items of the list.g) g = f True . one of the (unqualiﬁed) subordinate names is legal if and only if (a) it names a class method of . For example module A ( C. The form “module M” names the set of all entities that are in scope with both an unqualiﬁed name “e” and a qualiﬁed name “M. or as an implicitlynamed member (T(.). g. ). For example: module Mod1( module Mod1. C.1). For example. or as an explicitlynamed member of its data type (T(f). This set may be empty. but there are name clashes in the export list ¦ £ 8 8 ¥¥8 ¢ £ The form ( . It makes no difference to an importing module how an entity was exported. or M is imported by at least one import declaration (qualiﬁed or unqualiﬁed). item(2)). and (b) the class method is in scope in the module body regardless of whether it is in scope under a qualiﬁed or unqualiﬁed name.an invalid module There are no name clashes within module A itself. Here the module Queue uses the module name Stack in its export list to abbreviate all the entities imported from Stack.
) ¨ ¨ A 5 4 ¦ ¢¥¥8 8 8 ¡ ¢ ¡ ¤ 4 ¦ ¢ (. “qualified” and “hiding” are each a a . rather than Lexically.. methods.g and g (assuming C..3. Imported names serve as top level declarations: they scope over the entire body of the module but may be shadowed by local nontoplevel bindings.) ( . The list must name only entities exported by the imported module. or ﬁeld names exported from the module. in which case nothing except the instances is imported. 2 4 ¨ import qualified as .f and C. The imported entities can be speciﬁed explicitly by listing them in parentheses.5. They have special signiﬁcance only in the context of an import declaration. and between module B and C.f are different entities).1 What is imported Exactly which entities are to be imported can be speciﬁed in one of the following three ways: 1. hiding ( . ) ¦ ¦§ ¦ ¦ § ¢ 2 4§ . the terminal symbols “as”.3 Import Declarations § The entities exported by a module may be brought into scope in another module with an import declaration at the beginning of the module. . The list may be empty. the (.) ( (. ¨¡ 8 8 ¥¥8 A§ ¤ 2 4§ ¢ ¡ §¤¤32 4 § 8 8¡ ¥¥8 ¡§ ¤ 2 ( . IMPORT DECLARATIONS 69 between C.) refers to all of the constructors. 5. modules can import each other recursively).. The import declaration names the module to be imported and optionally speciﬁes the entities to be imported. they may also be used as variables. ¦ ¦ § ¦ ¤ ¢ A¤ 8 8 ¥¥8 . A single module may be imported by more than one import declaration. Items in the list have the same form as those in export lists.g and g are different entities – remember. ) ¦ ¨ A !§ ¤ ¦ § ¦ ¦§ ¦ 2 § § ¤ %§ 4 ¢ ¢ ¥ ¦ 7 ¨¡ © 4 § ¨ § 2 4 ¡ ¡ ¦ ¦ . .3. § 5. The ordering of import declarations is irrelevant. except qualiﬁers are not permitted and the ‘module ’ entity is not permitted. The effect of multiple import declarations is strictly cumulative: an entity is in scope if it is imported by any of the import declarations in a module.f (assuming B. When the (.) form of import is used for a type or class.. ) ¦ ¦ ¡ ¦ 2 ¤ 37 2 ¦ ¡ © 4§ ¤ ¢ ¢ %§ %§ 2 4 6 6 6 6 ¦ ¦ § ¤ © 7 § © ¤ 32 ¡ ¡ 4 ¦ ¢ ¡ ¤ ¦ ¡ 4§ 4§ 4§ . .
3. the toplevel environment is extended. in import qualified VeryLongModuleName as C entities must be referenced using ‘C. It is an error to hide an entity that is not.3. only the qualiﬁed name of the entity is brought into scope.3.’.All Prelude names must be qualified . Finally.3) on the import statement. For example. Hence. then both the qualiﬁed and unqualiﬁed name of the entity is brought into scope.70 ¡ ¤32 § ¤ CHAPTER 5. In contrast. or the local alias given in the as clause (Section 5. . in import M hiding (C) any constructor. Section 5.2 Qualiﬁed import For each entity imported under the rules of Section 5. Data constructors may be named directly in hiding lists without being preﬁxed by the associated type. in fact.+ 1) . using C in an import list names only a class or type. If the import declaration used the qualified keyword. class.This + differs from the one in the Prelude . This also allows a different module to be substituted for VeryLongModuleName without changing the 4§ 3. If the qualified keyword is omitted.This * differs from the one in the Prelude 5.3.’ as a qualiﬁer instead of ‘VeryLongModuleName. which speciﬁes that all entities exported by the named module should be imported except for those named in the list. ).1. the qualiﬁer is not necessarily the name of the module in which the entity was originally declared. © 5.3 Local aliases Imported modules may be assigned a local alias in the importing module using the as clause. MODULES 2. if ported.5. The qualiﬁer on the imported name is either the name of the imported module. Thus. exported by the imported module. or type named C is excluded. Entities can be excluded by using the form hiding( . The ability to exclude the unqualiﬁed names allows full programmer control of the unqualiﬁed namespace: a locally deﬁned entity can share the same name as a qualiﬁed import: module Ring where import qualified Prelude import List( nub ) l1 + l2 = l1 Prelude.++ l2 l1 * l2 = nub (l1 + l2) succ = (Prelude. is omitted then all the entities exported by the speciﬁed module are im A !§ ¤ 2 ¡ 4§ 8 8 ¥¥8 ¡ 4§ ¡ ¡ .1 describes qualiﬁed names in more detail.
x A.y (nothing) A. suppose the module A exports x and y.x B.4 Importing and Exporting Instance Declarations Instance declarations cannot be explicitly named on import or export lists.y y. IMPORTING AND EXPORTING INSTANCE DECLARATIONS 71 qualiﬁers used for the imported module.5.x. all instance declarations in scope in module A are imported (Section 5.x.y In all cases.x. B. A.y (nothing) x. For example: module M where import qualified Foo as A import qualified Baz as A x = A.3.y A. y. A.x. An as clause may also be used on an unqualified import statement: import Foo as A(f) This declaration brings into scope f and A.x x. 5.f.4 Examples To clarify the above import rules.y x. B. y.f This module is legal provided only that Foo and Baz do not both export f. A. B. B. provided that all names can still be resolved unambiguously. A. A. Then this table shows what names are brought into scope by the speciﬁed import statement: Import declaration import A import A() import A(x) import qualified A import qualified A() import qualified A(x) import A hiding () import A hiding (x) import qualified A hiding () import qualified A hiding (x) import A as B import A as B(x) import qualified A as B Names brought into scope x.x. 5.y x. y.x. A. A.4.y A.4). A. It is legal for more than one module in scope to use the same qualiﬁer. All instances in scope within a module are always exported and any import brings all instances in from the imported .
A module whose only purpose is to provide instance declarations can have an empty export list.ILLEGAL g x = let M.. 4 ¦ ¢ ¦ ¦ (Section 2. but does bring in any instances visible in M. it is illegal to write module M where M.1 Qualiﬁed names § By a top level declaration.f x = .3).5. MODULES module.f respectively..f.ILLEGAL By an import declaration... always brings into scope the qualiﬁed name of the imported entity (Section 5. An import declaration.y = x+1 in ..5.72 CHAPTER 5. that is. A toplevel declaration brings into scope both the unqualiﬁed and the qualiﬁed name of the entity being deﬁned. 5. whether qualified or not.2 Name clashes If a module contains a bound occurrence of a name. an instance declaration is in scope if and only if a chain of import declarations leads to the module containing the instance declaration. A qualiﬁed name is brought into scope: . it must be possible unambiguously to resolve which entity is thereby referred to. therefore. import M() does not bring any new names in scope from module M.. For example. The deﬁning occurrence must mention the unqualiﬁed name. there must be only one binding for f or A.f x x is legal. For example module MyInstances() where instance Show (a > b) where show fn = "<<function>>" instance Show (IO a) where show io = "<<IO action>>" 5. such as f or A. 2 4 A qualiﬁed name is written as . . This allows a qualiﬁed import to be replaced with an unqualiﬁed one without forcing changes in the references to the imported names. Thus.5 Name Clashes and Closure 5.4). Thus: module M where f x = . g x = M. .
In this case the same entity is brought into scope by two routes (the import of B and the import of C). y = .2). c. There is no reference to y. The reference to d is unambiguously resolved to d declared in D. The reference to x is ambiguous: it could mean x declared in B....5. NAME CLASHES AND CLOSURE 73 It is not an error for there to exist names that cannot be so resolved. c. so it is not erroneous that distinct entities called y are exported by both B and C. b = .4... even though the Prelude function sin is implicitly in scope. B. and can be referred to in A by the names d.d. x. The references to b and c can be unambiguously resolved to b declared in B..sin x) The local declaration for sin is legal. d. An error is only reported if y is actually mentioned.... For example. y ) where import D x = . provided that the program does not mention those names. c = ...5. and C.. b. the following module is legal: module F where sin :: Float > Float sin x = (x::Float) f x = Prelude. The name occurring in a type signature or ﬁxity declarations is always unqualiﬁed.x. y ) where import D x = . x) module B( d.x or C. x. Consider the deﬁnition of tup. For example: module A where import B import C tup = (b. y = . or x declared in C... module D( d ) where d = . and c declared in C respectively. The ambiguity could be ﬁxed by replacing the reference to x by B. module C( d.d. . and unambiguously refers to another declaration in the same declaration list (except that the ﬁxity declaration for a class method can occur at top level — Section 4.sin (F.
these are interchangeable even when T is not in scope.” In Haskell.sin and F. MODULES The references to Prelude.5. Whether or not T is explicitly exported. 5. However. For example.sin must both be qualiﬁed to make it unambiguous which sin is meant.74 CHAPTER 5. The Haskell system silently imports any information that must accompany an entity for type checking or any other purposes. and functions. the unqualiﬁed name sin in the type signature in the ﬁrst line of F unambiguously refers to the local declaration for sin. the import of a variable x does not require that the datatypes and classes in the signature of x be brought into the module along with x unless these entities are referenced by name in the user program.6 Standard Prelude Many of the features of Haskell are deﬁned in Haskell itself as a library of standard datatypes. every name explicitly mentioned by the source code must be either deﬁned locally or imported from another module. the type checker ﬁnds the deﬁnition of T if needed whether or not it is exported. 5. Such entities need not even be explicitly exported: the following program is valid even though T does not escape M1: module M1(x) where data T = T x = T module M2 where import M1(x) y = x In this example. That is. the Prelude is contained in the . entities that the compiler requires for type checking or other compile time analysis need not be imported if they are not mentioned by name. The type of an exported entity is unaffected by nonexported type synonyms. in module M(x) where type T = Int x :: T x = 1 the type of x is both T and Int. the deﬁnition of T is available to any module that encounters it whether or not the name T is in scope. That is.3 Closure Every module in a Haskell program must be closed. However. The only reason to export T is to allow other modules to refer it by name. called the “Standard Prelude. there is no way to supply an explicit type signature for y since T is not in scope. The Haskell compilation system is responsible for ﬁnding any information needed for compilation without the help of the programmer. module M2 knows enough about T to correctly type check the program. That is. classes.
6. These are deﬁned in Part II Separating libraries from the Prelude has the advantage of reducing the size and complexity of the Prelude. and most of the input/output are all part of the standard libraries. every module that does so must have an import declaration that makes this nonstandard usage explicit. Chapter 8 deﬁnes the module Prelude using several other modules: PreludeList.6. and so on. There are also many predeﬁned library modules. STANDARD PRELUDE 75 module Prelude.2 Shadowing Prelude Names The rules about the Prelude have been cast so that it is possible to use Prelude names for nonstandard purposes. they should be considered part of its implementation. complex numberss. For example. given in Chapter 8. The latter would be ambiguous without the hiding(null) on the . PreludeIO. they are not formally deﬁned in Chapter 8. and they cannot be imported separately. for example. arrays. This provision for explicit import allows entities deﬁned in the Prelude to be selectively imported. but the implementation only gives a scheme. The semantics of the entities in Prelude is speciﬁed by a reference implementation of Prelude written in Haskell.5. which provide less frequently used functions and types. This means. These modules are not part of Haskell 98. The implementation of Prelude is also incomplete in its treatment of tuples: there should be an inﬁnite family of tuples and their instance declarations. allowing it to be more easily assimilated. and increasing the space of useful names available to the programmer. not part of the language deﬁnition. that a compiler may optimize calls to functions in the Prelude without consulting the source code of the Prelude. Some datatypes (such as Int) and functions (such as Int addition) cannot be speciﬁed directly in Haskell. Prelude and library modules differ from other modules in that their semantics (but not their implementation) are a ﬁxed part of the Haskell language deﬁnition. just like those from any other module. For example: module A( null. nonNull :: Int > Bool null x = x == 0 nonNull x = not (null x) Module A redeﬁnes null. Since the treatment of such entities depends on the implementation. 5. nonNull ) where import Prelude hiding( null ) null. 5.1 The Prelude Module The Prelude module is imported automatically into all modules as if by the statement ‘import Prelude’. however. and contains an unqualiﬁed reference to null on the right hand side of nonNull. They are simply there to help explain the structure of the Prelude module. if and only if it is not imported with an explicit import declaration.6.
Explicit type signatures for all exported values may be necessary to deal with mutual recursion. push. the Prelude is an ordinary Haskell module.8 Abstract Datatypes The ability to export a datatype without its constructors allows the construction of abstract datatypes (ADTs).) x x h x = [x] ++ [] the explicit import Prelude() declaration prevents the automatic import of Prelude. there is no way to redeﬁne the meaning of [x].76 CHAPTER 5. On the other hand. 5. so it refers to ++ imported from MyPrelude. and then makes an unqualiﬁed reference to null must also resolve the ambiguous use of null just as A does. Thus there is little danger of accidentally shadowing Prelude names. Redeﬁning names used by the Prelude does not affect the meaning of these special constructs. it is special only in that some objects in the Prelude are referenced by special syntactic constructs. For example. The precise details of separate compilation are not deﬁned by this report. while the declaration import MyPrelude brings the nonstandard prelude into scope. pop. in module B where import Prelude() import MyPrelude f x = (x. an ADT for stacks could be deﬁned as: module Stack( StkType. however. MODULES import Prelude statement.)) and lists (such as [x] and []) continues to refer to the tuples and lists deﬁned by the standard Prelude.x) and (. Other than the fact that it is implicitly imported.x) g x = (. to hide instance declarations in the Prelude. The special syntax for tuples (such as (x. For example. the use of ++ is not special syntax. in terms of a different implementation of lists. For example. 5. separate compilation of mutually recursive modules may require that imported modules contain additional information so that they may be referenced before they are compiled. empty ) where data StkType a = EmptyStk  Stk a (StkType a) push x s = Stk x s pop (Stk _ s) = s empty = EmptyStk . It is not possible.7 Separate Compilation Depending on the Haskell implementation used. for example. Every module that imports A unqualiﬁed. It is possible to construct and use a different module to serve in place of the Prelude. one cannot deﬁne a new instance for Show Char.
pop. empty ) where newtype StkType a = Stk [a] push x (Stk s) = Stk (x:s) pop (Stk (_:s)) = Stk s empty = Stk [] .8.5. they must use push. Instead. and empty to construct such values. For example. push. ABSTRACT DATATYPES 77 Modules importing Stack cannot construct values of type StkType because they do not have access to the constructors of the type. It is also possible to build an ADT on top of an existing type by using a newtype declaration. pop. stacks can be deﬁned with lists: module Stack( StkType.
78 CHAPTER 5. MODULES .
Enum. Eq.4. we describe the types and classes found in the Prelude. and functions that are implicitly imported into every Haskell program. and rationals are deﬁned in Part II. 6. Show. Other predeﬁned types such as arrays. The basic boolean functions are && (and). Enum. 6. When appropriate. The name otherwise is deﬁned as True to make guarded expressions more readable.2 Characters and Strings The character type Char is an enumeration whose values represent Unicode characters [11].1 Booleans data Bool = False  True deriving (Read. and not. Bounded) The boolean type Bool is an enumeration. The lexical syntax for characters is deﬁned in Section 2.1. complex numbers.1. Most functions are not described in detail here as they can easily be understood from their deﬁnitions as given in Chapter 8.  (or). In this chapter.Chapter 6 Predeﬁned Types and Classes The Haskell Prelude contains predeﬁned classes. the Haskell deﬁnition of the type is given.6. types. Some deﬁnitions may not be completely valid on syntactic grounds but they faithfully convey the meaning of the underlying type.1 Standard Haskell Types These types are deﬁned by the Haskell Prelude. character literals are nullary constructors in the datatype Char. Show. 6. Ord. Numeric types are described in Section 6. Ord. and 79 . Type Char is an instance of the classes Read. Eq.
although with special syntax. . Lists are an instance of classes Read. but some Haskell implementations may restrict the size of tuples. of course. and limit the instances associated with larger tuples. and \n and \LF. Bounded. map characters to and from the Int type. every Haskell implementation must support tuples up to size 15. Read. A string is a list of characters: type String = [Char] Strings may be abbreviated using the lexical syntax described in Section 2. The same holds for tuple type constructors. For example. \v and \VT. The Prelude and libraries deﬁne tuple functions such as zip for tuples up to a size of 7. Bounded. (Int. "A string" abbreviates [ ’A’. Ord) Lists are an algebraic datatype of two constructors. as deﬁned in Section 3. are described in Sections 3.1.’n’. The following functions are deﬁned for pairs (2tuples): fst.4 Tuples Tuples are algebraic datatypes with special syntax. \t and \HT. \r and \CR. and uncurry.Int) and (. \f and \FF. thus (x.10 and 3. and MonadPlus. there are the following equivalences: \a and \BEL.) Int Bool Int denote the same type. PREDEFINED TYPES AND CLASSES Bounded. and the \ˆ notation.1) deﬁnes many standard list functions. In addition. 6. and Show. respectively. ASCII mnemonic escapes.’s’. Arithmetic sequences and list comprehensions. Ord.80 CHAPTER 6. that all their component types are). snd. Monad. written ‘[]’ (“nil”). and the second is ‘:’ (“cons”).7.3 Lists data [a] = []  a : [a] deriving (Eq. All tuples are instances of Eq. as described in Section 3. standard functions from class Enum. and Show (provided. two convenient syntaxes for special kinds of lists. Each tuple type has a single constructor. Similar functions are not predeﬁned for larger tuples.6.Bool.’g’] 6. Functor.) x y produce the same value. thus. The module PreludeList (see Section 8. There is no upper bound on the size of a tuple.’t’. curry. \b and \BS.1.8. Show. The ﬁrst constructor is the null list. However.’ ’.y) and (.’r’. The constructor for a tuple is written by omitting the expressions surrounding the commas. Ord. Read. together with the instances for Eq. ’i’. Note that ASCII control characters each have several representations in character literals: numeric escapes. Eq.11.. Ord. The toEnum and fromEnum functions.
Ord. Bounded. IOError is an abstract type representing errors raised by I/O operations. Sometimes it is desirable to force the evaluation of a value.8 Other Types data data data Maybe a Either a b Ordering = = = Nothing  Just a deriving (Eq.1. Enum. and MonadPlus. that is. Show) member. The functions maybe and either are found in the Prelude. The unit datatype () has one non 6. ($).1.3). and until. Enum.). Show) LT  EQ  GT deriving (Eq. Show) Left a  Right b deriving (Eq. Bounded. 6. Ord.6 Function Types Functions are an abstract type: no constructors directly create functional values. flip. STRICT EVALUATION 81 6. Read. See also Section 3. 6. using the seq function: seq :: a > b > b .9. Show) The Maybe type is an instance of classes Functor.1. The following simple functions are found in the Prelude: id. Ord. Read. the nullary constructor ().6. (. Read.7 The IO and IOError Types The IO type serves as a tag for operations (actions) that interact with the outside world.5 The Unit Datatype data () = () deriving (Eq. a function argument is evaluated only when required. Read. Ord. Values of this type are constructed by the various I/O functions and are not presented in any further detail in this report. Chapter 7 describes I/O operations. 6. The IO type is abstract: no constructors are visible to the user. Monad.1. IO is an instance of the Monad and Functor classes. It is an instance of Show and Eq.2. The Ordering type is used by compare in the class Ord. The Prelude contains a few I/O functions (deﬁned in Section 8. const. and Part II contains many more.2 Strict Evaluation Function application in Haskell is nonstrict.
$ has low. The Prelude also deﬁnes the $ operator to perform nonstrict application. the not the same as \x > existence of seq weakens Haskell’s parametricity properties. If there is no such comment.1 The Eq Class class Eq a where (==). The operator $! is strict (callbyvalue) application. since seq can be used to distinguish them.2. .3. such as map ($ 0) xs. For the same reason. because it is available at every type. so it sometimes allows parentheses to be omitted. then all class methods must be given to fully specify an instance. provide a reasonable deﬁnition for all the class methods. rightassociative binding precedence. and is deﬁned in terms of seq. since ordinary application (f x) means the same as (f $ x). (/=) :: x /= y x == y a > a > Bool = not (x == y) = not (x /= y) ¡¢ 0§ ' ' ¢ seq seq ' . Default class method declarations (Section 4. $! ($).1) are deﬁned in terms of the $! operator. infixr 0 $.3 Standard Haskell Classes Figure 6. A comment with each class declaration in Chapter 8 speciﬁes the smallest collection of method deﬁnitions that.3) are provided for many of the methods in standard classes. PREDEFINED TYPES AND CLASSES The function seq is deﬁned by the equations: seq is usually introduced to improve performance by avoiding unneeded laziness.1 shows the hierarchy of Haskell classes deﬁned in the Prelude and the Prelude types that are instances of these classes.82 CHAPTER 6. the provision of seq has is important semantic consequences. 6. However. ($!) :: (a > b) > a > b f $ x = f x f $! x = x ‘seq‘ f x The nonstrict application operator $ may appear redundant. As a consequence. for example: f $ g $ h x = f (g (h x)) It is also useful in higherorder situations. or zipWith ($) fs xs. together with the default declarations. However. 6. Strict datatypes (see Section 4.
Bool. Double Real Int. (>) Read All except IO. Char. tuples Enum (). Double Monad IO. Double Floating Float. Float. Integer. Float. STANDARD HASKELL CLASSES 83 Eq All except IO. Integer. Double Fractional Float. Integer.3. Double RealFloat Float. (>) Show All except IO. Double Integral Int. Ordering. Int. (>) Ord All except (>) IO. Bool. Maybe Functor IO. Maybe Figure 6.1: Standard Haskell Classes . [].6. Double Bounded Int. Integer RealFrac Float. Char. Float. () Ordering. IOError Num Int. [].
If an instance declaration for Eq deﬁnes neither == nor /=.3. All basic datatypes except for functions.2 The Ord Class class (Eq a) => Ord a where compare :: a > a > Ordering (<). (>=). The Ordering datatype allows a single comparison to determine the precise ordering of two objects. then both will loop. PREDEFINED TYPES AND CLASSES The Eq class provides equality (==) and inequality (/=) methods. min :: a > a > a compare x y  x == y = EQ  x <= y = LT  otherwise = GT x x x x <= < >= > y y y y = = = = compare compare compare compare x x x x y y y y /= == /= == GT LT LT GT . The default declarations allow a user to create an Ord instance either with a typespeciﬁc compare function or with typespeciﬁc == and <= functions. IO.Note that (min x max x y  x <= y  otherwise min x y  x <= y  otherwise y.x) y x x y The Ord class is used for totally ordered datatypes. are instances of this class. If one is deﬁned. and IOError. = = = = max x y) = (x. This declaration gives default method declarations for both /= and ==. (<=). 6. each being deﬁned in terms of the other.y) or (y. If both are deﬁned. The declared order of the constructors in the data declaration determines the ordering in derived Ord instances.84 CHAPTER 6. All basic datatypes except for functions and IO are instances of this class. the default method for the other will make use of the one that is deﬁned. Instances of Eq can be derived for any userdeﬁned datatype whose constituents are also instances of Eq. . (>) :: a > a > Bool max. neither default method is used. Instances of Ord can be derived for any userdeﬁned datatype whose constituent types are in Ord.
("". showsPrec and showList return a StringtoString function. Strings produced by showsPrec are usually readable by readsPrec."") <. except function types and IO types. the Prelude provides the following auxiliary functions: reads reads shows shows read read s :: (Read a) => ReadS a = readsPrec 0 :: (Show a) => a > ShowS = showsPrec 0 :: (Read a) => String > a = case [x  (x..lex t] of [x] > x [] > error "PreludeText..6. The method showList is provided to allow the programmer to give a specialised way of showing lists of values.read: no parse" _ > error "PreludeText. rather than between square brackets. show.read: ambiguous parse" . The Int argument to showsPrec and readsPrec gives the operator precedence of the enclosing context (see Section 10. a programmer can easily make functions and IO types into (vacuous) instances of Show.. and returns an ordinary String. to allow constanttime concatenation of its results using function composition. (If desired..3.3. are instances of Show and Read.) For convenience.3 The Read and Show Classes type type ReadS a = String > [(a.String)] ShowS = String > String class Read a where readsPrec :: Int > ReadS a readList :: ReadS [a] . All Prelude types.. default decl for readList given in Prelude class Show a where showsPrec :: Int > a > ShowS show :: a > String showList :: [a] > ShowS showsPrec _ x s = show x ++ s show x = showsPrec 0 x "" .reads s. which uses precedence context zero.. This is particularly useful for the Char type. is also provided.4). A specialised variant. default decl for showList given in Prelude The Read and Show classes are used to convert values to or from strings.t) <. STANDARD HASKELL CLASSES 85 6. by providing an instance declaration. Derived instances of Read and Show replicate the style in which a constructor is declared: inﬁx constructors and ﬁeld names are used on input and output. where values of type String should be shown in double quotes.
The function lex :: ReadS String. pred :: toEnum :: fromEnum :: enumFrom :: enumFromThen :: enumFromTo :: enumFromThenTo :: a > a Int > a a > Int a > [a] a > a > [a] a > a > [a] a > a > a > [a]  [n. of a value. respectively. The functions fromEnum and toEnum map values from a type in Enum to and from Int. The enumFrom. It reads a single lexeme from the input. see Chapter 10.e. fromEnum and toEnum should give a runtime error if the result value is not representable in the result type.86 CHAPTER 6.3. thus: enumFrom x = enumFromTo x maxBound enumFromThen x y = enumFromThenTo x y bound where bound  fromEnum y >= fromEnum x = maxBound  otherwise = minBound The following Prelude types are instances of Enum: .4 The Enum Class class Enum a where succ. If the input string contains only white space. toEnum 7 :: Bool is an error.) If there is no legal lexeme at the beginning of the input string.. PREDEFINED TYPES AND CLASSES shows and reads use a default precedence of 0. The read function reads input from a string. returns []).n’. and returning the characters that constitute the lexeme.] [n. the following should hold: The calls succ maxBound and pred minBound should result in a runtime error.n’.10). discarding initial white space.m] [n. lex returns a single successful “lexeme” consisting of the empty string...m] . The functions succ and pred return the successor and predecessor. lex fails (i.. (Thus lex "" = [("". For any type that is an instance of class Bounded as well as Enum.Default declarations given in Prelude Class Enum deﬁnes operations on sequentially ordered types.] [n.. which must be completely consumed by the input process. methods are used when translating arithmetic sequences (Section 3. used by read. enumFrom and enumFromThen should be deﬁned with an implicit bound. Instances of Enum may be derived for any enumeration type (types whose constructors have no ﬁelds). 6. is also part of the Prelude. For example.."")].
The conversions fromEnum and toEnum convert between the type and Int. the list is empty if . Char: the instance is given in Chapter 8. is . . For all four numeric types. ¤ . except that the list terminates when the elements become greater than for positive increment . If the increment is zero. ¥ ¢ The sequence enumFromThenTo is the list [ . 6. or when they become less than for negative . the enumeration functions have the following meaning: The sequence enumFromThen is the list [ . all the list elements are the same. and Maybe are in this class. and pred subtracts 1. Lists. The increment may be zero or negative. ¥ ¢ For Float and Double. . IO. If the increment is the next element would be greater than . and Ordering. the digits after the decimal point may be lost. . 8 8 ¥¥8 § ¤ ¤ ¡ ¡¢ 8 8 ¥¥8 § ¢¢ ¡ ¡ ¡¢ ¡ ¢ ¡ ¡¢ ¡ £ ¡ ¡ ¡ ¤ The sequence enumFrom is the list [ . In the case of Float and Double.GT]. .] is the list [LT. It is implementationdependent what fromEnum returns when applied to a value that is too large to ﬁt in an Int. 8 8 ¥¥8 ¤ § § ¢¥ 8 8 ¥¥8 ¤ ¥ ¥ ¢ ¡ ¢¢ £ ¥¡ § ¡ ¡¤ ¡ ¡¢ § ¡ ¡ ¢¤ ¡ ¢ ¤ § ¥ ¤ £ ¡ ¥ ¡¥ ¥ ¤ ¡ The sequence enumFromTo . succ adds 1. For all four of these Prelude numeric types. STANDARD HASKELL CLASSES 87 Enumeration types: (). the semantics of the enumFrom family is given by the rules for Int above. ..3. ]. . If the increment is positive or zero. where the increment. . Integer. all of the enumFrom family of functions are strict in all their arguments. the list terminates when the next element would be less than . the list terminates when . Float.3. The semantics of these instances is given next. The list is ¥ § ¦ § . Numeric types: Int. enumFromTo ’a’ ’z’ denotes the list of lowercase letters in alphabetical order. For the types Int and Integer. The semantics of these instances is given by Chapter 10. based on the primitive functions that convert between a Char and an Int. empty if is the list [ .5 The Functor Class class Functor f where fmap :: (a > b) > f a > f b The Functor class is used for types that can be mapped over. .6. ]. Double. Bool. [LT. £ ¡ ¥ ¤ § £ £ ¤¡ § ]. where the increment. For example. is . For example.EQ. ]. . the list is empty if negative.
“do” expressions provide a convenient syntax for writing monadic expressions (see Section 3. PREDEFINED TYPES AND CLASSES Instances of Functor should satisfy the following laws: All instances of Functor deﬁned in the Prelude satisfy these laws. fmap g k a m (m >>= k) >>= h . In the Prelude.88 CHAPTER 6. 6. See Chapter 7 for more information about monads. The Prelude provides the following auxiliary functions: sequence sequence_ mapM mapM_ (=<<) :: :: :: :: :: Monad Monad Monad Monad Monad m m m m m => => => => => [m [m (a (a (a a] a] > > > > m > m m b) m b) m b) [a] () > [a] > m [b] > [a] > m () > m a > m b fmap f xs xs >>= return . Maybe.14). The fail method is invoked on patternmatch failure in a do expression. Instances of Monad should satisfy the following laws: Instances of both Monad and Functor should additionally satisfy the law: All instances of Monad deﬁned in the Prelude satisfy these laws.3). and for IO raises a user exception in the IO monad (see Section 7. The fail method for lists returns the empty list []. lists.6 The Monad Class class Monad m (>>=) :: (>>) :: return :: fail :: m >> k fail s where m a > m a > a > m String (a > m b) > m b m b > m b a > m a = m >>= \_ > k = error s The Monad class deﬁnes the basic operations over a monad. g) id fmap f . for Maybe returns Nothing. f return a >>= k m >>= return m >>= (\x > k x >>= h) fmap id fmap (f .3. and IO are all instances of Monad.
1. an implementation may choose error ( . page 83. or a special value such as inﬁnity. The types Int. In particular. The ﬁniteprecision integer type Int covers at . 6. Other numeric types such as rationals and complex numbers are deﬁned in libraries. The class Integral contains integers of both limited and unlimited range. The Bounded class may be derived for any enumeration type. indeﬁnite. aspects of the IEEE ﬂoating point standard have been accounted for in Prelude class RealFloat.6. the type Rational is a ratio of two Integer values. Float is implementationdeﬁned. single precision ﬂoating (Float). Similarly. etc. The standard numeric classes and other numeric functions deﬁned in the Prelude are shown in Figures 6. arbitrary precision integers (Integer). As Int is an instance of the Bounded class. Char. as deﬁned in the Ratio library.7 The Bounded Class class Bounded a where minBound. and the class Floating contains all ﬂoatingpoint types. Bool. maxBound and least the range minBound can be used to determine the exact Int range deﬁned by an implementation. its subclass Real is also a subclass of Ord.3. maxBound :: a The Bounded class is used to name the upper and lower limits of a type. Some. Figure 6. both real and complex.2–6. The class Num of numeric types is a subclass of Eq.1 shows the class dependencies and builtin types that are instances of the numeric classes. These standards require considerably more complexity in the numeric structure and have thus been relegated to a library.4 Numbers Haskell provides several kinds of numbers. Double should cover IEEE doubleprecision.1. Ordering. (). minBound is the ﬁrst constructor listed in the data declaration and maxBound is the last. and all tuples are instances of Bounded. a truncated value. NUMBERS 89 6. the numeric types and the operations upon them have been heavily inﬂuenced by Common Lisp and Scheme. The default ﬂoating point operations deﬁned by the Haskell Prelude do not conform to current language independent arithmetic (LIA) standards.4. it is desirable that this type be at least equal in range and precision to the IEEE singleprecision type. since the other comparison operations apply to all but complex numbers (deﬁned in the Complex library). semantically). The Prelude deﬁnes only the most basic numeric types: ﬁxed sized integers (Int). but not all. The standard numeric types are listed in Table 6. and double precision ﬂoating (Double). since all numbers may be compared for equality. Numeric function names and operators are usually overloaded. ¨ ¡£ ¤ ¡£ ¤ . Bounded may also be derived for singleconstructor datatypes whose constituent types are in Bounded. The results of exceptional conditions (such as overﬂow or underﬂow) on the ﬁxedprecision numeric types are undeﬁned.3. using several type classes with an inclusion relation shown in Figure 6. Ord is not a superclass of Bounded since types that are not totally ordered may also have upper and lower bounds. the class Fractional contains all nonintegral types.
while the class method (/) applies only to fractional ones. and the unary function negate (which can also be written as a preﬁx minus sign. 6. rem. (*). while the result of ‘div‘ is truncated toward negative inﬁnity. divMod is deﬁned similarly: quotRem x y divMod x y = = (x `quot y. An integer literal represents the application of the function fromInteger to the appropriate value of type Integer. The quot.3.1: Standard Numeric Types 6. div. and mod apply only to integral numbers. x ` ` y) ` rem (x `div y. The quotRem class method takes a dividend and a divisor as arguments and returns a (quotient.4) apply to all numbers. see section 3. The class methods quot. remainder) pair.2 Arithmetic and NumberTheoretic Operations The inﬁx class methods (+). rem. even . See Section 4. PREDEFINED TYPES AND CLASSES Type Integer Int (Integral a) => Ratio a Float Double (RealFloat a) => Complex a Class Integral Integral RealFrac RealFloat RealFloat Floating Description Arbitraryprecision integers Fixedprecision integers Rational numbers Real ﬂoatingpoint. Given the typings: fromInteger :: (Num a) => Integer > a fromRational :: (Fractional a) => Rational > a integer and ﬂoating literals have the typings (Num a) => a and (Fractional a) => a.4 for a discussion of overloading ambiguity.5. Similarly. Numeric literals are deﬁned in this indirect way so that they may be interpreted as values of any appropriate numeric type.90 CHAPTER 6.4. double precision Complex ﬂoatingpoint Table 6. ().4. Ratio Integer). single precision Real ﬂoatingpoint. div. and mod class methods satisfy these laws if y is nonzero: (x ` quot y)*y + (x ` ` y) == x ` rem (x ` ` y)*y + (x ` ` y) == x div mod ‘quot‘ is integer division truncated toward zero. a ﬂoating literal stands for an application of fromRational to a value of type Rational (that is. x `mod y) ` ` Also available on integral numbers are the even and odd predicates: even x = odd = x ` ` 2 == 0 rem not .1 Numeric Literals The syntax of numeric literals is given in Section 2. respectively.
atan :: a > a sinh. rem. div.4. divMod toInteger => :: :: :: Integral a where a > a > a a > a > (a. Enum a) quot. There are three twoargument exponentiation operations: (ˆ) raises any number to a nonnegative integer power. Ord a) => Real a where toRational :: a > Rational class (Real a. gcd 0 4 = 4. gcd (3) (6) = 3. (ˆˆ) raises a fractional number to any integer power. gcd is the greatest (positive) integer that divides both and . mod quotRem. 0** is undeﬁned. The value of ˆ0 or ˆˆ0 is 1 for any . atanh :: a > a Figure 6. logBase returns the logarithm of in base . logBase :: a > a > a sin. acos. gcd 0 0 raises a runtime error. and (**) takes two ﬂoatingpoint arguments.3 Exponentiation and Logarithms The oneargument exponential function exp and the logarithm function log act on ﬂoatingpoint numbers and use base . log. (*) negate abs. Part 1 Finally. for example gcd (3) 6 = 3. acosh. ().a) a > Integer class (Num a) => Fractional a where (/) :: a > a > a recip :: a > a fromRational :: Rational > a class (Fractional a) => Floating a where pi :: a exp. ¢ )¢ lcm is the smallest positive integer that both and divide. including zero. tan :: a > a asin. sqrt :: a > a (**). ¢ ¢ ¢ ¢ ¢ ¢ ¢ ¢ ¢ . 6.2: Standard Numeric Classes and Related Operations. NUMBERS class (Eq a.6. cos.4. signum fromInteger a) :: :: :: :: => Num a where a > a > a a > a a > a Integer > a 91 class (Num a. tanh :: a > a asinh. Show (+). there are the greatest common divisor and least common multiple functions. sqrt returns the principal square root of a ﬂoatingpoint number. cosh.
isIEEE :: a > Bool atan2 :: a > a > a gcd. Part 2 6. Fractional a) => RealFrac properFraction :: (Integral b) => a truncate. isDenormalized. Fractional b) => a > b Figure 6.Int) encodeFloat :: Integer > Int > a exponent :: a > Int significand :: a > a scaleFloat :: Int > a > a isNaN. Integral b) => a > b > a fromIntegral :: (Integral a. floor :: (Integral b) => a class (RealFrac a. these functions are deﬁned by: abs x  x >= 0  x < 0 = x = x = 1 = 0 = 1 signum x  x > 0  x == 0  x < 0 . Floating a) => RealFloat a where floatRadix :: a > Integer floatDigits :: a > Int floatRange :: a > (Int.92 CHAPTER 6.a) b b class (Real a.Int) decodeFloat :: a > (Integer. round :: (Integral b) => a ceiling. isNegativeZero.4 Magnitude and Sign A number has a magnitude and a sign.4. Num b) => a > b realToFrac :: (Real a. lcm :: (Integral a) => a > a> a (ˆ) :: (Num a. Integral b) => a > b > a (ˆˆ) :: (Fractional a. The functions abs and signum apply to any number and satisfy the law: abs x * signum x == x For real numbers. isInfinite. PREDEFINED TYPES AND CLASSES a > > > where (b.3: Standard Numeric Classes and Related Operations.
truncate. inclusive.4. NUMBERS 93 6. machineindependent access to the components of a ﬂoatingpoint number. logBase. tanh. either and are both zero or else of floatDigits x. which in turn follows Penﬁeld’s proposal for APL [9]. approxRational takes two real fractional arguments and and returns the simplest rational number within of . and the lowest and highest values the exponent may assume. the number of digits of this radix in the signiﬁcand. cosine. atan2 1. and tangent functions and their inverses. **. Two functions convert numbers to type Rational: toRational returns the rational equivalent of its real argument with full precision. encodeFloat performs the inverse of this transformation. the greatest integer not greater than . See these references for discussions of branch cuts. The function properFraction takes a real fractional number and returns a pair such that . respectively. ). and floor . The functions ¦ ' ¥ ¢ ¢ ¢ 0 ¦ ¦ 0 ¢ ¢ £ ¡ ¢ ' 0 ¦ ¢ 4 A ¢ ' ¢ 4 ¡ ¦¥ ' ¥ ¢ ¢ 1 ¢ ¢ ¢ ¢ 1 ¡ ¦ ¢ ¦ £ ¡ ¤ 4 4 1 £ 1 ¡ ¢ £ ¢ ¦ ¢ ¢ 0 ¢ ¦ ¢ . then x is equal in value to . but implementors are free to provide more accurate implementations. with in a type that is RealFloat. and: is an integral number with the same sign as . and implementation. Every real interval contains a unique simplest rational. Class RealFloat provides a version of arctangent taking two real ﬂoatingpoint arguments. where a rational in reduced form is simpler than another if and . and furthermore. should return the same value as atan .6 Coercions and Component Extraction The ceiling. and floatRange give the parameters of a ﬂoatingpoint type: the radix of the representation. and round functions each take a real fractional argument and return an integral result. and is a fraction with the same type and sign as . and round functions can be deﬁned in terms of properFraction. but implementors can provide a more accurate implementation. It follows the Common Lisp semantics for the origin when signed zeroes are supported. ¢ ¢ 6.4. truncate. where is the value radix. and with absolute value less than 1.4. truncate yields the integer nearest between and . The ceiling. The functions floatRadix. discontinuities. A default deﬁnition of atan2 is provided. Default implementations of tan. floatDigits. and sqrt are provided. The class methods of class RealFloat allow efﬁcient. note that is the simplest rational of all.6. atan2 computes the angle (from the positive xaxis) of the vector from the origin to the point .5 Trigonometric Functions Class Floating provides the circular and hyperbolic sine. ceiling returns the least integer not less than . in particular. round returns the nearest integer to . pi]. atan2 returns a value in the range [pi. floor. If decodeFloat x yields ( . The function decodeFloat applied to a real ﬂoatingpoint number returns the signiﬁcand expressed as an Integer and an appropriately scaled exponent (an Int). the even integer if is equidistant between two integers. For real ﬂoating and . The precise deﬁnition of the above functions is as in Common Lisp. floor. where is the ﬂoatingpoint .
but rather than an Integer.94 CHAPTER 6. isInfinite. Num b) => a > b realToFrac :: (Real a. and isIEEE all support numbers represented using the IEEE standard. these may all return false. For nonIEEE ﬂoating point numbers. significand x yields a value of the same type as x. Also available are the following coercion functions: fromIntegral :: (Integral a. scaled to lie in the open interval . Fractional b) => a > b . scaleFloat multiplies a ﬂoatingpoint number by an integer power of the radix. isNegativeZero. exponent 0 is zero. PREDEFINED TYPES AND CLASSES significand and exponent together provide the same information as decodeFloat. The functions isNaN. isDenormalized.
1. return and linefeed. the abstract values are the mentioned above. To achieve this. two characters of input. For example.6) sequentially compose actions. corresponding to conventional I/O operations. In the case of the I/O monad. recall that String is a synonym for [Char] (Section 6. corresponding to sequencing operators (such as the semicolon) in imperative languages. an implementation has a great deal of freedom in choosing this order. see Section 6. yet has all of the expressive power found in conventional programming languages. These functions cannot be used portably for binary I/O. it is possible to write many Haskell programs using only the few simple functions that are exported from the Prelude.2). it is best to think of a monad as an abstract datatype. Actions. and which are described in this section.3. as deﬁned in the IO library. however. All I/O functions deﬁned here are character oriented. The treatment of the newline character will vary on different systems. must be ordered in a welldeﬁned manner for program execution – and I/O in particular – to be meaningful. 95 ¦ ¢ ¦ 32 4 7 3¢ ¦ ¢ ¦ 32 4 © ¦ 332 § § ¤¢ . Some operations are primitive actions. however. From the perspective of a Haskell programmer. In the following. The order of evaluation of expressions in Haskell is constrained only by data dependencies.1 Standard I/O Functions Although Haskell provides fairly sophisticated I/O facilities. Haskell uses a to integrate I/O operations into a purely functional context. © ¦ 332 § § ¤¢ © $ 7. may read as a single newline character. Special operations (methods in the class Monad. The term comes from a branch of mathematics known as category theory.Chapter 7 Basic Input/Output The I/O system in Haskell is purely functional. natural to a functional language and The I/O monad used by Haskell mediates between the the that characterize I/O operations and imperative programming in general. Haskell’s I/O monad provides the user with a way to specify the sequential chaining of actions. and an implementation is obliged to preserve this order.
.3) on endofﬁle. These functions read input from the standard input device (normally the user’s :: :: :: :: :: :: IO Char IO String IO String (String > String) > IO () Read a => String > IO a Read a => IO a getChar getLine getContents interact readIO readLn The getChar operation raises an exception (Section 7.) main = interact (filter isAscii) . BASIC INPUT/OUTPUT Output Functions These functions write to the standard output device (this is normally the user’s terminal). The entire input from the standard input device is passed to this function as its argument.19]]) Input Functions terminal). a program to print the ﬁrst 20 integers and their powers of 2 could be written as: main = print ([(n. 2ˆn)  n <.adds a newline Show a => a > IO () The print function outputs a value of any printable type to the standard output device.[0. (The isAscii function is deﬁned in a library.96 CHAPTER 7. putChar putStr putStrLn print :: :: :: :: Char > IO () String > IO () String > IO () . The readIO function is similar to read except that it signals parse failure to the I/O monad instead of terminating the program. For example. The readLn function combines getLine and readIO. and the resulting string is output on the standard output device. which is read lazily as it is needed. print converts values to strings for output using the show operation and adds a newline. The interact function takes a function of type String>String as its argument. The getContents operation returns all user input as a single string. the read operation from class Read is used to convert the string to a value. Printable types are those that are instances of class Show. deﬁned the IO library. The getLine operation raises an exception under the same circumstances as hGetLine. Typically. a predicate isEOFError that identiﬁes this exception is deﬁned in the IO library. The following program simply removes all nonASCII characters from its standard input and echoes the result on its standard output.
on demand. their ﬁrst argument.2.. methods in the Monad class.2]]) 7. their second argument.1. The two monadic binding functions. for example when it is (). The >> function is used where the result of the ﬁrst operation is uninteresting. to the ﬁle.2 Sequencing I/O Operations The type constructor IO is an instance of the Monad class. A message is printed on the standard output before the program completes. The do notation allows programming in a more imperative syntactic style. The writeFile and appendFile functions write or append the string. To write a value of any printable type. main = readFile "inputfile" writeFile "outputfile" (filter isAscii s) putStr "Filtering successful\n" >>= \ s > >> is similar to the previous example using interact. (>>=) :: IO a > (a > IO b) > IO b (>>) :: IO a > IO b > IO b For example. type FilePath = String writeFile :: FilePath > String > IO () appendFile :: FilePath > String > IO () readFile :: FilePath > IO String Note that writeFile and appendFile write a literal string to a ﬁle. are used to compose a series of I/O operations. The readFile function reads a ﬁle and returns the contents of the ﬁle as a string. as with getContents. SEQUENCING I/O OPERATIONS 97 Files These functions operate on ﬁles of characters. The >>= operation passes the result of the ﬁrst operation as an argument to the second operation.7. A slightly more elaborate version of the previous example would be: . main = appendFile "squares" (show [(x. The ﬁle is read lazily. use the show function to convert the value to a string ﬁrst.0. as with print.x*x)  x <. but takes its input from "inputfile" and writes its output to "outputfile".[0. Files are named by strings using some implementationspeciﬁc method to resolve strings as ﬁle names.
For example.3 Exception Handling in the I/O Monad The I/O monad includes a simple exception handling system.isEOFError e then return [] else ioError e) the function f returns [] when an endofﬁle exception occurs in g. Exceptions in the I/O monad are represented by values of type IOError.getChar if c == ’\n’ then return "" else do s <.readFile ifile writeFile ofile (filter isAscii s) putStr "Filtering successful\n" The return function is used to deﬁne the result of an I/O operation. otherwise. using return to deﬁne the result: getLine :: IO String getLine = do c <. Any I/O operation may raise an exception instead of returning a result. The isEOFError function is part of IO library. An exception is caught by the most recent handler established by catch. Exception propagation must be explicitly provided in a handler by reraising any unwanted exceptions. User error values include a string describing the error. in f = catch g (\e > if IO. . getLine is deﬁned in terms of getChar.98 CHAPTER 7.getLine s <. the catch function establishes a handler that receives any exception raised in the action protected by catch. BASIC INPUT/OUTPUT main = do putStr "Input file: " ifile <. the exception is propagated to the next outer handler.getLine putStr "Output file: " ofile <.getLine return (c:s) 7. userError :: String > IOError Exceptions are raised and caught using the following functions: ioError :: IOError > IO a catch :: IO a > (IOError > IO a) > IO a The ioError function raises an exception. The IO library deﬁnes functions that construct and examine IOError values. This is an abstract type: its constructors are hidden from the user. For example. These handlers are not selective: all exceptions are caught. The only Prelude function that creates an IOError value is userError.
(>>) fail s = ioError (userError s) The exceptions raised by the I/O functions in the Prelude are deﬁned in Chapter 21. (>>=).7. The fail method of the IO instance of the Monad class (Section 6. EXCEPTION HANDLING IN THE I/O MONAD 99 When an exception propagates outside the main program.3.. thus: instance Monad IO where .3. .6) raises a userError..bindings for return. the Haskell system prints the associated IOError value and exits the program.
100 CHAPTER 7. BASIC INPUT/OUTPUT .
The Prelude shown here is organized into a root module. indicated by names starting with “prim”. part of the speciﬁcation of the Prelude.. It constitutes a speciﬁcation for the Prelude. These modules are described fully in Part II. length. These imports are not. To take one particular example. of course. are deﬁned in a system dependent manner in module PreludeBuiltin and are not shown here. An ellipsis “. Monad. They do not constitute a speciﬁcation of the meaning of the method in all instances.. drop. of the Library modules. and it is not required that the speciﬁcation be implemented as shown here. given with class declarations. To reduce the occurrence of unexpected ambiguity errors. a number of commonlyused functions over lists use the Int type rather than using a more general numeric type. The default method deﬁnitions. and Numeric. Only the exports of module Prelude are signiﬁcant. 101 . or () are included in the Prelude for completeness even though the declaration may be incomplete or syntactically invalid. an implementation is free to import more. nor are these three modules available for import separately. Declarations for special types such as Integer. Some of these modules import Library modules. and PreludeIO. and three submodules. Many of the deﬁnitions are written with clarity rather than efﬁciency in mind. constitute a speciﬁcation only of the default method. An implementation is not required to use this organisation for the Prelude. as it pleases. Prelude. or less. such as Integral a or Num a. Instance declarations that simply bind primitives to class methods are omitted. the default method for enumFrom in class Enum will not work properly for types whose range exceeds that of Int (because fromEnum cannot map all values in the type to distinct Int values). !!. These functions are: take.Chapter 8 Standard Prelude In this chapter the entire Haskell Prelude is given. PreludeList. Primitives that are not deﬁnable in Haskell. IO. Some of the more verbose instances with obvious functionality have been left out for the sake of brevity. and to improve efﬁciency. such as Char. That is. This structure is purely presentational. PreludeText.” is often used in places where the remainder of a deﬁnition cannot be given in Haskell.
and replicate. for example genericLength.102 CHAPTER 8. The more general versions are given in the List library. with the preﬁx “generic”. STANDARD PRELUDE splitAt. .
fst. IO. min). Num((+). mapM_. (<). Monad((>>=). module PreludeIO. Enum(succ. Integer. sinh. fromEnum. sqrt. and cannot legally appear in an export list. tan. ($!) ) where import import import import import import PreludeBuiltin UnicodePrims( primUnicodeMaxChar ) PreludeList PreludeText PreludeIO Ratio( Rational ) . floor). asTypeOf. Integral(quot. (**). Real(toRational). error. (/=)). mapM.). Right). enumFromThenTo). const. isIEEE. not. Either(Left.. (. GT). (<=). floatRange. logBase. cos.. either. sequence. (). isDenormalized. enumFromTo.)). fromIntegral. quotRem. (ˆ). enumFrom. module PreludeText.Unicode primitives . subtract.Contains all ‘prim’ values . acosh. (&&). (>>). scaleFloat. enumFromThen.103 module Prelude ( module PreludeList. flip. asin. (=<<). log. isInfinite. exponent. (). Bool(False. etc. Int. fromInteger). fromRational). otherwise. fail). Ord(compare. lcm. acos. Trivial type: ()(()) Functions: (>) Eq((==). abs. truncate. isNegativeZero. asinh. RealFrac(properFraction. (>=). (*). RealFloat(floatRadix. (>). div. max. atan2). divMod. Floating(pi. snd. (. recip. signum. realToFrac. undefined. Bounded(minBound. odd.)((. ($). floatDigits. round. Char. isNaN. Functor(fmap). seq. String. gcd. rem. cosh. Float.)((. id. Just). Double. sin. sequence_. toInteger). atanh). These builtin types are defined in the Prelude. decodeFloat. but are denoted by builtin syntax. return. List type: []((:). uncurry. pred. tanh. Fractional((/). maybe. exp. True). Ordering(LT. atan. Rational. curry.)). (ˆˆ). encodeFloat. negate. EQ. []) Tuple types: (. significand. Maybe(Nothing. toEnum. mod. even. maxBound). ceiling. until.
> &&  >>.Equality and Ordered classes class Eq a where (==). instances and related functions . ** *. <.Minimal complete definition: (<=) or compare . min :: a > a > a .note that (min x y. (<=). ‘div‘.Standard types. compare x y  x == y = EQ  x <= y = LT  otherwise = GT x x x x <= < >= > y y y y = = = = compare compare compare compare x x x x y y y y /= == /= == GT LT LT GT .104 infixr infixr infixl infixl 9 8 7 6 CHAPTER 8. ‘mod‘ +.y) or (y. but its fixity is given by: infixr 5 : infix infixr infixr infixl infixr infixr 4 3 2 1 1 0 ==.Minimal complete definition: (==) or (/=) x /= y = not (x == y) x == y = not (x /= y) class (Eq a) => Ord a where compare :: a > a > Ordering (<). ‘quot‘.Using compare can be more efficient for complex types. >=.x) max x y  x <= y = y  otherwise = x min x y  x <= y = x  otherwise = y . /=.  . classes. $!. max x y) = (x. /. ˆˆ. >>= =<< $. (>) :: a > a > Bool max.a fixity declaration. ˆ. (/=) :: a > a > Bool . <=.The (:) operator is builtin syntax. and cannot legally be given . ‘seq‘ . (>=). STANDARD PRELUDE . ‘rem‘.
. signum :: a > a fromInteger :: Integer > a .Numeric classes class (Eq a. fromEnum enumFrom x = map toEnum [fromEnum x .y = x + negate x = 0 definition: negate or () negate y x class (Num a.Enumeration and Bounded classes class Enum a where succ.. (+1) .. (*) :: a > a > a negate :: a > a abs.. Show a) => Num a where (+). fromEnum z] class Bounded a minBound maxBound where :: a :: a . (). fromEnum y] enumFromThen x y = map toEnum [fromEnum x. Ord a) => Real a where toRational :: a > Rational .] enumFromTo x y = map toEnum [fromEnum x . fromEnum y .. fromEnum y .m] .n’.Minimal complete All.NOTE: these default methods only make sense for types that map injectively into Int using fromEnum and toEnum. (subtract 1) . fromEnum .105 .n’.m] [n.] [n..] [n.] enumFromThenTo x y z = map toEnum [fromEnum x. pred toEnum fromEnum enumFrom enumFromThen enumFromTo enumFromThenTo :: :: :: :: :: :: :: a > a Int > a a > Int a > [a] a > a > [a] a > a > [a] a > a > a > [a]  [n.Minimal complete definition: toEnum. fromEnum pred = toEnum . except x .. succ = toEnum ..
atan asinh. mod quotRem. sqrt :: a > a (**). sin.a) a > Integer . toInteger n ‘quot‘ d = q where (q.r) = class (Num a) => Fractional a where (/) :: a > a > a recip :: a > a fromRational :: Rational > a quotRem n d quotRem n d divMod n d divMod n d signum d then (q1. tan :: a > a asin. acosh. cosh.r) = n ‘mod‘ d = r where (q.Minimal complete definition: fromRational and (recip or (/)) recip x = 1 / x x / y = x * recip y class (Fractional a) => Floating a where pi :: a exp. cosh asin.106 class (Real a. r+d) else qr quotRem n d . cos. logBase :: a > a > a sin. atanh x ** y = exp (log x * y) logBase x y = log y / log x sqrt x = x ** 0. STANDARD PRELUDE => Integral a where a > a > a a > a > a a > a > (a. atanh :: a > a . log. rem div.r) = n ‘rem‘ d = r where (q.r) = n ‘div‘ d = q where (q. Enum quot. acos. tanh :: a > a asinh. divMod toInteger a) :: :: :: :: CHAPTER 8. log. exp.Minimal complete definition: quotRem. sinh. atan :: a > a sinh.5 tan x = sin x / cos x tanh x = sinh x / cosh x .Minimal complete definition: pi. cos. acosh. acos.r) = divMod n d = if signum r == where qr@(q.
1 else n + 1 in case signum (abs r .5) of 1 > n 0 > if even n then n else m 1 > m if r > 0 then n + 1 else n where (n.r) = properFraction x ceiling x floor x = = .r) = properFraction x if r < 0 then n . round :: (Integral b) => a ceiling.r) = properFraction x m = if r < 0 then n . Fractional a) => RealFrac properFraction :: (Integral b) => a truncate.Minimal complete definition: properFraction truncate x = m where (m.107 class (Real a._) = properFraction x round x = let (n.0.1 else n where (n. floor :: (Integral b) => a a > > > where (b.a) b b .
n) = decodeFloat x atan2 y x  x>0 = atan (y/x)  x==0 && y>0 = pi/2  x<0 && y>0 = pi + atan (y/x) (x<=0 && y<0)  (x<0 && isNegativeZero y)  (isNegativeZero x && isNegativeZero y) = atan2 (y) x  y==0 && (x<0  isNegativeZero x) = pi . isInfinite.gcd: gcd 0 0 is undefined" = gcd’ (abs x) (abs y) where gcd’ x 0 = x gcd’ x y = gcd’ y (x ‘rem‘ y) . isIEEE :: a > Bool atan2 :: a > a > a .108 CHAPTER 8. STANDARD PRELUDE class (RealFrac a.x or y is a NaN. significand. isDenormalized.must be after the previous test on zero y  x==0 && y==0 = y . even :: (Integral a) => a > a > a = error "Prelude. atan2 exponent x = if m == 0 then 0 else n + floatDigits x where (m.floatDigits x) where (m.Minimal complete definition: All except exponent. scaleFloat.n) = decodeFloat x significand x scaleFloat k x = = encodeFloat m (.Numeric functions subtract subtract even. isNegativeZero.must be after the other double zero tests  otherwise = x + y .Int) decodeFloat :: a > (Integer. return a NaN (via +) .Int) encodeFloat :: Integer > Int > a exponent :: a > Int significand :: a > a scaleFloat :: Int > a > a isNaN._) = decodeFloat x encodeFloat m (n+k) where (m. odd even n odd gcd gcd 0 0 gcd x y :: (Num a) => a > a > a = flip () :: (Integral a) => a > Bool = n ‘rem‘ 2 == 0 = not . Floating a) => RealFloat a where floatRadix :: a > Integer floatDigits :: a > Int floatRange :: a > (Int.
ˆ: negative exponent" :: (Fractional a. Num b) => a > b = fromInteger . Integral b) => a > b > a = 1 = f x (n1) x where f _ 0 y = y f x n y = g x n where g x n  even n = g (x*x) (n ‘quot‘ 2)  otherwise = f x (n1) (x*y) = error "Prelude. but lift the function or .Minimal complete definition: (>>=). toRational . Fractional b) => a > b = fromRational . Integral b) => a > b > a = if n >= 0 then xˆn else recip (xˆ(n)) :: (Integral a.The xxxM functions take list arguments. toInteger :: (Real a.Monadic classes class Functor f fmap where :: (a > b) > f a > f b class Monad m where (>>=) :: m a > (a > m b) > m b (>>) :: m a > m b > m b return :: a > m a fail :: String > m a .109 lcm lcm _ 0 lcm 0 _ lcm x y (ˆ) x ˆ 0 x ˆ n  n > 0 :: = = = (Integral a) => a > a > a 0 0 abs ((x ‘quot‘ (gcd x y)) * y) _ ˆ _ (ˆˆ) x ˆˆ n fromIntegral fromIntegral realToFrac realToFrac :: (Num a.list element to a monad type mapM :: Monad m => (a > m b) > [a] > m [b] mapM f as = sequence (map f as) mapM_ mapM_ f as (=<<) f =<< x :: Monad m => (a > m b) > [a] > m () = sequence_ (map f as) :: Monad m => (a > m b) > m a > m b = x >>= f . return m >> k = m >>= \_ > k fail s = error s sequence sequence sequence_ sequence_ :: Monad m => [m a] > m [a] = foldr mcons (return []) where mcons p q = p >>= \x > q >>= \y > return (x:y) :: Monad m => [m a] > m () = foldr (>>) (return ()) .
Not legal Haskell. True False True False () && x && _  _  x :: = = = = Bool > Bool > Bool x False True x not not True not False otherwise otherwise :: Bool > Bool = False = True :: Bool = True . for illustration only .Function type ..Boolean functions (&&). g = \ x > f (g x) ..110 . . Bounded) .function composition (.identity function id :: a > a id x = x . ...rightassociating infix application operators . ($!) :: (a > b) > a > b f $ x = f x f $! x = x ‘seq‘ f x .Trivial type data () CHAPTER 8.Primitive . Ord. STANDARD PRELUDE = () deriving (Eq..Character type data Char = .(useful in continuationpassing style) ($). Ord.Unicode values instance Eq Char c == c’ where = fromEnum c == fromEnum c’ . Enum.. Read. Enum.flip f takes its (first) two arguments in the reverse order of f. flip :: (a > b > c) > b > a > c flip f x y = f y x seq :: a > b > b seq = . Show.) :: (b > c) > (a > b) > a > c f . ’a’  ’b’ .constant function const :: a > b > a const x _ = x . Bounded) .Boolean type data Bool = False  True deriving (Eq.
Ord. fromEnum c’ .IO type data IO a = .Maybe type data Maybe a = Nothing  Just a deriving (Eq. Read. Show) maybe :: b > (a > b) > Maybe a > b maybe n f Nothing = n maybe n f (Just x) = f x instance Functor Maybe fmap f Nothing = fmap f (Just x) = where Nothing Just (f x) instance Monad Maybe where (Just x) >>= k = k x Nothing >>= k = Nothing return = Just fail s = Nothing .111 instance Ord Char c <= c’ where = fromEnum c <= fromEnum c’ instance Enum Char where toEnum = primIntToChar fromEnum = primCharToInt enumFrom c = map toEnum [fromEnum c .. f) instance Monad IO where (>>=) = . return = .....Either type data Either a b = Left a  Right b deriving (Eq.. . fromEnum lastChar] where lastChar :: Char lastChar  c’ < c = minBound  otherwise = maxBound instance Bounded Char where minBound = ’\0’ maxBound = primUnicodeMaxChar type String = [Char] . Show) either :: (a > c) > (b > c) > Either a b > c either f g (Left x) = f x either f g (Right y) = g y . Read. fail s = ioError (userError s) . Ord... fromEnum (maxBound::Char)] enumFromThen c c’ = map toEnum [fromEnum c.abstract instance Functor IO where fmap f x = x >>= (return .
.... ... .. instance Integral Integer where ... instance Ord Integer where . ... ...... data Integer = .. instance Enum Integer where . STANDARD PRELUDE Ordering = LT  EQ  GT deriving (Eq.... ... instance Num Integer where ... .far too large.... instance Eq Integer where .Standard numeric types. ...be expressed directly in Haskell since the constructor lists would be . .. . Read. instance Real Integer where .. 1  0  1 . .. .. Bounded) . Ord..112 . data Int instance instance instance instance instance instance instance = minBound .... 1 Eq Int where Ord Int where Num Int where Real Int where Integral Int where Enum Int where Bounded Int where  0  1 ..... . . maxBound . where where where where where where where where ... . ..... .... Enum. .. Show. ........ data Float instance Eq instance Ord instance Num instance Real instance Fractional instance Floating instance RealFrac instance RealFloat data Double instance Eq instance Ord instance Num instance Real instance Fractional instance Floating instance RealFrac instance RealFloat Float Float Float Float Float Float Float Float Double Double Double Double Double Double Double Double where where where where where where where where .. . ... The data declarations for these types cannot . .Ordering type data CHAPTER 8......
The ‘toEnum’ function truncates numbers to Int. Ord a) => a > a > a > [a] iterate (+1) iterate (+(mn)) n takeWhile (<= m+1/2) (numericEnumFrom n) m = takeWhile p (numericEnumFromThen n n’) where p  n’ >= n = (<= m + (n’n)/2)  otherwise = (>= m + (n’n)/2) . Ord a) => a > a > [a] (Fractional a. Ord) .0. However.. depending on how 0.may overflow (Fractional a) => a > [a] (Fractional a) => a > a > [a] (Fractional a. for illustration only instance Functor [] where fmap = map instance Monad [] m >>= k return x fail s where = concat (map k m) = [x] = [] . roundoff errors make these somewhat dubious.Lists data [a] = []  a : [a] deriving (Eq.95]. The definitions of enumFrom and enumFromThen allow floats to be used in arithmetic series: [0. truncate enumFrom = numericEnumFrom enumFromThen = numericEnumFromThen enumFromTo = numericEnumFromTo enumFromThenTo = numericEnumFromThenTo numericEnumFrom :: numericEnumFromThen :: numericEnumFromTo :: numericEnumFromThenTo :: numericEnumFrom = numericEnumFromThen n m = numericEnumFromTo n m = numericEnumFromThenTo n n’ .1 .may overflow instance Enum Double where succ x = x+1 pred x = x1 toEnum = fromIntegral fromEnum = fromInteger .113 The Enum instances for Floats and Doubles are slightly unusual.1 is represented. where = x+1 = x1 = fromIntegral = fromInteger .Not legal Haskell. truncate = numericEnumFrom = numericEnumFromThen = numericEnumFromTo = numericEnumFromThenTo instance Enum Float succ x pred x toEnum fromEnum enumFrom enumFromThen enumFromTo enumFromThenTo . 0. This example may have either 10 or 11 elements.
It is expected that compilers will recognize this and insert error . for illustration only . and its typing forces its first argument .b) deriving (Eq.as an infix operator.b) = (a.(NB: not provided for triples. Bounded) (a. b) > c) = f (fst p) (snd p) .uncurry converts a curried function to a function on pairs.c) deriving (Eq. . It is usually used .y) :: (a.Tuples data data CHAPTER 8. quadruples. y) uncurry uncurry f p :: (a > b > c) > ((a.114 .curry converts an uncurried function to a curried function.b) > a fst (x.undefined" .asTypeOf is a typerestricted version of const.Misc functions .error stops execution and displays an error message error error :: String > a = primError .b) > b = y . asTypeOf :: a > a > a asTypeOf = const .b.component projections for pairs: .Not legal Haskell.) fst :: (a. Ord. curry :: ((a. etc. STANDARD PRELUDE (a. until :: (a > Bool) > (a > a) > a > a until p f x  p x = x  otherwise = until p f (f x) .(which is usually overloaded) to have the same type as the second.b.appears.until p f yields the result of applying f until p holds. Bounded) . Ord.y) = x snd snd (x. b) > c) > a > b > c curry f x y = f (x.c) = (a. undefined undefined :: a = error "Prelude.messages that are more appropriate to the context in which undefined .
zip. notElem. or. tail. minimum. (!!). takeWhile. any. all. unwords. iterate. :: [a] > a = x = error "Prelude. span.Map and append map :: (a > b) > [a] > [b] map f [] = [] map f (x:xs) = f x : map f xs (++) :: [a] > [a] > [a] [] ++ ys = ys (x:xs) ++ ys = x : (xs ++ ys) filter :: (a > Bool) > [a] > [a] filter p [] = [] filter p (x:xs)  p x = x : filter p xs  otherwise = filter p xs concat :: [[a]] > [a] concat xss = foldr (++) [] xss concatMap :: (a > [b]) > [a] > [b] concatMap f = concat . respectively. lines. lookup. rather than the beginning.Standard list functions module PreludeList ( map. length.tail: empty list" head head (x:_) head [] tail tail (_:xs) tail [] . product. scanl. init. replicate. (++). elem. unlines. reverse. concat. foldr1. zipWith. cycle. zip3. filter. sum. of a list. and. splitAt. last and init are the dual functions working from the end of a finite list. null.1. maximum. foldr.1 Prelude PreludeList . break. concatMap. dropWhile. take. head. foldl. PRELUDE PRELUDELIST 115 8. unzip3) where import qualified Char(isSpace) infixl 9 infixr 5 infix 4 !! ++ ‘elem‘. drop. ‘notElem‘ . map f head and tail extract the first element and remaining elements. zipWith3. repeat. scanl1. last. scanr. foldl1. words. which must be nonempty. scanr1.8. unzip.head: empty list" :: [a] > [a] = xs = error "Prelude.
.. scanl is similar to foldl. .. and a list... xn] == (.. . again without the starting element: scanl1 f [x1. x2. .] Note that last (scanl f z xs) == foldl f z xs.last: empty list" [a] > [a] [] x : init xs error "Prelude. (z ‘f‘ x1) ‘f‘ x2. length :: [a] > Int length [] = 0 length (_:l) = 1 + length l .length returns the length of a finite list as an Int...] foldl :: (a > b > a) > a > [b] > a foldl f z [] = z foldl f z (x:xs) = foldl f (f z x) xs foldl1 foldl1 f (x:xs) foldl1 _ [] scanl scanl f q xs :: (a > a > a) > [a] > a = foldl f x xs = error "Prelude. STANDARD PRELUDE [a] > a x last xs error "Prelude.. x2. applied to a binary operator..!!: negative index" [] !! _ = error "Prelude.init: empty list" :: [a] > Bool = True = False . and thus must be applied to nonempty lists. 0origin (!!) :: [a] > Int > a xs !! n  n < 0 = error "Prelude.) ‘f‘ xn foldl1 is a variant that has no starting value argument.List index (subscript) operator. a starting value (typically the leftidentity of the operator). scanl1 is similar.((z ‘f‘ x1) ‘f‘ x2) ‘f‘. ..!!: index too large" (x:_) !! 0 = x (_:xs) !! n = xs !! (n1) foldl.. from left to right: foldl f z [x1.foldl1: empty list" :: (a > b > a) > a > [b] > [a] = q : (case xs of [] > [] x:xs > scanl f (f q x) xs) :: (a > a > a) > [a] > [a] = scanl f x xs = [] scanl1 scanl1 f (x:xs) scanl1 _ [] . but returns a list of successive reduced values from the left: scanl f z [x1.. x1 ‘f‘ x2.116 last last [x] last (_:xs) last [] init init [x] init (x:xs) init [] null null [] null (_:_) :: = = = :: = = = CHAPTER 8. x2.. reduces the list using the binary operator. z ‘f‘ x1..] == [x1.] == [z..
f (f x).8. .foldr. Int > [a] > [a] [] [] x : take (n1) xs take :: take n _  n <= 0 = take _ [] = take n (x:xs) = . or equivalently. returns the prefix of xs of length n. splitAt n xs is equivalent to (take n xs. and scanr1 are the righttoleft duals of the .iterate f x returns an infinite list of repeated applications of f to x: .repeat x is an infinite list.on infinite lists.] iterate :: (a > a) > a > [a] iterate f x = x : iterate f (f x) . cycle cycle [] cycle xs :: [a] > [a] = error "Prelude.replicate n x is a list of length n with x the value of every element replicate :: Int > a > [a] replicate n x = take n (repeat x) . or [] if n > length xs. It is the identity . or xs itself if n > length xs. with x the value of every element.cycle: empty list" = xs’ where xs’ = xs ++ xs’ take n. scanr..iterate f x == [x.cycle ties a finite list into a circular one.foldr1: empty list" scanr :: (a > b > b) > b > [a] > [b] scanr f q0 [] = [q0] scanr f q0 (x:xs) = f x q : qs where qs@(q:_) = scanr f q0 xs scanr1 scanr1 f [] scanr1 f [x] scanr1 f (x:xs) :: = = = (a > a > a) > [a] > [a] [] [x] f x q : qs where qs@(q:_) = scanr1 f xs . foldr1..above functions. applied to a list xs. drop n xs). drop n xs returns the suffix of xs after the first n elements. foldr :: (a > b > b) > b > [a] > b foldr f z [] = z foldr f z (x:xs) = f x (foldr f z xs) foldr1 foldr1 f [x] foldr1 f (x:xs) foldr1 _ [] :: = = = (a > a > a) > [a] > a x f x (foldr1 f xs) error "Prelude. repeat :: a > [a] repeat x = xs where xs = x:xs .1. PRELUDE PRELUDELIST 117 .the infinite repetition of the original list. . f x.
[a]) span p [] = ([].isSpace s of "" > [] s’ > w : words s’’ where (w. drop n xs) takeWhile. s’’) = break Char.zs) = span p xs’ break p = span (not . p) lines breaks a string up into a list of strings at newline characters.[a]) = (take n xs. applied to a predicate p and a list xs. The resulting strings do not contain newlines. Similary. returns the longest prefix (possibly empty) of xs of elements that satisfy p. span p xs is equivalent to (takeWhile p xs. unlines and unwords are the inverse operations. which were delimited by white space. s’) = break (== ’\n’) s in l : case s’ of [] > [] (_:s’’) > lines s’’ :: String > [String] = case dropWhile Char.118 drop :: drop n xs  n <= 0 = drop _ [] = drop n (_:xs) = splitAt splitAt n xs  CHAPTER 8. :: String > [String] = [] = let (l. words breaks a string up into a list of words. STANDARD PRELUDE Int > [a] > [a] xs [] drop (n1) xs :: Int > [a] > ([a]. :: (a > Bool) > [a] > [a] = [] = = x : takeWhile p xs [] takeWhile takeWhile p [] takeWhile p (x:xs)  p x  otherwise dropWhile dropWhile p [] dropWhile p xs@(x:xs’)  p x  otherwise :: (a > Bool) > [a] > [a] = [] = = dropWhile p xs’ xs span. break :: (a > Bool) > [a] > ([a]. unlines joins lines with terminating newlines. dropWhile p xs returns the remaining suffix.[]) span p xs@(x:xs’)  p x = (x:ys.zs)  otherwise = ([]. and unwords joins words with separating spaces. while break p uses the negation of p.isSpace s’ lines lines "" lines s words words s .xs) where (ys. dropWhile p xs).
reverse xs returns the elements of xs in reverse order. sum. or :: [Bool] > Bool and = foldr (&&) True or = foldr () False .b)] > Maybe b lookup key [] = Nothing lookup key ((x..8. .disjunctive dual of and. .True. and.minimum: empty list" foldl1 min xs . elem. .and returns the conjunction of a Boolean list.Applied to a predicate and a list. x ‘elem‘ xs. notElem :: (Eq a) => a > [a] > Bool elem x = any (== x) notElem x = all (/= x) .maximum: empty list" maximum xs = foldl1 max xs minimum [] minimum xs = = error "Prelude. usually written in infix form. minimum :: (Ord a) => [a] > a maximum [] = error "Prelude. the list must be finite. map p all p = and .elem is the list membership predicate. any determines if any element . and of an ordered type. all :: (a > Bool) > [a] > Bool any p = or . for all. reverse :: [a] > [a] reverse = foldl (flip (:)) [] xs must be finite. notElem is the negation. results from a False . map p . maximum.y):xys)  key == x = Just y  otherwise = lookup key xys .of the list satisfies the predicate. product :: (Num a) => [a] > a sum = foldl (+) 0 product = foldl (*) 1 . lookup :: (Eq a) => a > [(a.g.e. False.which must be nonempty. For the result to be .value at a finite index of a finite or infinite list.maximum and minimum return the maximum or minimum value from a list. Similarly. finite. any.lookup key assocs looks up a key in an association list. PRELUDE PRELUDELIST unlines unlines unwords unwords [] unwords ws :: [String] > String = concatMap (++ "\n") :: [String] > String = "" = foldr1 (\w s > w ++ ’ ’:s) ws 119 . or is the .sum and product compute the sum or product of a finite list of numbers.1. however.
zipWith (+) is applied to two lists to produce the list of corresponding sums.b) ˜(as.) :: [a] > [b] > [c] > [(a.b:bs)) ([].cs) > (a:as.) zip zip zip3 zip3  The zipWith family generalises the zip family by zipping with the function given as the first argument.b)] > ([a]. instead of a tupling function.b:bs. excess elements of the longer list are discarded.[]) .[b].[c]) = foldr (\(a.bs.c:cs)) ([].c)] > ([a]. zip3 takes three lists and returns a list of triples.[]) :: [(a.120  CHAPTER 8.[b]) = foldr (\(a. unzip unzip unzip3 unzip3 :: [(a.b..c)] = zipWith3 (. STANDARD PRELUDE zip takes two lists and returns a list of corresponding pairs. If one input list is short.bs) > (a:as.[].c) ˜(as.b)] = zipWith (. For example. zipWith :: (a>b>c) > [a]>[b]>[c] zipWith z (a:as) (b:bs) = z a b : zipWith z as bs zipWith _ _ _ = [] zipWith3 :: (a>b>c>d) > [a]>[b]>[c]>[d] zipWith3 z (a:as) (b:bs) (c:cs) = z a b c : zipWith3 z as bs cs zipWith3 _ _ _ _ = [] .b.unzip transforms a list of pairs into a pair of lists.b. Zips for larger tuples are in the List library :: [a] > [b] > [(a.
u) readl’ s = [([]. readl’ u] .t) (x. isAlpha.’ . reads. shows x . showInt. readList). isAlphaNum. Maybe.hs import Char(isSpace.t) [(x:xs. lexDigits) type type ReadS a ShowS = String > [(a.String)] = String > String where :: Int > ReadS a :: ReadS [a] class Read a readsPrec readList .t) (xs.8. readl’ t] lex s] ++ lex s.s) pr where readl s = [([]. shows. ShowS.t)  ("]". PRELUDE PRELUDETEXT 121 8. showChar. showl xs where showl [] = showChar ’]’ showl (x:xs) = showChar ’.2 Prelude PreludeText module PreludeText ( ReadS. showList). showLitChar.u) (xs. readSigned. readParen.2. read. Either.v)  (".The instances of Read and Show for Bool. shows x . readLitChar.Mimimal complete definition: show or showsPrec showsPrec _ x s = show x ++ s show x showList [] showList (x:xs) = showsPrec 0 x "" = showString "[]" = showChar ’[’ . showString. Ordering . Read(readsPrec.v) class Show a showsPrec show showList where :: Int > a > ShowS :: a > String :: [a] > ShowS <<<<<<<<< lex r. Show(showsPrec. lexLitChar) import Numeric(showSigned. readFloat. showl xs .u)  (x. isDigit.Minimal complete definition: readsPrec readList = readParen False (\r > [pr  ("[".are done via "deriving" clauses in Prelude. readl s]) lex s] ++ reads s.t) [(x:xs. showFloat. readDec. show.t)  ("]". showParen ) where . lex.". reads t.
p .read: no parse" _ > error "Prelude.This lexer is not completely faithful to the Haskell lexical syntax.u) showChar showChar showString showString showParen showParen b p readParen readParen b g r <.t)  ’\\’:t <[dropWhile isSpace s]] lexStrItem s = lexLitChar s .t) <.’\’’:t) <. ("". t)  (ch.u)  ("(".lexLitChar s.lexString t ] lexStrItem (’\\’:’&’:s) = [("\\&".s) (x. <.u) <.lexString s] where lexString (’"’:s) = [("\"". t)  (str."")] = = = lex (dropWhile isSpace s) [(’\’’:ch++"’".optional s.lex t ] .t) <. STANDARD PRELUDE :: (Read a) => String > a = case [x  (x.s)] lexString s = [(ch++str. ch /= "’" ] [(’"’:str.Current limitations: Qualified names are not handled properly Octal and hexidecimal numerics are not recognized as a single token Comments are not treated properly lex lex "" lex (c:s)  isSpace c lex (’\’’:s) lex (’"’:s) :: ReadS String = [("".lex t] of [x] > x [] > error "Prelude.122 reads reads shows shows read read s :: (Read a) => ReadS a = readsPrec 0 :: (Show a) => a > ShowS = showsPrec 0 CHAPTER 8.s)] lexStrItem (’\\’:c:s)  isSpace c = [("\\&".read: ambiguous parse" :: Char > ShowS = (:) :: String > ShowS = (++) :: Bool > ShowS > ShowS = if b then showChar ’(’ . (str. u)  (ch.lex r.t) <. .lexStrItem s. <. showChar ’)’ else p :: Bool > ReadS a > ReadS a = if b then mandatory else optional where optional r = g r ++ mandatory mandatory r = [(x."") <.reads s.t) (")".
t) <.s)] [(c:sym.()[]{}_‘" isSym c = c ‘elem‘ "!@#$%&*+.t) 123  otherwise = [] where isSingle c = c ‘elem‘ ".s)] <..2.u) <.[span isSym s]]  (nam.u)  (c:t) [(e:ds. (e.lexDigits t] ++  (ds.t) lexExp s = [("". c ‘elem‘ "+".lexFracExp s ] .’:c:cs)  isDigit c = [(’.8. (ds.t) <.lexDigits (c:cs).s) <.[span isIdChar s]]  (ds.Converting to Integer avoids .Reading at the Integer type avoids .t) <.lexDigits s] instance Show Int where showsPrec n = showsPrec n . PRELUDE PRELUDETEXT lex (c:s)     isSingle c isSym c isAlpha c isDigit c = = = = [([c].possible difficulty with minInt instance Show Integer showsPrec instance Read Integer readsPrec p instance Show Float showsPrec p instance Read Float readsPrec p instance Show Double showsPrec p instance Read Double readsPrec p where = showSigned showInt where = readSigned readDec where = showFloat where = readSigned readFloat where = showFloat where = readSigned readFloat instance Show () where showsPrec p () = showString "()" .’:ds++e.readsPrec p r] .[span isDigit s]. toInteger .t) [(c:ds++fe.possible difficulty with minInt instance Read Int where readsPrec p r = [(fromInteger i. t)  (i.u)  (ds.t) <.u) <. (fe./<=>?\\ˆ:˜" isIdChar c = isAlphaNum c  c ‘elem‘ "_’"  (sym.t) <.[s].lexExp t] lexFracExp s = lexExp s lexExp (e:s)  e ‘elem‘ "eE" = [(e:c:ds.t) [(c:nam.t) <.bad character lexFracExp (’.
showl cs where showl "" = showChar ’"’ showl (’"’:cs) = showString "\\\"" . showChar ’. showl cs showl (c:cs) = showLitChar c .Other tuples have similar Read and Show instances <<<<< lex r. Read b) => Read (a.’ . reads s.Tuples instance (Show a. (c.v) (")".readl s ]) where readl (’"’:s) = [("".lex r.u) (y. lex v ] ) .s) (x. t) <.w) .s)] readl (’\\’:’&’:s) = readl s readl s = [(c:cs. reads u. showChar ’)’ instance (Read a. shows y .u)  (c . showChar ’\’’ showList cs = showChar ’"’ .readLitChar s]) readList = readParen False (\r > [(l.t) (".t)  ("(". lex t.y) = showChar ’(’ .b) where readsPrec p = readParen False (\r > [((x.lex r. showLitChar c .". showl cs instance Read Char readsPrec p where = readParen False (\r > [(c.readLitChar s. (cs.t)<. shows x .t) <.lex r."\’") <.u) <. Show b) => Show (a.readl t ] instance (Show a) => Show [a] where showsPrec p = showList instance (Read a) => Read [a] where readsPrec p = readList .b) where showsPrec p (x. w)  ("(". (l. (")".t) <.t)  (’\’’:s._) <.124 CHAPTER 8. STANDARD PRELUDE instance Read () where readsPrec p = readParen False (\r > [(().lex s ] ) instance Show Char where showsPrec p ’\’’ = showString "’\\’’" showsPrec p c = showChar ’\’’ .t)  (’"’:s.s) <.y).
putStr.3 Prelude PreludeIO module PreludeIO ( FilePath. PRELUDE PRELUDEIO 125 8. Eq IOError where . interact. appendFile.. putChar. catch. putStrLn.. getChar. :: = :: = :: = IOError > IO a primIOError String > IOError primUserError IO a > (IOError > IO a) > IO a primCatch :: Char > IO () = primPutChar :: String > IO () = mapM_ putChar s putStrLn :: String > IO () putStrLn s = do putStr s putStr "\n" print print x getChar getChar getLine getLine :: Show a => a > IO () = putStrLn (show x) :: IO Char = primGetChar :: IO String = do c <.getLine return (c:s) getContents :: IO String getContents = primGetContents .The internals of this type are system dependent data IOError instance instance ioError ioError userError userError catch catch putChar putChar putStr putStr s Show IOError where .. readLn ) where import PreludeBuiltin type FilePath = String .3.8. getLine. getContents. readIO. print. writeFile.getChar if c == ’\n’ then return "" else do s <.. userError. readFile. ioError. IOError.
getContents putStr (f s) readFile readFile writeFile writeFile :: FilePath > IO String = primReadFile :: FilePath > String > IO () = primWriteFile appendFile :: FilePath > String > IO () appendFile = primAppendFile .t) <. ("".lex t] of [x] > return x [] > ioError (userError "Prelude.readIO: ambiguous parse") readLn :: Read a => IO a readLn = do l <.126 CHAPTER 8.raises an exception instead of an error readIO :: Read a => String > IO a readIO s = case [x  (x. STANDARD PRELUDE interact :: (String > String) > IO () .The hSetBuffering ensures the expected interactive behaviour interact f = do hSetBuffering stdin NoBuffering hSetBuffering stdout NoBuffering s <.readIO: no parse") _ > ioError (userError "Prelude."") <.getLine r <.readIO l return r .reads s.
Chapter 9 Syntax Reference 9. and lambda abstractions extend to the right as far as possible. there are some ambiguities that are to be resolved by making grammatical phrases as long as possible. In the contextfree syntax.1 Notational Conventions These notational conventions are used for presenting syntax: optional zero or more repetitions grouping choice difference—elements generated by except those generated by fibonacci terminal syntax in typewriter font BNFlike syntax is used throughout. Thus. letexpressions. this means that conditionals. an associativity variable varies over . and may have a double index: a letter . A precedencelevel variable ranges from 0 to 9. or for left. proceeding from left to right (in shiftreduce parsing. with 10 substitutions for and 3 for . for example actually stands for 30 productions. right. In the lexical syntax. resolving shift/reduce conﬂicts by shifting). 127 § ¢ 2 ¢ ¡ ( ) ¦ ¤ 7 § § ¢ £¡ 1§ ¢ £¡ ¦ ¡ 2 ©¦ 2 ¤ ¡7 A !§ 7 3¢ ¡ p v £!e ¢ $ 2 &¤ 8 8 8 @¥¥9 £ § ¢ )'% $ " 0(&§# § ¢§ £§ ¡ £¡ ¢ ¢ ¦ £¤ ¡ §¥ § § £¡ §¥ § § £ ¦¤ ¢ ¡ ¨ ¦¤ ¢ ¡ ©§¥ § § £ ¢ £ ¡ ¡ ¢ ¡ 2 ¡ 7 3¢ v ¡§ ¡ 7 3¢ 6 6 4¤ ¦ 2 5 § 3©¦ ¡ ¢ S ¢ . Similarly. . this is the “maximal munch” rule. .or nonassociativity and a precedence level. with productions having the form: There are some families of nonterminals indexed by precedence levels (written as a superscript). the nonterminals . In both the lexical and the contextfree syntax.
§§ § § ¦ £$ § § § © ¢ 6 6 7 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 §§ § t § 6 7 2 ' 4 3 ' ¦ £$ © ¦ ) 4 2 B2 © ¦§ 7 £ ¦ ¨ 3¦ ¢ )A 98 7 64 #"@¦"%5 3¦ ¢ ¦ 1§¤ 0 0 4 2 ¦ § ¨)§ § ¥ ( § ¦£$ ¦ ¥ 0% ¦ § §£%¢ ¤ % ¦ § 5¤ %§ ¤ ¦¤ $§ 0 ¦ $ ¦ 7 7 § © § ¤ ¤ ¦ § £ ¦ ¡ ' ¢ 7 4 '#4 ¢ 2 ¦ ¤§ ¢ 4 ¨32 ¤ ¦ 4 & $ © § ¥ %§ § ¨¦£ ¥ § ¨¦£ § ¥ ¢ & $ © § ¥ %§ § ¨¦£ ¦ ¦ § #¦ § ¢ ¤ ¤ © 2 4 © ¦ 332 ¡ 9. / < = > ? \ ˆ  . [ ] ` { } ¤ ¤© ¤ ¥ § 2 " § ! ¢ §¢ © ¥¢ ¤ ¤ © ¦ 7 ¦ 43¤ 3§ ¢ 32 ¡ © ¢ § ¦ ¨¦¤ © § ¥ £ ¤¢ ¡ ¤¥ § ¦ § ¤ § § 7 3§ ¢ ¤ 7 4¦ ¢ ¡ ¢ 7 . SYNTAX REFERENCE : " ’ 7 ¥ 4 §© § © § § § 2 43© 2¤ ¦ 7 ' 7 3¢ ¡ ¢ 7 § !3¢ ¤ 77 § © ¨¥ '¨ ¡ ¤ ¢ ¥ § ¨¢£¡ ¤ ¨¥ §¢ ¤ § ¥ ¨¦£ § ¢ ¡T ) cRasY`WXrpq7"9 g 24"9 A g hi7¡9 gA " 3¦db`XV GH§¢ C U f f 9 e c a Y W U E ¦ 2 ¡ ! # $ % & * + .2 Lexical Syntax 128 ( ) .˜ any Unicode symbol or punctuation y B 2 4 3 t ¢ h h h h A v f 4 x"$ wg " 5 7 2 ' 4 3 t § ¦ £$ § 7 2 ' 4 3 t © ¢ A B Z any uppercase or titlecase Unicode letter _ : " ’ %¤ ¢ u 8 8 8 @¥¥9 ¦ £$ 2¤ ¢ u ¢ © 2 3© 4 7 ' § £$ 2¤ ¦ ¢u © %¤ ¢ ¢ u ¢7 %¤ S¢RQFP§ 4 32 ¦ © G E C ¦ 4 _ a b z any Unicode lowercase letter 77 !3¢ 4 t § 8 8 8 @¥¥9 ¦ £$ 4 © 77 03¢ ¢ t 4 § £$ ¦ 703¢ 7 4 t © 77 !3¢ §¢© t 4 77 !3¢ § #¥ ¡3 §¢ ¦ ¤ G E QFC © G E S¢RQFC ¢ © G E C 4 ¡ IHFD32 © ¥ © ¢ ¦ § ¦¥ 4 32 ¦ 4 4 2 B2 © 4 2 ¥ ¥2 ¦ 7 ¡ © ¥ © ¦ ¦ ¥ 4 4 ¢ 2 § § ¨)§ § ¥ ( ¦ £$ ' ¨¢ § © ¤ ¥ § ¨¦£ § ¥ ¢ & $ § © § ¥ %¤ § ¨¦£ ¢ ¤£¡ © § ¥ § ¨¦£ § ¤¢ ¡ 1§3¥0 0 4 ¤ 2 ¦ § ¥ ¤ ' #¢ ¢2 ¦ § 0 ¦ ¦¤ $§ §£%¢ ¤7 ¦§ £ ¦ 7 6 6 6 6 7 ¤ 3¢ ¥ § ¡ § 7 3¢ 7 © ¥ ¡ 4 ¢ 4 ¤ ¡&¤ 7 2 ¢ ¡ .{} a carriage return a line feed a vertical tab a form feed a space a horizontal tab any Unicode character deﬁned as whitespace CHAPTER 9. .
¤ ¦ ¦ § ¦ ¦ § ¦ ¦ § ¦ ¦ § ¦ ¦ § ¦ ¦ 2 4 2 4 2 4 2 4 2 4 2 4 § ¦32 ¦ § ¦32 ¦ ¦ 32 § ¦ § ¤ ’ " \ 0o 0x e E +  . . .4§ §§ © § 2 7 ¢ 7 3¢ ¦ ¢ © © ) h ¡ 5)¢ ¡ 5¢ ¢ ¨£¡ © © ) h ¡ 5¢ ¢ ¨£¡ o \& ¢ ¦ ¤ ¡ §¢ ¤ ¡ §¢ 4§ ¨ 7 3¢ § ¦ ¦ ¦32 ¢¡ 4 § 7 ¨ § ¦32 ¡ ¦ ¢ 4 § ¡ 3¢ 4 § ¦ ¦ ¦ 7 ¢ 4 § ¢¡ ¡ ¥ 73 ¢ 4 § 3¢ ¡ ¥ 7 ¢ ¦ ¢ 7 ¢ ¦ ¢ § 2 § 2 7 ¢ 4§ 7 3¢ ¦ 7 3¢ § § S ¢ ¥ § § ¡ ¥ ¢ §§ § § 2 § § § 2 §§ § § § § § ¦ ¦ § 43¦ 2 ¨ © 4 S¤ `¨ © © ¢ %§ ¨ `¨ ¦ 72 3¥ %§ ¨ ¦ ¦ § § ¦ 2 ¨ ¢ ¦ ˜ => ¥ h 9 f £ f 4 f S¥ X¤¢%w5 4 ) " 9¡¦fX¤ f24w5¡ 2 3© ¥ £ f 4 ©7 ' 2 4 © 7 ' : ) 4 f ¡$ 4 ¡ " 9. .. .2.> 0 1 9 any Unicode decimal digit 0 1 7 A F a f variables constructors type variables type constructors type classes modules y @ 7 2 ' 8 8 8 @¥¥9 8¥8¥8 § § § ¦ 8 8 8 @¥¥9 8 8 8 @¥¥9 . 0O ’ \ " \ 0X ’ 129 " x 7 3¢ 4§ ¦ ¢ ¢ ¡ ¥ © § ¨¥ § ¨¥ ¤ ¥ 6 6 6 6 6 6 § © ¡ §¢ #¦ § ¤ § © ¤ ¢ ¡ ¢ 2 ¥ ¢ ¡ ¦ ¦ ¥ 32 § ! ¤ § ¦ § 6 4§ 7 6 3¢ 6 6 6 6 6 6 6 6 6 6 ¦ ¦ ¦ ¢ § 2 73§ ¢ 4 ¢ S ¥ 7 ¢ 4 ¦ © ¦ 32 © 4 © 3¤ ¦ 37 2 § § § ¢ %§ ¦ 32 ¤ ¢ %§ 6 ¦ ¦ © 2 4 %§ %§ ¢ ¤ ¦ ¦ 72 3¥ %§ § ¢¦ 2 § ¦ ¤ ¢ 6 6 6 6 6 6 2 ¥¢ ¤ ¤ © ¡ ¦ 43¦ 2 © 4 S¤ © ¢ ¦ ¦ § ¥¢ ¤ © ¦ ¦ § § ¦ 2 ¢ ¤ ¤ 6 6 6 6 §§ § §§ § § § S ¥ ¢ §§§ § 2 ¦ £$ © ¢ . : :: = \  <. . LEXICAL SYNTAX ’ ’ case class data default deriving do else if import in infix infixl infixr instance let module newtype of then type where _ ) ¥ v ¥ £ f ¦f ¤¢24 f ¡ § § § %¤ 4 §© 2¤ ¦ 77 4 4 § § § %¤ ¢ 7 !3¢ §© §© ¢ 7 ¦ ¢ 7 !3¢ 77 77 !3¢ : : .
in which each element is either: – Zero. (NB: a string literal it is not. ¦ ¦ – If the ﬁrst lexeme of a module is not { or module.7 gives an informal discussion of the layout rule. nor before the . which is the indentation column of the enclosing layout context. or if the end of ﬁle has been reached. this lexeme is preceded by where is the indentation of the lexeme. – A positive integer. then no layout tokens will be inserted until either the enclosing context ends or a new context is pushed. because it is not preceded only by white space. where. SYNTAX REFERENCE 9. with the following additional tokens: – If a let. The speciﬁcation takes the form of a function that performs the translation.130 CHAPTER 9.) A stack of “layout contexts”. do. because it is not the beginning of a complete lexeme. where is the indentation of the next lexeme if there is one. as a consequence of the ﬁrst two rules. the programmer supplied the opening brace.e. The meaning of a Haskell program may depend on its layout. The input to is: A stream of lexemes as speciﬁed by the lexical syntax in the Haskell report. The meaning of this augmented program is now layout insensitive. then it is preceded by is the indentation of the lexeme. So in the fragment f = ("Hello \ \Bill". preceded by may span multiple lines – Section 2. The effect of layout is speciﬁed in this section by describing how to add braces and semicolons to a laidout program. "Jake") There is no inserted before the \Bill. provided that . indicating that the enclosing context is explicit (i.. The effect of layout on its meaning can be completely described by adding braces and semicolons in places determined by the layout. u u – Where the start of a lexeme is preceded only by white space on the same line. or of keyword is not followed by the lexeme {.3 Layout Section 2. This section deﬁnes it more precisely. If the innermost context is 0. where ¦ ¦ ¤ ¥ § §#¥¦£ ¤ ¥ § ¨¦£ § ¥ © ¢ y ¢ 2¤ ¢ u ¢ ¤§ ¦ ¦ ¦ £ ¦ ¦ £ ¦ ¦ 7 ¦ 6 6 6 6 © 7 § @§ ¤ ¡ ¤ § 5¢¦ ¢ © ¥ a b f n r t v \ " ’ & ˆ NUL SOH STX ETX EOT ENQ ACK BEL BS HT LF VT FF CR SO SI DLE DC1 DC2 DC3 DC4 NAK SYN ETB CAN EM SUB ESC FS GS RS US SP DEL [ \ ] ˆ _ \ \ ¢ .6. the token is inserted after the keyword.
where we use “ ” as a stream construction operator. To determine the column number. to avoid visual confusion. For the purposes of the layout rule. . and “ ” for the empty stream. programmers should avoid writing programs in which the meaning of implicit layout depends on the width of nonspace characters. and ¦ ¦ 7 7 . ﬁxed. assume a ﬁxedwidth font with the following conventions: 1§3¥0 0 4 ¤ 2 © The ﬁrst column is designated column 1. width as an ASCII character. the indentation of a line is the indentation of its leftmost lexeme. not 0. Unicode characters in a source program are considered to be of the same. where is the result of lexically analysing a module and adding columnnumber indicators to it as described above. u ¤ ¨ ¥ } ¡ if !£ ¡ ¤ £ ¡ ¡ © § § ¥ © § © ¡ ¥ } ¥ ¡ ¡ if and parseerror © & § © ¥ ¤ § ¡ ¡ ¥ ¨ § © ¥ § § © © © ¥ § § ¡ ¡ ¨ © ¨ ¨ ¥ { ¥ ¡ { £ £ ¡ ¡ ¡ ¡ § © § ¡ ¥ ¥ ¤ § § © © § § ¡ ¡ ¥ ¥ } } } parseerror £ ¡ ¡ ¥ £ § © § ¡ ¥ } £ £ £ ¡ ¡ £ £ ¤ £ ¡ ¡ ¥ § & § ¡ ¥ ¥ ¥ ¦ ! ¨ ¥ § ¡ ¥ ¥ ¥ { { { ¡ if if £ ¡ © © ¦ ¥ ¥ § § © & © § ¡ ¥ © ¥ £ ¥ ¥ ¦ § ¡ § © § ¥ ¥ . The deﬁnition of is as follows.9. delivers a layoutinsensitive translation of . LAYOUT 131 The “indentation” of a lexeme is the column number of the ﬁrst character of that lexeme.3. . } ¡ if if ¥ © ¨ © ¦ ¥ ¢ 2§ ¨ § § ¥ £ ¡ ¨¦¤¢ ¢ © © ¦ ¥ © ¡ ¢ The application ¢2 0 § 2§ ¡ ¦§ ¦¤ $ §£%§ ¤ ¦ § § £ ¥ § © ¥ ¦ © The characters . Tab stops are 8 characters apart. § § ¥ © § © © © ¨© § § ¡ ¡ § § § ¥ ¥ ¡ ¡ ¡ £ £ ¥ ¥ ¥ § ¡ ¥ ¥ ¥ ¥ ¥ ¥ ¦ ¦ ¡ . all start a new line. A tab character causes the insertion of enough spaces to align the current position with the next tab stop. However.
including labelled construction and update (Section 3. A parse error results if an explicit close brace matches an implicit open brace. y = x } in e’ The close brace is inserted due to the parse error rule above. Note 4. and the tokens generated so far by followed by the token “}” represent a valid preﬁx of the Haskell grammar. Note 5. Note 2. The token is replaced by .132 CHAPTER 9. and the compiler should indicate a layout error. any pending closebraces are inserted. The parseerror rule is hard to implement in its full generality. At the end of the input. Note 1 implements the feature that layout processing can be stopped prematurely by a parse error. the deﬁnition of p is indented less than the indentation of the enclosing context. This clause means that all brace pairs are treated as explicit layout contexts. An example is: § § &§ u © u £ ¥ ¦ . so empty braces are inserted. and a nonlayout context is active. It can fail for instance when the end of the input is reached. If none of the rules given above matches. By matching against 0 for the current layout context. SYNTAX REFERENCE ). u f x = let h y = let p z = z in p in h Here. checks that an implicitlyadded closing brace would match an implicit open 4 £ ¦ Note 1.4. For example let x = e. although they could be: for example let }. we ensure that an explicit close brace can only match an explicit open brace. since the close brace is missing. then the algorithm fails. ¤ ¥ Note 6. A nested context must be further indented than the enclosing context ( fails. For example. then parseerror is true. to mimic the situation if the empty braces had been explicit. which is set in this case by the deﬁnition of h. the expression ¦ 4 The test brace. If not. Note 3. y = x in e’ is valid. It is an error at this point to be within a nonlayout context (i.15). This is a difference between this formulation and Haskell 1. The side condition parseerror is to be interpreted as follows: if the tokens generated so far by together with the next token represent an invalid preﬁx of the Haskell grammar. If the ﬁrst token after a where (say) is not indented more than the enclosing layout context. then the block must be empty. because it translates to let { x = e. Some error conditions are not detected by the algorithm. ). because doing so involves ﬁxities.e.
namely (do { a == b }) == c 133 because (==) is nonassociative. .9. LAYOUT do a == b == c has a single unambiguous (albeit probably typeincorrect) parse.3. Programmers are therefore advised to avoid writing code that requires the parser to insert a closing brace in such situations.
The program text is recovered by taking only those lines beginning with “>”. it is an error for a program line to appear adjacent to a nonblank comment line. To capture some cases where one omits an “>” by mistake. and replacing the leading “>” with a space. More precisely: Program code begins on the ﬁrst line following a line that begins \begin{code}. where a line is taken as blank if it consists only of whitespace. the style of comment is indicated by the ﬁle extension. ﬁrst developed by Richard Bird and Philip Wadler for Orwell. Layout and comments apply exactly as described in Chapter 9 in the resulting text.lhs” indicating a literate Haskell ﬁle. SYNTAX REFERENCE 9. with “. Using this style.4 Literate comments The “literate comment” convention. though it may be stylistically desirable. By convention. A line in which “>” is the ﬁrst character is treated as part of the program. For example.134 CHAPTER 9. In this convention. The literate style encourages comments by making them the default. and inspired in turn by Donald Knuth’s “literate programming”. 8 8 ¥¥8 . all other lines are comment. of course).readLine > putStr "n!= " > print (fact (read l)) This is the factorial function. Program code ends just before a subsequent line that begins \end{code} (ignoring string literals. It is not necessary to insert additional blank lines before or after these delimiters. > fact :: Integer > Integer > fact 0 = 1 > fact n = n * fact (n1) An alternative style of literate programming is particularly suitable for use with the LaTeX text processing system. only those parts of the literate program that are entirely enclosed between \begin{code} \end{code} delimiters are treated as program text. all other lines are comment.hs” indicating a usual Haskell ﬁle and “. a simple factorial program would be: This literate program prompts the user for a number and prints the factorial of that number: > main :: IO () > main = do putStr "Enter a number: " > l <. is an alternative style for encoding Haskell source code.
9.[1. . \begin{code} main :: IO () main = print [ (n.. It is not advisable to mix these two styles in the same ﬁle.4.20]] \end{code} \end{document} This style uses the same ﬁle extension..n])  n <. product [1. LITERATE COMMENTS \documentstyle{article} \begin{document} \section{Introduction} 135 This is a trivial program that prints the first 20 factorials.
. . . ) ¨ A§ ¤ 2 4§ 4§ ¡ §¤¤32 4 § ¡§ ¤ 2 8 8¡ ¥¥8 (.) ( (.. SYNTAX REFERENCE .5 ContextFree Syntax 136 module where 2 ¨ ©§ ¤ 5@¤32 ¢ ¡ § 2 4 ¦ ' { { { . . . 4§ 8 8 ¥¥8 ¡ 7 ¥ ¦ ¡ ( . .. . as . A §¤ 8 8 ¥¥8 ¡ ¤ 4 ¦ ¢ 2 4 .. ) ¦ ¨ A§ ¤ !¤32 ¢ S (.) ( module . 8 8 ¥¥8 ¡ ¢ import qualified 2 4 ¨ ¦ ¦ § ¡ ¤ 4 ¢¦ 8 8 ¥¥8 ( . hiding ( . } . .) ( . ¨ §¤ A A 5 4 ¦ ¢ ) 8 8 ¥¥8 . } = ) = where where ) ) ) ¦ A 8 8 ¥¥8 7¥ ¦ 7 ¥ ¦ 6 6 © 2§ 7¥ ¦ ¡ 2 § 7 ¥ ¦ ¡ ¢ %§ %§ 6 6 § 4 ¦ ¢ ¤ 32 ¡ © 4§ 4§ 4§ ¡ 6 ¡ ¡ 6 7 ¦ 6 6 § ¤ ¤32 ¢ ¡ ¡ ¡ ©§ ¤ @¤32 ¢ ¡ 4§ 6 6 6 © 7 ¦ ¡ 4§ ¦ ' 2 $ 7 ¦ 2 4 CHAPTER 9. = => => => => .) ( (. ) ¨¡ 8 8 ¥¥8 A !§ ¤ 2 . 6 6 © ¦ § 7 ¦ ¦ 7 ¡ ¦ 7 ¦ 7 ¦ ¦ A %§ ¡ ¢ %§ 8 8 ¥¥8 ¦ § ¡ ¡ ¨ © § § ©¦ § © %§ ¨ § ¡ § ¦ 2 © ¢ 7 5© ¦ 7 ¨ ¤ ¥ %§ © %§ ¨ § S § 32 © ¢ ¦ 7§ © ¦ ¦ 7§ © ¨ ¦ § § ¤ ¥ 332 £ ¦ %¢§¢ 4 ¥ x¨ ¤ § ¡ § 32 ¢ ¦ V ¨ ¦ #¦ § § ¥ ©¤ § ©332 ¡ 7©¡ %§ 4 § © ¨ ¤ ¦ § S § 32 ¢ ¦ ¦ ¡ 7© ¡ %§ %¢ § 4 § V © A ¡ 2 § ¡ ¥¥8 ©¡ ¡ 2 § 8 8 7 7 ¥ ¦ ¡ 7 ¥ ¦ ¡ ¦ § ¦ ¦§ ¦ ¦ § ¨ ¢ ¢ ¦ ¦§ ¦ ¦ § empty declaration § ¡ ¨ © 4 § ¨ § 2 4 ¡ ¡ ¦ ¦ ¦ ¦ ¦ ¦§ ¦ ¦ § ¨ ¢ ¢ ¦ § ¦ A ¡ ¡ 7 ¦ ¡ 7 ¦ ¡ © 2§ 7 ¥ ¦ ¡ 4 § © 7¥ ¦ ¡ 4 § 7 ¥ ¦ ¡ 2 © ¦ ' ¡ ¦ ¦ 9. . . ¨ A 5 4 ¦ ¢¥¥8 8 8 ¡ ¢ . . ¦ ¦ 2 ¤ © 37 2 ¦ ¤ ¢ 4§ ¡ © %§ 3¥ %§ ¦ 72 ¤ ¢ ¢ ¡ ¡ ¤32 § ¤ { type data newtype class instance default ( .. } } © 2§ .
. %§ © S© ¤ ¢ ¡ ¤ ¡ B%§ ¦ 32 ¢ %§ ¡ ¡ 2 ¨ ¥ § ¦ § ¤ ¡ § S § 32 ¢ ¦ V © ¥ ¦ § 7 ¥ ¦ ¤ ¤ © ¥ £0 ¦ $ 8 8 ¥¥8 ¢ ¡ 7 § 7 ¥ ¦ ¤ ¤ ¢ 8 8 ¥¥8 ¤ © ¥ © ¦ § A 7 ¦ 7 ¥ ¦ © ¥ © ¥ ¤ § ¢ £¡ 7 ¦ $ £0 9. infixl infixr infix ¦ A §¤ ¦ A¢ 2 ¡ 8¥¥8 8 8 8 ¥¥8 © ¨ > function type type application ¨ ¡ %§ %§ ¢ ¨ ¡ %§ ' %§ ¡ ¡ ¤ ¡ %§ § ¢ © ¤ ( [ ( . . . ¦ § ¢ ¤ ¢ %§ 8 8 ¥¥8 ¡ ¤ ¢ %§ ¦ 32 %§ 6 ¡ § %¢ 7 ©¡ 4§ © 6 6 6 6 6 6 6 © © ¦ § ¦ ¦ ¦ § ¢7 ¤ %§ © %§ ¢ ¥ § © 74 4 § © ¥8¥8 8 ¡ ©S© ¢ 7 7©¡ ¢ ¥ ©¡ 4 § © 7 7 ©S© A 5 %§ 8¥¥8 ¡¢ %§ ¤ B%§ ¢ 7¥ 7 © ¡ %§ 8 ¡ ¢ ¡ ¢ ¢ ¤ %§ © ¥ %§ 7 A ©© 8¥¥8 ¢ ¡ ©S© 7¥ 8 ¢ ¥ 7 ¢ ¥ 7 ( . . . } ¦ ¡ 7 ¦ $ ¥ £0 7 ¦ ¦ { .5. . CONTEXTFREE SYNTAX { . . . ] ) . ) tuple type list type parenthesized constructor %§ 8 8 ¥¥8 () [] (>) (. . ) unit type list constructor function constructor tupling constructors ¦ 32 %§ ¡ ¡ %§ %§ %§ ¡ ¤ ( ( ) ) ) ¦ A © S© ¢ ¥ ©¡ 7 7 § S § ¢ 4§ © © ¦ 32 © © ¢ ¥ 7 ¦ 2 § ¡ § ¢ ¦ 32 %§ ¡ %§ ¢ ' %§ ' ¡ %§ 6 ¡ 6 6 6 6 6 6 © %§ § ¢ © S¤ © ¢ 2 ¡ ¢ 2 ¡ ¢ 7 ¥ ¦ ¦ ¥ § ¦ § 7 ¦ 7 6 6 © 7¥ ¦ 7 ¥ ¦ 137 . } empty ¦ A § :: => type signature ﬁxity declaration empty declaration .
! } . ) © S¤ %§ ) and £ ¤ B%§ ¡ ¤ %§ = ( = ¨ © ¥ ¤ ¢ ¡ ¤ ¢ ¡  :: where where ) => %§ ¨ § S § ¢ \ let in if then case of { ¢ ¡ © ¡ v ¡ 2 ¢ S ¥¡ v ¢ S v v v ¡ 7 ¢ S ¤ ¡ S ¢ 7 ¡ ¤ p v ¢ §e ¦ ¡ ¦ 32 ¡ ¡ ¡ ¢ ¡ ¢ ¡ ¤ ¥¡ ¢ ¡  > lambda abstraction let expression conditional case expression ¦ else } ¢ ¡ © @§ ¢ ¡ 7 ¢ 3¢ S ¡ ¡ ¢ S 6 6 6 6 6 v ¤ ¡ ¢ ¡ ¡ v v ¡ ¡ ¡ ¤ ¢ ¡ ¢ ¡ ¢ ¡ ¡ ¢ ¡ ¡ ¡ ¡ ¡ ¢ ¡ 7 7 ¢ ¡ ¢ ¡ ¢ ¡ 6 6 ¦ ¦ ¦ 6 6 6 © ¥ ¤ ¦ © ¥ ¤ © ¥ 7 ¦ $ 0 distinct 6 § ¦ § © 6 6 6 6 6 6 #¦ § § © © ¢ 7¥ ¤ ¦ £ ¦ 7 ¥ ¦ ¦ 7 ¤ ¤32 § © ¦ ¦ © © ¤ § ¦ ¤ § ¦ 2 © 2 . . CHAPTER 9. { :: } :: ! deriving ( . ¡ ¡ v v ¢ S ¡ ¡ ¡ v ¢ ¡ ¡ ¡ v A!¡ § 8 8 ¥¥8 7 ¡ § ¢ ¡ ¢ ¡ ¢ ¤ £5¢ 2 ¡ £v §¢ ¡ p v §e ¢ ¦ ¢ ¡ 2 ¢ ¡ s ¡ p v §e ¢© ¨ ¡ expression type signature ¡ ¡ V ¤ ¡ ¦ ¡ ¦ © ¥ ¨© ¨ 7 © ¥ 7 ¥ ¦ ¡ 9§ § ¢ §¢ ¤ £5¢ 2 ¡ ¢ ¡ § v ¢£¡ p v ¢ §e ¡ § ¡ v © ¢ £¡ p v ¢ §e § 2 ¡ v ¢£¡ p v ¢ 0e $ § ¡ ¢ ¡ £5¢ © ¥ £0 ¦ $ ¤ ¡7 v § ¢ 2¢ &¤ § £¡ ¡ ¢ v £ 7¡ ¢ ¤ ¡ v§ ¢ ¢ ¤ £ ¡ ¢ § ¢ ¡ £5¢ ¢ ¢ ¢ ¤ ¢ ¦ § ¢ £ ¤ %§ ¡ ¤ %§ ¢ ¤ ¢ %§ ¢ ¤ %§ ¥¥8 ¡ ¤ %§ 8 8 ¤ B%§ ¢ ¥¥8 ¡ ¤ %§ ¦ 2 ¢ %§ 8 8 ¢ ¢ %§ ¦ 32 © ¦ § ¢ ¥ ¦ 7 ¦ ¦ § 2©¦ 2 ¡ ¦32 ¦ arity inﬁx 138   ¦ § £ ¢ ¢ A 8 8 ¥¥8 ¦ ¦ 3 %§ 7 7 %§ 2 ¦ ©32 ¡ ¢ ¡ ¡ ¡ ' %§ ¨ 8 8 ¥¥8 A¢ § © ¦ §¤ ¤32 ¡ 8 8 ¥¥¡8 © ¤ ¦ 3¢ 2 ¢ %§ ¦ 32 ¡ ¢ 32 ¦ %§ ¨ ¡ 32¡ ¦ ' ¢ ¡ ¤ ¤32 § © ¦ ! ! 7¥ ¦ ¦ 7 %§ ¡ ¢ ¢ %§ ¡ { ! . SYNTAX REFERENCE ) ¦ A© §S© 8 8 ¥¥8 ¡ © ¤S© © S© 7 ¥ %§ ¢ 7¥ 3 ¦ ¡ %§ ¢ ¢ 7¥ ¦ ¡ %§ ¡ %§ ¤ ¡ ( ( [ ( ) distinct distinct © S¤ ¢ %§ . ] > .
. ) ] ¢ £ . ] ¦ ) ) )  ( ) right section labeled construction labeled update { ¦ § . ¨ © ¦ ¨5© 7 7 ¥ ¦ A§ > where where .5. . CONTEXTFREE SYNTAX do { } do expression function application variable general constructor ¤ ¢ ¡ © @§ ¢ S ¢ 4§ © ¨ ¡ ¢ S¢0 139 ¡ ¢ S¢0 ( ( [ [ [ ( ( ( ) . . . ¡ § § § ¦ 4 ¢ © %§ ¡ 4 ¥ © ¦ § ¢ £¡ ¦ ¡ § 3 § § ¢ ¦¤ 5 § 7 3¢ %§ ¡ 4 ¦ 7 3¢ £¡ ¦ ¢ ¢ £¡ ¢ ¡ § ¡ ¥¥8 ¢ £¡ ¡§ 8 8 7 3¢ © A ¦§ ¦ ' ¡ 0 ¡ ¦§ 0 8 8 ¥¥8 ) A 9 g © ¡ ¨ ¢ ¦ A ¦ § 0 8¥¥8 ' ¡ ¦ § 0 ¦¡ 2 ¢ 8 ¦ ¦ ' ' ¢ S ¤ ) 2 v ¡ p v ¢ ¡e ¡ ¢ S ) 2 ¡ v ¡ p v ¢ $0e ¡ 2 v S ¢ p v ¢ 5e ¡ A ¡ ¡ 7 2 ¢ ¡ v ¡ p v £!e ¡ ¢ $ A ¥8¥8 $ ¡ $ ¢ ¡ 8 7 3¢ ¨ ¥ ¢¡ ¢ ¡¢ ¨ £ 7 ¡ ¢ ¡ ¡ ¡ ¢ S ¢ 8¡ ¥¥8 ¡ ¡ ¡ 8 ¡¡ ¡¢ ¢S ¡ ¡ 8 ¥8¥8 ¡¡ ¡ ¡ ¢ ¡ § § ¤ 7 3¢ ¦ 2 7 9.  parenthesized expression tuple list arithmetic sequence list comprehension left section left section right section ¤ ¥ £ ¢ . . } ¦ { . ] . <let . = ¢ ¡ + successor pattern ¤ ¥ § ¦ § ¤ ¢ 6 § ¢ £¡ ¤ ¢ 6 ¦ ¦§ ' 0 6 6 6 § § © @§ © © 4§ 4§ ¢ £¡ ¦ ¦ 6 § © @§ ¦§ 6 6 7 3¢ 7 3¢ ¦ ¡ ¢ ¡ § ¢ £¡ 7 3¢ $ 6 ¡ 6 ¡ ¢ S ¢ ¢ ¡ 0 . ¢ ¡ ¨ § .. } ¦ <let generator local declaration guard ¢ ¡ 7 . > . . . ¦ ¨ ¡ ¢ S 7 ¦ § ¢ ¡ ¡ ¢¡ £ ¡ ¢ A § 8 8 !§ 4 ¤© ¥¥8 ¡ § ¡ 4 § © .
. . . . ¤ ¢ £¡ ¢ § £¡ ¢ . ) ] ¢ § 8¥¥8 8 8 8 ¥¥8 = § () [] (. 4 © ¦ 3332 2 ¦ ©32 2 ¤ ¡ ©¦ 2 ¡ &¤¢ 2 2 ¦ ¡ 4 ©¡ ¢ § 32 3¦ 2 ¦ ¦ 4 © ¦ § 32 33 2 ¦ 4 S¤ © § ¤ ¦ ¢ 4 © 3¤¢ § ¤ ¦ 4 32 ¢ § ¦ 2 ¢ © ¦ ¦ ¦ 4 © ¦ 3332 § 3 2 ¦ 43¤ § ¤ © 4 © 3¢S¤ ¦ § ¤¢ ¦ ¢ ¢ ( ( ( ( ` ` ` ` ¢ £¡ ¦ § ¢ ¦ ¦ 32 ¢ ¢ ¢ £¡ ¡ 2©¦32 ¡ § ¦ 2 8 ¥8¥8 ¡ § ¢ §¢ ¡ ¢£¡§¢ § ¢ ¡ £§¢ ¡ v§ v§ ¤ v 2 ©¦32 § ¢ ¡ ¢£¡ p ¢ § §e 2 ¡ !¡ ¤¥ ¡ § ¦ v § £¡ ¢ § 2 ©¦32 s¢ ¡ v § § ¡ v © ¢ £¡ p v ¢ §e ¡ ¢ ¡ v £ 7¡ ¤ ¢ § v £¡ ¢ § v ¢£ 7¡ ¨ ¡ v§ § v ¢£¡ p v ¢ §e ¦ ¢ £¡ ¤ § 140  CHAPTER 9. SYNTAX REFERENCE negative literal arity as pattern arity labeled pattern £¡ ¢ ¢ £¡ ¢ ¡ £§¢ ¨§ ¦ 32 { . } § 0 8 8 ¥¥8 ¡§ 0 ¤ § § 7 3¢ ¦ 2 7 ¦ 2 ¤ y _ ( ( [ ˜ wildcard parenthesized pattern tuple pattern list pattern irrefutable pattern ) . ) ) variable qualiﬁed variable constructor qualiﬁed constructor variable operator qualiﬁed variable operator constructor operator qualiﬁed constructor operator operator qualiﬁed operator ) ) ) ` ` ` ` 6 6 6 6 6 6 6 6 6 6 6 6 ¦ 2 ¤ ¢ § ¢£§¢ ¡ ¡§ ¢£¡ ¡§ ¢£¡ ¢ £¡ § : 4 32 © ¦ 2 ¡ 2 2 ¦ ©32 ¡ ¡ ©¦ 2 2 ¡ &¤ 2 ¡ 2 ¤¢ ¡ ¦32 ¢ ¦ 2 ¤ ¤¢ ¢ ¦ 32 6 § ¢ £¡ 0 ¢ 6 § ¢ ¡ £§¢ 6 6 6 6 6 § ¢ ¤ ¤ ¡ £¡ § v ¢£¡ § ¢£ 7¡ ¢ £ 7¡ v § v § ¢ £¡ .
Chapter 10
Speciﬁcation of Derived Instances
A derived instance is an instance declaration that is generated automatically in conjunction with a data or newtype declaration. The body of a derived instance declaration is derived syntactically from the deﬁnition of the associated type. Derived instances are possible only for classes known to the compiler: those deﬁned in either the Prelude or a standard library. In this chapter, we describe the derivation of classes deﬁned by the Prelude.
If
is an algebraic datatype declared by:
3. If is Bounded, the type must be either an enumeration (all constructors must be nullary) or have only one constructor.
5. There must be no explicit instance declaration elsewhere in the program that makes an instance of . For the purposes of derived instances, a newtype declaration is treated as a data declaration with a single constructor. If the deriving form is present, an instance declaration is automatically generated for over each class . If the derived instance declaration is impossible for any of the
v ¦
$
8 8 ¥¥8 ¡
$
$
4. If
is Enum, the type must be an enumeration.
141
v §
v §
1
¢
1 ©¢
2. There is a context
such that
8 8 ¥¥8 ¡
1.
is one of Eq, Ord, Enum, Bounded, Show, or Read. holds for each of the constituent types .
4
(where and the parentheses may be omitted if possible for a class if these conditions hold:
) then a derived instance declaration is
7
8 8 ¥¥8
¡
deriving (
A § ¥¥8 ¡ !§ A A 8 8
)
¡ ¡ ¢¢¡
¡§
8 8 ¥¥8 ¡ ¡ § ¡
$
8 8 ¥¥8 ¡
$
¢
data
=>
=
 ,
 ,
£
¢
¦ §
4
$
142
v
CHAPTER 10. SPECIFICATION OF DERIVED INSTANCES
then a static error results. If no derived instances are required, the deriving form may be omitted or the form deriving () may be used. Each derived instance declaration will have the form:
The context is the smallest context satisfying point (2) above. For mutually recusive data types, the compiler may need to perform a ﬁxpoint calculation to compute it. The remaining details of the derived instances for each of the derivable Prelude classes are now given. Free variables and constructors used in these translations always refer to entities deﬁned by the Prelude.
10.1 Derived instances of Eq and Ord
The class methods automatically introduced by derived instances of Eq and Ord are (==), (/=), compare, (<), (<=), (>), (>=), max, and min. The latter seven operators are deﬁned so as to compare their arguments lexicographically with respect to the constructor set given, with earlier constructors in the datatype declaration counting as smaller than later ones. For example, for the Bool datatype, we have that (True > False) == True. Derived comparisons always traverse constructors from left to right. These examples illustrate this property:
(1,undefined) == (2,undefined) (undefined,1) == (undefined,2)
False
All derived operations of class Eq and Ord are strict in both arguments. For example, False <= is , even though False is the ﬁrst constructor of the Bool type.
10.2 Derived instances of Enum
Derived instance declarations for the class Enum are only possible for enumerations (data types with only nullary constructors). The nullary constructors are assumed to be numbered lefttoright with the indices 0 through . The succ and pred operators give the successor and predecessor respectively of a value, under this numbering scheme. It is an error to apply succ to the maximum element, or pred to the minimum element.
£
¥
v
where is derived automatically depending on described in the remainder of this section).
and the data type declaration for
$
8 8 ¥¥8 ¡
$
v d
1 ©¢
¢
instance (
¦
,
) =>
where {
¦
1
¢
} (as will be
10.3. DERIVED INSTANCES OF BOUNDED
143
The toEnum and fromEnum operators map enumerated values to and from the Int type; toEnum raises a runtime error if the Int argument is not the index of one of the constructors. The deﬁnitions of the remaining methods are
enumFrom x enumFromThen x y = enumFromTo x lastCon = enumFromThenTo x y bound where bound  fromEnum y >= fromEnum x =  otherwise = enumFromTo x y = map toEnum [fromEnum x .. fromEnum enumFromThenTo x y z = map toEnum [fromEnum x, fromEnum y
lastCon firstCon y] .. fromEnum z]
where firstCon and lastCon are respectively the ﬁrst and last constructors listed in the data declaration. For example, given the datatype: data we would have: [Orange ..] fromEnum Yellow == == [Orange, Yellow, Green] 2 Color = Red  Orange  Yellow  Green deriving (Enum)
10.3 Derived instances of Bounded
The Bounded class introduces the class methods minBound and maxBound, which deﬁne the minimal and maximal elements of the type. For an enumeration, the ﬁrst and last constructors listed in the data declaration are the bounds. For a type with a single constructor, the constructor is applied to the bounds for the constituent types. For example, the following datatype: data Pair a b = Pair a b deriving Bounded
would generate the following Bounded instance: instance (Bounded a,Bounded b) => Bounded (Pair a b) where minBound = Pair minBound minBound maxBound = Pair maxBound maxBound
10.4 Derived instances of Read and Show
The class methods automatically introduced by derived instances of Read and Show are showsPrec, readsPrec, showList, and readList. They are used to coerce values into strings and parse strings into values.
144
CHAPTER 10. SPECIFICATION OF DERIVED INSTANCES
The function showsPrec d x r accepts a precedence level d (a number from 0 to 11), a value x, and a string r. It returns a string representing x concatenated to r. showsPrec satisﬁes the law: showsPrec d x r ++ s == showsPrec d x (r ++ s) The representation will be enclosed in parentheses if the precedence of the toplevel constructor in x is less than d. Thus, if d is 0 then the result is never surrounded in parentheses; if d is 11 it is always surrounded in parentheses, unless it is an atomic expression (recall that function application has precedence 10). The extra parameter r is essential if treelike structures are to be printed in linear time rather than time quadratic in the size of the tree. The function readsPrec d s accepts a precedence level d (a number from 0 to 10) and a string s, and attempts to parse a value from the front of the string, returning a list of (parsed value, remaining string) pairs. If there is no successful parse, the returned list is empty. Parsing of an unparenthesised inﬁx operator application succeeds only if the precedence of the operator is greater than or equal to d. It should be the case that (x,"") is an element of (readsPrec d (showsPrec d x "")) That is, readsPrec should be able to parse the string produced by showsPrec, and should deliver the value that showsPrec started with. showList and readList allow lists of objects to be represented using nonstandard denotations. This is especially useful for strings (lists of Char). readsPrec will parse any valid representation of the standard types apart from strings, for which only quoted strings are accepted, and other lists, for which only the bracketed form [. . . ] is accepted. See Chapter 8 for full details. The result of show is a syntactically correct Haskell expression containing only constants, given the ﬁxity declarations in force at the point where the type is declared. It contains only the constructor names deﬁned in the data type, parentheses, and spaces. When labelled constructor ﬁelds are used, braces, commas, ﬁeld names, and equal signs are also used. Parentheses are only added where needed, ignoring associativity. No line breaks are added. The result of show is readable by read if all component types are readable. (This is true for all instances deﬁned in the Prelude but may not be true for userdeﬁned instances.) Derived instances of Read make the following assumptions, which derived instances of Show obey: If the constructor is deﬁned to be an inﬁx operator, then the derived Read instance will parse only inﬁx applications of the constructor (not the preﬁx form).
Associativity is not used to reduce the occurrence of parentheses, although precedence may be. For example, given
10.5. AN EXAMPLE
infixr 4 :$ data T = Int :$ T then: – show (1 :$ 2 :$ NT) produces the string "1 :$ (2 :$ NT)". – read "1 :$ (2 :$ NT)" succeeds, with the obvious result. – read "1 :$ 2 :$ NT" fails.
145

NT
If the constructor is deﬁned using record syntax, the derived Read will parse only the recordsyntax form, and furthermore, the ﬁelds must be given in the same order as the original declaration.
The derived Read instance allows arbitrary Haskell whitespace between tokens of the input string. Extra parentheses are also allowed.
The derived Read and Show instances may be unsuitable for some uses. Some problems include: Circular structures cannot be printed or read by these instances. The printer loses shared substructure; the printed representation of an object may be much larger than necessary. The parsing techniques used by the reader are very inefﬁcient; reading a large structure may be quite slow. There is no user control over the printing of types deﬁned in the Prelude. For example, there is no way to change the formatting of ﬂoating point numbers.
10.5 An Example
As a complete example, consider a tree datatype: data Tree a = Leaf a  Tree a :ˆ: Tree a deriving (Eq, Ord, Read, Show) Automatic derivation of instance declarations for Bounded and Enum are not possible, as Tree is not an enumeration or singleconstructor datatype. The complete instance declarations for Tree are shown in Figure 10.1, Note the implicit use of default class method deﬁnitions—for example, only <= is deﬁned for Ord, with the other class methods (<, >, >=, max, and min) being deﬁned by the defaults given in the class declaration shown in Figure 6.1 (page 83).
readsPrec (up_prec+1) r.s) <.t) <.t) <.Application has precedence one more than .s) <.146 CHAPTER 10.readsPrec (app_prec+1) s]) r up_prec = 5 app_prec = 10 .1: Example of Derived Instances .the most tightlybinding operator Figure 10.Note: rightassociativity instance (Read a) => Read (Tree a) where readsPrec d r = readParen (d > up_prec) (\r > [(u:ˆ:v. v of :ˆ: ignored ++ readParen (d > app_prec) (\r > [(Leaf m. (m.lex s.lex r. .t)  ("Leaf".Precedence of :ˆ: . (":ˆ:".readsPrec (up_prec+1) t]) r > up_prec) showStr u . (v. SPECIFICATION OF DERIVED INSTANCES infixr 5 :ˆ: data Tree a = Leaf a  Tree a :ˆ: Tree a instance (Eq a) => Eq (Tree a) where Leaf m == Leaf n = m==n u:ˆ:v == x:ˆ:y = u==x && v==y _ == _ = False instance (Ord a) => Ord (Tree a) where Leaf m <= Leaf n = m<=n Leaf m <= x:ˆ:y = True u:ˆ:v <= Leaf n = False u:ˆ:v <= x:ˆ:y = u<x  u==x && v<=y instance (Show a) => Show (Tree a) where showsPrec d (Leaf m) = showParen (d > app_prec) showStr where showStr = showString "Leaf " .w) <.w)  (u. showsPrec (app_prec+1) m showsPrec d (u :ˆ: v) = showParen (d where showStr = showsPrec (up_prec+1) showString " :ˆ: " showsPrec (up_prec+1) .
but the pragma should be ignored if an implementation is not prepared to handle it. except that the enclosing syntax is {# #}.1 Inlining ¢ ¤ © © The INLINE pragma instructs the compiler to inline the speciﬁed variables at their use sites. 11. but which do not form part of the Haskell language proper and do not change a program’s semantics. #} ¢ ¡ © S¤ ¡ {# INLINE {# NOINLINE ¢ ¡ %§ ¥ §¥ © ¤ ¢ 6 6 6 6 7¥ ¦ 7 ¥ ¦ ¡ 7 ¥ ¦ #} #} © . in 147 8 8 ¥¥8 ¡ {# SPECIALIZE . For example.2 Specialization © Specialization is used to avoid inefﬁciencies involved in dispatching overloaded functions. This may be prevented by the NOINLINE pragma. pragmas appear as comments. Compilers will often automatically inline simple expressions. which are used to give additional instructions or hints to the compiler.Chapter 11 Compiler Pragmas Some compiler implementations support compiler pragmas. An implementation is not required to respect any pragma. Lexically. . 11. This chapter summarizes this existing practice.
148 CHAPTER 11. COMPILER PRAGMAS factorial :: Num a => a > a factorial 0 = 0 factorial n = n * factorial (n1) {# SPECIALIZE factorial :: Int > Int. factorial :: Integer > Integer #} calls to factorial in which the compiler can detect that the parameter is either Int or Integer will use specialized versions of factorial which do not involve overloaded numeric operations. .
Part II The Haskell 98 Libraries 149 .
.
Ord (Ratio a) where . For example.. approxRational ) where infixl 7 % data (Integral a) => type Rational = (%) :: numerator. a) => Read (Ratio a) where .. Num (Ratio a) where .. the instance for Ratio simply “lifts” the corresponding operations over . Enum (Ratio a) where . RealFrac (Ratio a) where . the results may be unpredictable. Num.. If is a bounded type. there is a type Ratio of rational pairs with components of type .. denominator :: approxRational :: instance (Integral a) => instance (Integral a) => instance (Integral a) => instance (Integral a) => instance (Integral a) => instance (Integral a) => instance (Integral a) => instance (Read a.. The functions numerator and denominator extract the components of a ratio..Integral instance (Integral a) => Ratio a = ... Read. Ord. Rational. The operator (%) forms the ratio of two integral numbers. Ratio is an instance of classes Eq.Chapter 12 Rational Numbers module Ratio ( Ratio....... Real. Fractional (Ratio a) where . these are in reduced form with a positive denominator.. Real (Ratio a) where . The type name Rational is a synonym for Ratio Integer.. for example Ratio Int may give rise to integer overﬂow even for rational numbers of small absolute size. and Show. reducing the fraction to terms with no common factor and such that the denominator is positive.. Ratio is an abstract type. Enum. numerator. 151 ¡ ¡ ¡ ¡ ¡ ¡ . In each case.. denominator. For each Integral type . Show (Ratio a) where . Ratio Integer (Integral a) => a > a > Ratio a (Integral a) => Ratio a > a (RealFrac a) => a > a > Rational Eq (Ratio a) where . (%). Fractional.. RealFrac. 12 % 8 is reduced to 3/2 and 12 % (8) is reduced to (3)/2.
returns the simplest rational number within the open interval x epsilon x epsilon . A rational number in reduced form is said to be simpler than another if and . 1 ¦ ¦ 1 ¦ ¦ 1 1 ¦ ¦ ¦ ¡¦ . applied to two real fractional numbers x and epsilon. RATIONAL NUMBERS The approxRational function. Note that it can be proved that any real interval contains a unique simplest rational.152 CHAPTER 12.
It normalises a ratio by dividing both numerator and denominator by their greatest common divisor. numerator. denominator.% : zero denominator" (x ‘quot‘ d) :% (y ‘quot‘ d) where d = gcd x y reduce (x * signum y) (abs y) x y => Ord (Ratio a) where = x * y’ <= x’ * y = x * y’ < x’ * y => = = = = = = Num (Ratio a) where reduce (x*y’ + x’*y) (y*y’) reduce (x * x’) (y * y’) (x) :% y abs x :% y signum x :% 1 fromInteger x :% 1 => Real (Ratio a) where = toInteger x :% toInteger y => = = = Fractional (Ratio a) where (x*y’) % (y*x’) y % x fromInteger x :% fromInteger y . LIBRARY RATIO 153 12.1 Library Ratio . (%). denominator approxRational  :: (Integral a) => a > a > Ratio a :: (Integral a) => Ratio a > a :: (RealFrac a) => a > a > Rational "reduce" is a subsidiary function used only in this module.12.. Rational.Standard functions on rational numbers module Ratio ( Ratio.g.1. 12 ‘reduce‘ 8 == 12 ‘reduce‘ (8) == = = = = = 3 :% 2 3 :% (2) reduce _ 0 reduce x y x % y numerator (x :% _) denominator (_ :% y) instance (Integral a) (x:%y) <= (x’:%y’) (x:%y) < (x’:%y’) instance (Integral a) (x:%y) + (x’:%y’) (x:%y) * (x’:%y’) negate (x:%y) abs (x:%y) signum (x:%y) fromInteger x instance (Integral a) toRational (x:%y) instance (Integral a) (x:%y) / (x’:%y’) recip (x:%y) fromRational (x:%y) error "Ratio. approxRational ) where infixl 7 % ratPrec = 7 :: Int data type (Integral a) Rational => Ratio a = !a :% !a = Ratio Integer deriving (Eq) (%) numerator. E.
simplest’ (n’) d’ (n) d  otherwise = 0 :% 1 where xr@(n:%d) = toRational x (n’:%d’) = toRational y simplest’ n    d n’ d’ r == 0 q /= q’ otherwise .readsPrec (ratPrec+1) t ]) instance (Integral a) showsPrec p (x:%y) => Show (Ratio a) where = showParen (p > ratPrec) (showsPrec (ratPrec+1) x .lex s.r) = quotRem x y instance (Integral a) succ x = pred x = toEnum = fromEnum = enumFrom = enumFromThen = enumFromTo = enumFromThenTo = => Enum (Ratio a) where x+1 x1 fromIntegral fromInteger . showsPrec (ratPrec+1) y) approxRational x eps = simplest (xeps) (x+eps) where simplest x y  y < x = simplest y x  x == y = xr  x > 0 = simplest’ n d n’ d’  y < 0 = .154 CHAPTER 12. ("%". RATIONAL NUMBERS instance (Integral a) => RealFrac (Ratio a) where properFraction (x:%y) = (fromIntegral q. (y.r’) = quotRem n’ d’ (n’’:%d’’) = simplest’ d’ r’ d r .r) = quotRem n d (q’.hs but not exported from it! instance (Read a.u)  (x. r:%y) where (q. Integral a) => Read (Ratio a) where readsPrec p = readParen (p > ratPrec) (\r > [(x%y. truncate numericEnumFrom numericEnumFromThen numericEnumFromTo numericEnumFromThenTo May overflow These numericEnumXXX functions are as defined in Prelude. showString " % " .s) <.u) <.t) <.readsPrec (ratPrec+1) r.assumes 0 < n%d < n’%d’ = q :% 1 = (q+1) :% 1 = (q*n’’+d’’) :% n’’ where (q.
in the range . conjugate.Chapter 13 Complex Numbers module Complex ( Complex((:+))... phase ) where infix data 6 :+ => Complex a = !a :+ !a :: :: :: :: :: :: a) a) a) a) a) a) => => => => => => (RealFloat (RealFloat (RealFloat (RealFloat (RealFloat (RealFloat Eq Read Show Num Fractional Floating a) a) a) a) a) a) => => => => => => Complex a > a Complex a > Complex a a > a > Complex a a > Complex a Complex a > (a. ... The function polar takes a complex number and returns a (magnitude. if the magnitude is zero. This constructor is strict: if either the real part or the imaginary part of the number is . magnitude. cis is a complex value with magnitude and phase (modulo ). 155 § ¨ § ¡¤ § .. and the phase.. polar. phase) pair in canonical form: The magnitude is nonnegative. imagPart. then so is the phase... realPart. imagPart conjugate mkPolar cis polar magnitude.a) Complex a > a a) a) a) a) a) a) where where where where where where . .. mkPolar. . The function cis produces a complex number from an angle .. the entire number is . The constructor (:+) forms a complex number from its real and imaginary rectangular components. . phase instance instance instance instance instance instance (RealFloat (RealFloat (RealFloat (RealFloat (RealFloat (RealFloat (Complex (Complex (Complex (Complex (Complex (Complex Complex numbers are an algebraic type. (RealFloat a) realPart.. A complex number may also be formed from polar components of magnitude and phase by the function mkPolar. cis. Put another way.. .
phase z) magnitude :: (RealFloat a) => Complex a > a magnitude (x:+y) = scaleFloat k (sqrt ((scaleFloat mk x)ˆ2 + (scaleFloat mk y)ˆ2)) where k = max (exponent x) (exponent y) mk = . The function conjugate computes the conjugate of a complex number in the usual way. The magnitude and sign of a complex number are deﬁned as follows: abs z signum 0 signum z@(x:+y) = = = magnitude z :+ 0 0 x/r :+ y/r where r = magnitude z That is.1 Library Complex module Complex(Complex((:+)). imagPart :: (RealFloat a) => Complex a > a realPart (x:+y) = x imagPart (x:+y) = y conjugate :: (RealFloat a) => Complex a > Complex a conjugate (x:+y) = x :+ (y) mkPolar mkPolar r theta cis cis theta polar polar z :: (RealFloat a) => a > a > Complex a = r * cos theta :+ r * sin theta :: (RealFloat a) => a > Complex a = cos theta :+ sin theta :: (RealFloat a) => Complex a > (a.k phase :: (RealFloat a) => Complex a > a phase (0 :+ 0) = 0 phase (x :+ y) = atan2 y x . cis. magnitude.Read. but unit magnitude. mkPolar. realPart.Show) (RealFloat a) realPart.156 CHAPTER 13. COMPLEX NUMBERS The functions realPart and imagPart extract the rectangular components of a complex number and the functions magnitude and phase extract the polar components of a complex number. imagPart. phase) where infix data 6 :+ => Complex a = !a :+ !a deriving (Eq. whereas signum has the phase of . abs is a number with the magnitude of . but oriented in the positive real direction. 13. polar. conjugate.a) = (magnitude z.
13.max (exponent x’) (exponent y’) d = x’*x’’ + y’*y’’ fromRational a = fromRational a :+ 0 . LIBRARY COMPLEX instance (RealFloat a) (x:+y) + (x’:+y’) (x:+y) .(x’:+y’) (x:+y) * (x’:+y’) negate (x:+y) abs z signum 0 signum z@(x:+y) fromInteger n => = = = = = = = = Num (Complex a) where (x+x’) :+ (y+y’) (xx’) :+ (yy’) (x*x’y*y’) :+ (x*y’+y*x’) negate x :+ negate y magnitude z :+ 0 0 x/r :+ y/r where r = magnitude z fromInteger n :+ 0 157 instance (RealFloat a) => Fractional (Complex a) where (x:+y) / (x’:+y’) = (x*x’’+y*y’’) / d :+ (y*x’’x*y’’) / d where x’’ = scaleFloat k x’ y’’ = scaleFloat k y’ k = .1.
COMPLEX NUMBERS instance (RealFloat a) => Floating (Complex a) where pi = pi :+ 0 exp (x:+y) = expx * cos y :+ expx * sin y where expx = exp x log z = log (magnitude z) :+ phase z sqrt 0 sqrt z@(x:+y) = = 0 u :+ (if y < 0 then v else v) where (u.z*z)) y’’:+(x’’) where (x’’:+y’’) = log (z + ((y’):+x’)) (x’:+y’) = sqrt (1 .z*z) y’:+(x’) where (x’:+y’) = log (((1y):+x) / sqrt (1+z*z)) log (z + sqrt (1+z*z)) log (z + (z+1) * sqrt ((z1)/(z+1))) log ((1+z) / sqrt (1z*z)) sin (x:+y) cos (x:+y) tan (x:+y) = = = sinh (x:+y) cosh (x:+y) tanh (x:+y) = = = asin z@(x:+y) acos z@(x:+y) = = atan z@(x:+y) asinh z acosh z atanh z = = = = .v’) v’ = abs y / (u’*2) u’ = sqrt ((magnitude z + abs x) / 2) sin x * cosh y :+ cos x * sinh y cos x * cosh y :+ (.u’) else (u’.sin x * sinh y) (sinx*coshy:+cosx*sinhy)/(cosx*coshy:+(sinx*sinhy)) where sinx = sin x cosx = cos x sinhy = sinh y coshy = cosh y cos y * sinh x :+ sin y * cosh x cos y * cosh x :+ sin y * sinh x (cosy*sinhx:+siny*coshx)/(cosy*coshx:+siny*sinhx) where siny = sin y cosy = cos y sinhx = sinh x coshx = cosh x y’:+(x’) where (x’:+y’) = log (((y):+x) + sqrt (1 .v) = if x < 0 then (v’.158 CHAPTER 13.
showFloat. readHex. showSigned. readSigned. Int) :: (RealFrac a) => ReadS a :: ReadS String 159 . showHex. showIntAtBase. readOct. showEFloat. showOct. floatToDigits. readFloat. showGFloat. readDec. showInt. lexDigits) where fromRat showSigned showIntAtBase showInt showOct showHex readSigned readInt readDec readOct readHex showEFloat showFFloat showGFloat showFloat floatToDigits readFloat lexDigits :: (RealFloat a) => Rational > a :: :: :: :: :: (Real a) Integral Integral Integral Integral => (a > ShowS) > Int > a > ShowS a => a > (Int > Char) > a > ShowS a => a > ShowS a => a > ShowS a => a > ShowS :: (Real a) => ReadS a > ReadS a :: (Integral a) => a > (Char > Bool) > (Char > Int) > ReadS a :: (Integral a) => ReadS a :: (Integral a) => ReadS a :: (Integral a) => ReadS a :: :: :: :: (RealFloat (RealFloat (RealFloat (RealFloat a) a) a) a) => => => => Maybe Int > a > ShowS Maybe Int > a > ShowS Maybe Int > a > ShowS a > ShowS :: (RealFloat a) => Integer > a > ([Int].Chapter 14 Numeric module Numeric(fromRat. showFFloat. readInt.
1 Showing functions showSigned :: (Real a) => (a > ShowS) > Int > a > ShowS converts a possiblynegative Real value of type a to a string.0015).45e2. and scientiﬁc notation otherwise. . £ ¤ ¡ ¡ ¡ ¢ ¦ 7 3¢ ¦ 7 3¢ 7 3¢ © § ¦ ¤ ¥ £ 2 ¤ ¥ © ¡ © § ¦ ¡ £ ¦ 2 ¥ © © § ¦ ¡ ) . the value is shown to full preciIn the call showEFloat sion. NUMERIC This library contains assorted numeric functions.160 CHAPTER 14. 8. In what follows. – showGFloat uses standard decimal notation for arguments whose absolute value lies between 0. floatToDigits :: (RealFloat a) => Integer > a > ([Int]. if is Nothing. and 16 respectively.999. recall the following type deﬁnitions from the Prelude: type ShowS = String > String type ReadS = String > [(a.g. 1.5e3).1 and 9. showIntAtBase :: Integral a => a > (Int > Char) > a > ShowS shows a nonnegative Integral number using the base speciﬁed by the ﬁrst argument. and is a function that can show unsigned values. 2. many of which are used in the standard Prelude. showHex :: Integral a => a > ShowS show nonnegative Integral numbers in base 10.String)] 14. – showEFloat uses scientiﬁc (exponential) notation (e. is the value to show. showInt. and the character representation speciﬁed by the second. showEFloat. In the call showSigned . 245000. if is Just . is the precedence of the enclosing context. then at most digits after the decimal point are shown. showFFloat. 0.g.999. Exactly the same applies to the argument of the other two functions. showOct. showGFloat :: (RealFloat a) => Maybe Int > a > ShowS These three functions all show signed RealFloat values: – showFFloat uses standard decimal notation (e. if © § then the following properties hold: £ £ ¤ – ¤ £ ¡ ¤ – (when ¥ ¤ ¢ ¨£ – £ 888 ¤ £ ¢ £8 ¤ – ¥ ) £888 ¤ £ ¢ £ floatToDigits ([ ]. More speciﬁcally. Int) converts a base and a value to the representation of the value in digits. plus an exponent.
numerator. readDec. expressed in decimal scientiﬁc notation. floatToDigits. showOct. readSigned. isOctDigit. readHex.3 Miscellaneous fromRat :: (RealFloat a) => Rational > a converts a Rational value into any type in class RealFloat. is a predicate distinguishing valid digits in this base. Array. lexDigits) where import Char import Ratio import Array ( . and hexadecimal notation respectively. is the base. octal. array ) ¦ ©§ ¢© ¢ ' § ¤ ¦ § ¦ ©§ § ¤ ¦ ¢© ¢ ' . showInt. readOct. intToDigit ) (%). showSigned. showIntAtBase.4 Library Numeric module Numeric(fromRat. 14. § (NB: readInt is the “dual” of showIntAtBase. The inconsistent naming is a historical accident. readOct.2. READING FUNCTIONS 161 14. given a reader for an unsigned value. in decimal. ( ( isDigit. showFFloat. both upper or lower case letters are allowed. readFloat. showFloat. readHex :: (Integral a) => ReadS a each read an unsigned number. readInt :: (Integral a) => a > (Char>Bool) > (Char>Int) > ReadS a reads an unsigned Integral value in an arbitrary base. and converts a valid digit character to an Int.) 14. In the call readInt .2 Reading functions readSigned :: (Real a) => ReadS a > ReadS a reads a signed Real value. isHexDigit digitToInt. showGFloat. denominator ) (!). readFloat :: (RealFrac a) => ReadS a reads an unsigned RealFrac value. readInt. In the hexadecimal case.14. lexDigits :: ReadS String reads a nonempty string of decimal digits. showEFloat. readDec. showHex. and readDec is the “dual” of showInt.
This should be used in the .This converts a rational to a floating. p’) = scaleRat (toRational b) minExp xMin xMax p0 (x / f) r = encodeFloat (round x’) p’ .Then round the rational to an Integer and encode it with the exponent .Handle exceptional cases .Scale x until xMin <= x < xMax. or p (the exponent) <= minExp. p) else if x >= xMax then scaleRat b minExp xMin xMax (p+1) (x/b) else if x < xMin then scaleRat b minExp xMin xMax (p1) (x*b) else (x.Scale the rational number by the RealFloat base until . .that we got from the scaling.it lies in the range of the mantissa (as used by decodeFloat/encodeFloat).Conversion process: . Int) scaleRat b minExp xMin xMax p x = if p <= minExp then (x. minExpt = 0::Int maxExpt = 1100::Int expt :: Integer > Int > Integer expt base n = if base == 2 && n >= minExpt && n <= maxExpt then expts!n else baseˆn . .To speed up the scaling process we compute the log2 of the number to get .p) ‘max‘ minExp f = if p0 < 0 then 1 % expt b (p0) else expt b p0 % 1 (x’. fromRat’ :: (RealFloat a) => Rational > a fromRat’ x = r where b = floatRadix r p = floatDigits r (minExp0.Fractional instances of Float and Double.a first guess of the exponent.fromRat’ (x) else fromRat’ x . _) = floatRange r minExp = minExp0 . fromRat :: (RealFloat a) => Rational > a fromRat x = if x == 0 then encodeFloat 0 0 else if x < 0 then . scaleRat :: Rational > Int > Rational > Rational > Int > Rational > (Rational.Exponentiation with a cache for the most common numbers.first.162 CHAPTER 14. p) .the real minimum exponent xMin = toRational (expt b (p1)) xMax = toRational (expt b p) p0 = (integerLogBase b (numerator x) integerLogBase b (denominator x) . NUMERIC .p . .
s) (n.s)  (str.but that would be very slow! We are just slightly more clever.4.2ˆn)  n <.Simplest way would be just divide i by b until it’s smaller then b. showHex are used for positive numbers only showInt. integerLogBase :: Integer > Integer > Int integerLogBase b i = if i < b then 0 else .digit to char > a . maxExpt]] 163 . read’’ s] lex r.[minExpt . .showIntAtBase: can’t show negative numbers"  n’ == 0 = rest’  otherwise = showIntAtBase base intToDig n’ rest’ where (n’. showOct.maxExpt) [(n. showHex :: Integral a => a > ShowS showOct = showIntAtBase 8 intToDigit showInt = showIntAtBase 10 intToDigit showHex = showIntAtBase 16 intToDigit showIntAtBase :: Integral a => a . LIBRARY NUMERIC expts :: Array Int Integer expts = array (minExpt.number to show > ShowS showIntAtBase base intToDig n rest  n < 0 = error "Numeric.t)  (""."") <<<< lex r. let l = 2 * integerLogBase (b*b) i doDiv :: Integer > Int > Int doDiv i l = if i < b then l else doDiv (i ‘div‘ b) (l+1) in doDiv (i ‘div‘ (bˆl)) l .d) = quotRem n base rest’ = intToDig (fromIntegral d) : rest readSigned :: (Real a) => ReadS a > ReadS a readSigned readPos = readParen False read’ where read’ r = read’’ r ++ [(x.Compute the (floor of the) log of i in base b. showOct.Try squaring the base first to cut down the number of divisions. showPos (x))  otherwise = showPos x .t) read’’ r = [(n.Misc utilities to show integers and floats showSigned :: Real a => (a > ShowS) > Int > a > ShowS showSigned showPos p x  x < 0 = showParen (p > 6) (showChar ’’ .showInt.s) (x. readPos str] .base > (Int > Char) .14.. .
. readHex :: (Integral a) => ReadS a readDec = readInt 10 isDigit digitToInt readOct = readInt 8 isOctDigit digitToInt readHex = readInt 16 isHexDigit digitToInt showEFloat showFFloat showGFloat showFloat :: :: :: :: (RealFloat (RealFloat (RealFloat (RealFloat showString showString showString showGFloat a) a) a) a) => => => => Maybe Int > a > ShowS Maybe Int > a > ShowS Maybe Int > a > ShowS a > ShowS showEFloat d x = showFFloat d x = showGFloat d x = showFloat = (formatRealFloat FFExponent d x) (formatRealFloat FFFixed d x) (formatRealFloat FFGeneric d x) Nothing This type is not exported.nonnull isDig s ] . NUMERIC . readInt :: (Integral a) => a > (Char > Bool) > (Char > Int) > ReadS a readInt radix isDig digToInt s = [(foldl1 (\n d > n * radix + d) (map (fromIntegral . .164 CHAPTER 14. data FFFormat = FFExponent  FFFixed  FFGeneric . digToInt) ds). readOct.readInt reads a string of digits using an arbitrary base. r)  (ds.These are the format types.Unsigned readers for various bases readDec.Leading minus signs must be handled elsewhere.r) <.
e) = let ds = map intToDigit is in case fmt of FFGeneric > doFmt (if e < 0  e > 7 then FFExponent else FFFixed) (is.0e0" [d] > d : ".’:ds ++ "e" ++ show (e1+ei) FFFixed > case decs of Nothing .14. LIBRARY NUMERIC 165 formatRealFloat :: (RealFloat a) => FFFormat > Maybe Int > a > String formatRealFloat fmt decs x = s where base = 10 s = if isNaN x then "NaN" else if isInfinite x then if x < 0 then "Infinity" else "Infinity" else if x < 0  isNegativeZero x then ’’ : doFmt fmt (floatToDigits (toInteger base) (x)) else doFmt fmt (floatToDigits (toInteger base) x) doFmt fmt (is. e) FFExponent > case decs of Nothing > case ds of [] > "0. is’) = roundTo base (dec’+1) is d:ds = map intToDigit (if ei > 0 then init is’ else is’) in d:’.’ : ds ++ ’e’:show (e1) Just dec > let dec’ = max dec 1 in case is of [] > ’0’:’.Always prints a decimal point  e > 0 > take e (ds ++ repeat ’0’) .0e" ++ show (e1) d:ds > d : ’.’:take dec’ (repeat ’0’) ++ "e0" _ > let (ei.4.
digits after the decimal point roundTo :: Int > Int > [Int] > (Int. not . .. NUMERIC ++ ’. is) > (1. In general.166 CHAPTER 14.ab." ++ mk0 (replicate (e) ’0’ ++ ds) Just dec > .This function returns a nonempty list of digits (Ints in [0. 0:ds) else (0. i’:ds) Based on "Printing FloatingPoint Numbers Quickly and Accurately" by R. 1 : is) where b2 = base ‘div‘ 2 f n [] = (0.Print 34. [Int]) roundTo base d is = case f d is of (0.when the format specifies no . not 34. Dybvig.34. Int) . is) (1.then r = 0. K.. b. in PLDI 96. . .’ : s .34 mk0 s = s mkdot0 "" = "" mkdot0 s = ’. It should be improved. z]. Burger and R.base1]) . e) . is’) = roundTo base dec’ (replicate (e) 0 ++ is) d : ds = map intToDigit (if ei > 0 then is’ else 0:is’) in d : mkdot0 ds where mk0 "" = "0" .z * baseˆe floatToDigits :: (RealFloat a) => Integer > a > ([Int].’ : mk0 (drop e ds)  otherwise > "0.G. rs) = splitAt (e+ei) (map intToDigit is’) in mk0 ls ++ mkdot0 rs else let (ei. ds) = f (d1) is i’ = c + i in if i’ == base then (1. is’) = roundTo base (dec’ + e) is (ls... replicate n 0) f 0 (i:_) = (if i >= b2 then 1 else 0.Print 0.Print decimal point iff dec > 0 let dec’ = max dec 0 in if e >= 0 then let (ei. if floatToDigits r = ([a.and an exponent. []) f d (i:is) = let (c. The version here uses a much slower logarithm estimator. is) > (0.
1 + e0) * 3 ‘div‘ 10 else ceiling ((log (fromInteger (f+1)) + fromIntegral e * log (fromInteger b)) / log (fromInteger base)) fixup n = if n >= 0 then if r + mUp <= expt base n * s then n else fixup (n+1) else if expt base (n) * (r + mUp) <= s then n .4. e0+n) else (f0.p 167 . b) else (f*be*2.Haskell promises that p1 <= logBase b f < p. 0) floatToDigits base x = let (f0.the fraction will make it err even more. 1) else (f*2. 2. 2*b.14. e0) (r. bˆ(e+1)*2. Adjust for this. Ignoring . mDn) = if e >= 0 then let be = bˆe in if f == bˆ(p1) then (f*be*b*2.Haskell requires that f be adjusted so denormalized numbers . be) else if e > minExp && f == bˆ(p1) then (f*b*2. e) = let n = minExp . 1) k = let k0 = if b==2 && base==10 then .the following will err on the low side. bˆ(e)*2.the real minimum exponent .logBase 10 2 is slightly bigger than 3/10 so . f :: Integer e :: Int (f. e0) = decodeFloat x (minExp0. mUp. be. (p .e0 in if n > 0 then (f0 ‘div‘ (bˆn). be*b. s. b. . _) = floatRange x p = floatDigits x b = floatRadix x minExp = minExp0 .will have an impossibly low exponent. LIBRARY NUMERIC floatToDigits _ 0 = ([]. 1.
t) <.lexFrac d ] lexFrac (’. readFloat readFloat r :: (RealFrac a) => ReadS a = [(fromRational ((n%1)*10ˆˆ(kd)). False) > dn : ds (False. NUMERIC else fixup (n+1) in fixup k0 gen ds rn sN mUpN mDnN = let (dn.t)  (k.s)] readExp (e:s)  e ‘elem‘ "eE" = readExp’ s readExp s = [(0.readDec s] readExp’ (’+’:s) = readDec s readExp’ s = readDec s lexDigits lexDigits nonnull nonnull p s :: ReadS String = nonnull isDigit :: (Char > Bool) > ReadS String = [(cs.t) <. True) > if rn’ * 2 < sN then dn : ds else dn+1 : ds (False. (ds’.lex r] where readFix r = [(read (ds++ds’).lexDigits r. rn’) = (rn * base) ‘divMod‘ sN mUpN’ = mUpN * base mDnN’ = mDnN * base in case (rn’ < mDnN’.t) <.t) <.’ is optional. (k. False) > gen (dn:ds) rn’ sN mUpN’ mDnN’ rds = if k >= 0 then gen [] r (s * expt base k) mUp mDn else let bk = expt base (k) in gen [] (r * bk) s (mUp * bk) (mDn * bk) (map fromIntegral (reverse rds).d) <. rn’ + mUpN’ > sN) of (True. The ‘. t)  (ds.168 CHAPTER 14.point than the Haskell lexer. length ds’. k) in .d. t)  ("Infinity".[span p s]] .t) <. True) > dn+1 : ds (True.t)  (n.readFix r.s) <.t) <.’:ds) = lexDigits ds lexFrac s = [("".This floating point reader uses a less restrictive syntax for floating .readExp s] ++ [ (0/0.t)  (cs@(_:_).lex r] ++ [ (1/0. t)  ("NaN".s)] readExp’ (’’:s) = [(k.
. index.u) map index (range (l.. An implementation is entitled to assume the following laws about these operations: range (l.a) > (a.a) > (a. Ix b) . where .. inRange..... index.u) !! index (l.a) > (a. which deﬁnes the lower and upper bounds of the range.Chapter 15 Indexing Operations module Ix ( Ix(range... instance instance instance instance (Ix a.u)] 169 .. The Ix class contains the methods range.rangeSize (l. The range operation enumerates all subscripts. to an integer..et cetera instance instance Ix Ix Ix => Ix Ix Bool Ix Ordering where . The index operation maps a bounding pair. .. .when i is in range inRange (l. and inRange. and a subscript.u)) == [0. the inRange operation tells whether a particular subscript lies in the range deﬁned by a bounding pair. .a) > [a] a > Int a > Bool Int Char Int Integer (a.b) where where where where .u) i == i . The Ix class is used to map a contiguous subrange of values in a type onto integers..u) i == i ‘elem‘ range (l. rangeSize) ) where class Ord a => range index inRange rangeSize Ix :: :: :: :: a where (a. It is used primarily for array indexing (see Chapter 16).
For an enumeration.170 CHAPTER 15. the derived instance declarations are as shown for tuples in Figure 15.e.Green.Blue] 1 False . For example.3.Blue) Red For singleconstructor datatypes.Blue) Green inRange (Yellow.3). £ ¥ ¤ == == == [Yellow. datatypes having only nullary constructors) and singleconstructor datatypes. INDEXING OPERATIONS 15.Blue) index (Yellow.1 Deriving Instances of Ix It is possible to derive an instance of Ix automatically. whose constituent types are instances of Ix. This is the same numbering deﬁned by the Enum class. given the datatype: data Colour = Red  Orange  Yellow  Green  Blue  Indigo  Violet we would have: range (Yellow. Such derived instance declarations for the class Ix are only possible for enumerations (i. using a deriving clause on a data declaration (Section 4. the nullary constructors are assumed to be numbered lefttoright with the indices being to inclusive. A Haskell implementation must provide Ix instances for tuples up to at least size 15.1.
.uk1) ik1 + rangeSize (lk1.i2.(u1... i2 <.u2.uk) * ( index (lk1.l’).u2)..u1))) inRange ((l1.i2.range (l2..u’)) (i..u) i * rangeSize (l’..uk)) (i1..u2.i’)  i <..15...uk1) * ( ..u’)) = [(i. .l2.lk).(u1.ik)  i1 <.ik) = index (lk.. && inRange (lk.u’)] index ((l..l2.b) where range ((l..(u.Instances for other tuples are obtained from this scheme: .....1: Derivation of Ix instances .lk).l’). . i’ <.. DERIVING INSTANCES OF IX 171 instance (Ix a.uk)] index ((l1.a2. Ix b) => Ix (a..range (l.ak) where range ((l1...u’) i’ inRange ((l.uk) ik Figure 15.uk)) = [(i1.u’)) (i.instance (Ix a1. Ix ak) => Ix (a1...range (l1.. ik <.(u1.u2) i2 && .range (l’.lk).(u.u1).u)..ik) = inRange (l1.u’) + index (l’. index (l1.i’) = inRange (l....i2.l2.uk) ik + rangeSize (lk.......(u.. ..1.u1) i1 && inRange (l2.l’)...range (lk.u2.u) i && inRange (l’... Ix a2.....i’) = index (l.uk)) (i1.u’) i’ ..
" inRange (m.h)  null (range b) = 0  otherwise = index b h + 1 .2) <= (2.2).n) = [m.a) > Int rangeSize b@(l." inRange (c.n) i = m <= i && i <= n instance instance instance instance (Ix a.n] index b@(m.a) > a > Bool rangeSize :: (a.as derived .172 CHAPTER 15.fromEnum c  otherwise = error "Ix.index: Index out of range.n) i  inRange b i = fromInteger (i .Ix b) => Ix (a. inRange.m error "Ix. index.as derived..c’) ci  inRange b ci = fromEnum ci . INDEXING OPERATIONS 15.n) i = [m." m <= i && i <= n instance Ix Integer where range (m.index: Index out of range.n) = [m.fails if the bounds are tuples.n] = = = i . b) .n) index b@(m.a) > [a] index :: (a. For example.index: Index out of range.n) i  inRange b i  otherwise inRange (m..as derived Ix () .NB: replacing "null (range b)" by "not (l <= h)" .1)) = [] instance Ix Char where range (m.a) > a > Int inRange :: (a.m)  otherwise = error "Ix.c’) i = c <= i && i <= c’ instance Ix Int where range (m.. (1. rangeSize) ) where class Ord a => Ix a where range :: (a.n] index b@(c.1) . for all tuples Ix Bool .as derived Ix Ordering .(2.2 Library Ix module Ix ( Ix(range.but the range is nevertheless empty range ((1.
..a) > (a > b) > Array b c > Array a c Eq b) Ord b) Show a. (//).c)] > Array a b :: (Ix a) => Array a b > [(a. Ix b) => (a. ixmap ) where import Ix infixl 9 data !. (!).. assocs. :: :: :: :: :: :: :: :: (Ix (Ix (Ix (Ix (Ix (Ix (Ix (Ix a) a) a) a) a) a) a) a) => => => => => => => => ..a) Array a b > [a] Array a b > [b] Array a b > [(a.a) > [(a. Show b) Read a.. (Ix (Ix (Ix (Ix a..c)] > Array a b :: (Ix a... 173 . . . // => Array a b = . array.b)] > Array a b (a..a) > [(a.b)] (b > c > b) > b > (a.export all of Ix for convenience Array.. accumArray.. listArray.a) > [b] > Array a b Array a b > a > b Array a b > (a. elems. .Abstract (Ix a) array listArray (!) bounds indices elems assocs accumArray (//) accum ixmap instance instance instance instance instance (a. accum. a. . indices.b)] > Array a b :: (Ix a) => (b > c > b) > Array a b > [(a.. a. a.. bounds. Read b) => => => => Functor (Array a) Eq (Array a b) Ord (Array a b) Show (Array a b) Read (Array a b) where where where where where .Chapter 16 Arrays module Array ( module Ix.
These bounds are the lowest and highest indices in the array. in index order.174 CHAPTER 16. but bounds still yields the bounds with which the array was constructed. the type of arrays with indices in a and elements in b is written Array a b. x) deﬁnes the value of the array at index i to be x.1 Array Construction If a is an index type and b is any type. respectively. the value at that index is undeﬁned (i. ) if any index in the list is out of bounds. this module is exported from Array so that modules need not import both Array and Ix. then the array is legal.. To ensure the possibility of such an implementation. and assocs. each of the index type of the array.1 shows some examples that use the array constructor. elements. elems. using an accumulating function which combines the values of associations with the same index. return lists of the indices. a oneorigin vector of length 10 has bounds (1.100]]) Not every index within the bounds of the array need appear in the association list. For example. The array is undeﬁned (i. If.e. The functions indices.100) ((1.1. not as general functions. accumArray. 16.e. Functions restricted in this way can be implemented efﬁciently.1) : [(i. ). Because the indices must be checked for these errors. in that order. Figure 16. the lower bound is greater than the upper bound. but empty. An array may be constructed from a pair of bounds and a list of values in index order using the function listArray. . ARRAYS Haskell provides indexable arrays. Indexing an empty array always gives an arraybounds error.10)).10). ). The ﬁrst argument of array is a pair of bounds. The bounds function applied to an array returns its bounds.1). relaxes the restriction that a given index may appear at most once in the association list. Typically.(10.e. Thus. arrays are treated as data. An array may be created by the function array. An association (i. this The second argument of array is a list of associations of the form ( list will be expressed as a comprehension. and a oneorigin 10 by 10 matrix has bounds ((1.[2. which may be thought of as functions whose domains are isomorphic to contiguous subsets of the integers. when applied to an array. or associations. but nonstrict in the values. array is strict in the bounds argument and in the indices of the association list. The ﬁrst argument of accumArray is the accumulating £ £ ¤¢ £ ¡ £ £ ¥ . If any two associations in the list have the same index. 16. but the values associated with indices that do not appear will be undeﬁned (i. i * a!(i1))  i <. a programmer may reasonably expect rapid access to the components. ). recurrences such as the following are possible: a = array (1. The (!) operator denotes array subscripting.1 Accumulated Arrays Another array creation function. in particular. Since most array functions involve the class Ix. in any dimension.
range b]) 0 0 . in the association list.) For example. hist produces a histogram of the number of occurrences of each index within a speciﬁed range: hist :: (Ix a. the second is an initial value. as well as the indices. i)  i <. accum takes an array and an association list and accumulates pairs from the list into the array with the accumulating function . unlike ordinary arrays.i).16. given a list of values of some index type.2.The inner product of two vectors inner :: (Ix a.range b] = bounds a 175 .range b] where b = bounds a . Thus. Num b) => Array a b > Array a b > b inner v w = if b == bounds w then sum [v!i * w!i  i <. accumulated arrays should not in general be recursive. then accumArray is strict in the values. z)  i <. if m is a 1origin.1: Array examples function. Num b) => (a. INCREMENTAL ARRAY UPDATES .Scaling an array scale :: (Num a. inRange bnds i] If the accumulating function is strict. Thus accumArray can be deﬁned using accum: accumArray f z b = accum f (array b [(i. the remaining two arguments are a bounds pair and an association list.range b] else error "inconformable arrays for inner product" where b = bounds v Figure 16.a) > [a] > Array a b hist bnds is = accumArray (+) 0 bnds [(i. except with the diagonal zeroed.. For example. as for the array function. then m//[((i.[1. n by n matrix.Inverting an array that holds a permutation of its indices invPerm :: (Ix a) => Array a a > Array a a invPerm a = array b [(a!i. Ix scale x a = array b where b of numbers by a given number: b) => a > Array b a > Array b a [(i. 1)  i<is.n]] is the same matrix. 0)  i <. (As with the array function. 16. the indices in the association list must be unique for the updated elements to be deﬁned.2 Incremental Array Updates The operator (//) takes an array and a list of pairs and returns an array identical to the left argument except that it has been updated by the associations in the right argument. a!i * x)  i <.
l’).a) > Array a b > Array a b subArray bnds = ixmap bnds (\i>i) . assocs.Diagonal of a matrix (assumed to be square) diag :: (Ix a) => Array (a.4 Library Array module Array ( module Ix. . // data (Ix a) => Array a b = MkArray (a.j)) x where ((_.b) c > Array b c row i x = ixmap (l’. elems.u’)) = bounds x . bounds.Projection of first components of an array of pairs firstArray :: (Ix a) => Array a (b.176 CHAPTER 16. respectively.2 shows some examples.export all of Ix Array. accum. (//).c) > Array a b firstArray = fmap (\(x. array.u’) (\j>(i.a) (a > b) deriving () ._). ARRAYS .A rectangular subarray subArray :: (Ix a) => (a. ixmap ) where import Ix import List( (\\) ) infixl 9 !.y)>x) Figure 16. they may be thought of as providing function composition on the left and right. Ix b) => a > Array (a.a) b > Array a b diag x = ixmap (l.(_.i)) x where ((l. 16.(u. (!). accumArray. The fmap function transforms the array values while ixmap allows for transformations on array indices.2: Derived array examples 16.u) (\i>(i. Figure 16. indices. listArray. with the mapping that the original array embodies.A row of a matrix row :: (Ix a._)) = bounds x .3 Derived Arrays The two functions fmap and ixmap derive new arrays from existing ones.
b)] > Array a b array b ivs = if and [inRange b i  (i.b)] > Array a b = array (bounds a) (old_ivs ++ new_ivs) where old_ivs = [(i. Ix b) => (a. f) instance (Ix a.c)] > Array a b = accum f (array b [(i._) <.b)] = [(i.a!i)  i <. i ‘notElem‘ new_is] new_is = [i  (i. bounds :: (Ix a) => Array a b > [b] = [a!i  i <.a) > [b] > Array a b = array b (zipWith (\ a b > (a.f (a!i) v)]) :: (Ix a) => (b > c > b) > b > (a.a) > [(a.range b] accum accum f accumArray accumArray f z b ixmap ixmap b f a instance (Ix a) => Functor (Array a) where fmap fn (MkArray b f) = MkArray b (fn .!: \ \multiply defined array element") else error "Array.v) <. Eq b) => Eq (Array a b) a == a’ = assocs a == assocs a’ where . i == j] of [v] > v [] > error "Array.16.array: outofrange array association" listArray listArray b vs (!) (!) (MkArray _ f) bounds bounds (MkArray b _) indices indices elems elems a assocs assocs a (//) a // new_ivs :: (Ix a) => (a.new_ivs] :: (Ix a) => (b > c > b) > Array a b > [(a.!: \ \undefined array element" _ > error "Array.a) = b :: (Ix a) => Array a b > [a] = range ._) <.indices a.indices a] :: (Ix a) => Array a b > [(a.v) > a // [(i. LIBRARY ARRAY 177 array :: (Ix a) => (a.ivs.4.c)] > Array a b = foldl (\a (i.z)  i <. a ! f i)  i <.b)) (range b) vs) :: (Ix a) => Array a b > a > b = f :: (Ix a) => Array a b > (a.range b]) :: (Ix a.a) > [(a.indices a] :: (Ix a) => Array a b > [(a. a!i)  i <.ivs] then MkArray b (\j > case [v  (i.a) > (a > b) > Array b c > Array a c = array b [(i.
Show a. showChar ’ ’ . showsPrec (arrPrec+1) (assocs a) ) instance (Ix a. u)  ("array". showsPrec (arrPrec+1) (bounds a) .lex r. (as. (b.178 instance (Ix a. ARRAYS instance (Ix a. Ord b) => Ord (Array a b) a <= a’ = assocs a <= assocs a’ where CHAPTER 16. Read a.readsPrec (arrPrec+1) s.u) <. Show b) => Show (Array a b) where showsPrec p a = showParen (p > arrPrec) ( showString "array " .Precedence of the ’array’ function is that of application itself arrPrec = 10 . Read b) => Read (Array a b) where readsPrec p = readParen (p > arrPrec) (\r > [ (array b as.readsPrec (arrPrec+1) t ]) .s) <.t) <.
179 .
intersect. nubBy. foldl1. any. tails. unfoldr. tail. unzip5. insert. groupBy. deleteBy. scanl. zip. nub.[]((:). splitAt. find. dropWhile. takeWhile. minimumBy.This is builtin syntax map.. intersperse. genericTake. maximum. genericLength. zipWith6. . intersectBy. zip4. replicate. unlines. all. genericIndex. minimum. delete. concatMap. group. cycle. zipWith5. (\\). unzip7.. (!!). foldl. insertBy. scanl1. foldr1. scanr. zip3. sort.180 CHAPTER 17. filter. scanr1. (++). mapAccumL. elemIndices. isPrefixOf. genericReplicate. notElem. unwords. elem. zipWith7. . transpose. unzip4. genericDrop. partition. null. break. union. lines. zipWith. zipWith3. reverse. mapAccumR. concat. product. last. repeat. genericSplitAt. head. words. findIndices. zipWith4. take. sum. drop. iterate. zip6. unionBy. sortBy.and what the Prelude exports . inits. unzip6.. []). zip7. findIndex. length. unzip. deleteFirstsBy. and. unzip3 ) where infix 5 \\ elemIndex elemIndices find findIndex findIndices nub nubBy delete deleteBy (\\) deleteFirstsBy union unionBy :: :: :: :: :: :: :: :: :: :: :: :: :: Eq Eq (a (a (a Eq (a Eq (a Eq (a Eq (a a => a > [a] > Maybe Int a => a > [a] > [Int] > Bool) > [a] > Maybe a > Bool) > [a] > Maybe Int > Bool) > [a] > [Int] a => [a] > [a] > a > Bool) > [a] > [a] a => a > [a] > [a] > a > Bool) > a > [a] > [a] a => [a] > [a] > [a] > a > Bool) > [a] > [a] > [a] a => [a] > [a] > [a] > a > Bool) > [a] > [a] > [a] . maximumBy. foldr. lookup. zip5. or. span. init. isSuffixOf. LIST UTILITIES Chapter 17 List Utilities module List ( elemIndex.
d.c.[a]) Eq a => [a] > [[a]] (a > a > Bool) > [a] > [[a]] [a] > [[a]] [a] > [[a]] Eq a => [a] > [a] > Bool Eq a => [a] > [a] > Bool (a > b > (a.[c].b.[d].[b]) Integral a => [b] > a > b Integral a => a > b > [b] :: [a] > [b] > [c] > [d] > [(a.d.b. [c]) (a > b > (a.[e]) :: [(a.d.d.f)] :: [a] > [b] > [c] > [d] > [e] > [f] > [g] > [(a.f)] > ([a].c.e.[e].[f].f.e)] :: [a] > [b] > [c] > [d] > [e] > [f] > [(a.[c].[d].g)] :: (a>b>c>d>e) > [a]>[b]>[c]>[d]>[e] :: (a>b>c>d>e>f) > [a]>[b]>[c]>[d]>[e]>[f] :: (a>b>c>d>e>f>g) > [a]>[b]>[c]>[d]>[e]>[f]>[g] :: (a>b>c>d>e>f>g>h) > [a]>[b]>[c]>[d]>[e]>[f]>[g]>[h] :: [(a.b. c)) > a > [b] > (a.e.181 intersect intersectBy intersperse transpose partition group groupBy inits tails isPrefixOf isSuffixOf mapAccumL mapAccumR unfoldr sort sortBy insert insertBy maximumBy minimumBy genericLength genericTake genericDrop genericSplitAt genericIndex genericReplicate zip4 zip5 zip6 zip7 zipWith4 zipWith5 zipWith6 zipWith7 unzip4 unzip5 unzip6 unzip7 :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: Eq a => [a] > [a] > [a] (a > a > Bool) > [a] > [a] > [a] a > [a] > [a] [[a]] > [[a]] (a > Bool) > [a] > ([a]. [c]) (b > Maybe (a.g)] > ([a].d.b)) > b > [a] Ord a => [a] > [a] (a > a > Ordering) > [a] > [a] Ord a => a > [a] > [a] (a > a > Ordering) > a > [a] > [a] (a > a > Ordering) > [a] > a (a > a > Ordering) > [a] > a Integral a => [b] > a Integral a => a > [b] > [b] Integral a => a > [b] > [b] Integral a => a > [b] > ([b].c.b.f.b.[e].[b]. .c.b.e)] > ([a].[d].[c].b.d)] :: [a] > [b] > [c] > [d] > [e] > [(a.[b].c.c.[f]) :: [(a.[b].c. c)) > a > [b] > (a.d)] > ([a].e.d.[c].c.b.[d]) :: [(a.[g]) This library deﬁnes some lesserused operations over lists.[b].e.
delete. e.. the ﬁrst occurrence of each element of ys in turn (if any) has been removed from xs. giving the occurrences of val in list. if there is no such element.. find returns the ﬁrst element of a list that satisﬁes a predicate.g.3] = [1.3.4] .2 “Set” operations There are a number of “set” operations deﬁned over the List type. [1.4. e. Nothing is returned if not (val ‘elem‘ list). provided that their ﬁrst argument contains no duplicates. elemIndices val list returns an inorder list of indices.g. In the result of xs \\ ys.1. findIndices returns a list of all such indices. union and intersect (and their By variants) preserve the invariant that their result does not contain duplicates. Thus. "dog" ‘union‘ "cow" == "dogcw" intersect is list intersection.4.4] ‘intersect‘ [2.2.. nub (meaning “essence”) removes duplicates elements from a list. findIndex returns the corresponding index.4] delete x removes the ﬁrst occurrence of x from its list argument. LIST UTILITIES 17.3. union is list union. of val in list as Just index. 17.1 Indexing lists elemIndex val list returns the index of the ﬁrst occurrence.3.8] == [2. delete ’a’ "banana" == "bnana" (\\) is list difference (nonassociative).3. nub removes duplicate elements from a list.182 CHAPTER 17. or Nothing. (\\).g. if any. For example: nub [1. (xs ++ ys) \\ xs == ys.6. e.
3.d. longest ﬁrst.3]. unfoldr builds a list from a seed value.[3.e. e.6]] partition takes a predicate and a list and returns a pair of lists: those elements of the argument list that do and do not satisfy the predicate."pp".""] mapAccumL f s l applies f to an accumulating “state” parameter s and to each element of l in turn.5]."ss".e" transpose transposes the rows and columns of its argument.b.4].[2. e. mapAccumR is similar to mapAccumL except that the list is processed from righttoleft rather than lefttoright. inits "abc" == ["". transpose [[1.[4."a".6]] == [[1."i". group splits its list argument into a list of lists of equal.. filter (not ."ab". shortest ﬁrst. tails "abc" == ["abc". partition p xs == (filter p xs.g."i"] inits returns the list of initial segments of its argument list..g. For example group "Mississippi" == ["M"."i". "c". which inserts objects into a list according to the speciﬁed ordering relation. respectively."ss". For example: . LIST TRANSFORMATIONS 183 17."i". here speciﬁed in terms of the insertBy function. "bc". adjacent elements.17.’ "abcde" == "a. p) xs) sort implement a stable sorting algorithm. intersperse ’."abc"] tails returns the list of all ﬁnal segments of its argument list.5.. insert inserts a new element into an ordered list (arranged in increasing order).3 List transformations intersperse sep inserts sep between the elements of its list argument.c. 17. i.4 unfoldr The unfoldr function is a “dual” to foldr: while foldr reduces a list to a summary value.2.
The library does not provide elemBy. The function: nubBy nubBy eq [] nubBy eq (x:xs) :: (a > a > Bool) > [a] > [a] = [] = x : nubBy eq (filter (\y > not (eq x y)) xs) allows the programmer to supply their own equality test. groupBy. unionBy. 17. the predicate is assumed to deﬁne a total ordering. The “By” variants are as follows: nubBy. overloaded functions have a nonoverloaded counterpart whose name is sufﬁxed with “By”. unfoldr can undo a foldr operation: unfoldr f’ (foldr f z xs) == xs if the following holds: f’ (f x y) = Just (x. when the “By” function replaces an Ord context by a binary predicate. A handful of overloaded functions (elemIndex.184 CHAPTER 17. deleteBy. the function nub could be deﬁned as follows: nub nub [] nub (x:xs) :: (Eq a) => [a] > [a] = [] = x : nub (filter (\y > not (x == y)) xs) However. the equality method may not be appropriate in all situations. . When the “By” function replaces an Eq context by a binary predicate. the predicate is assumed to deﬁne an equivalence. sufﬁx) of the second argument. insertBy.5 Predicates isPrefixOf and isSuffixOf check whether the ﬁrst argument is a preﬁx (resp. deleteFirstsBy (the By variant of \\). because any (eq x) does the same job as elemBy eq x would. f x)) In some cases. sortBy. elemIndices. isSuffixOf) were not considered important enough to have “By” variants.6 The “By” operations By convention. maximumBy. minimumBy. intersectBy. isPrefixOf. LIST UTILITIES iterate f == unfoldr (\x > Just (x. For example.y) f’ z = Nothing 17.
unzip. The “generic” operations are as follows: genericLength. genericIndex (the generic version of !!). The List library provides these same three operations for 4. genericTake.8 Further “zip” operations The Prelude provides zip. genericSplitAt. 6. zipWith. . genericDrop. :: Integral a => [b] > a 17. genericLength is a generalised version of length. and 7 arguments.17. unzip3. 5. zip3. and zipWith3.7 The “generic” operations The preﬁx “generic” indicates an overloaded function that is a generalised version of a Prelude function. THE “GENERIC” OPERATIONS 185 17. For example.7. genericReplicate.
genericIndex.9 Library List module List ( elemIndex. tails. take. intersperse. zip5. zipWith3. insert. intersectBy. unzip5. genericTake. iterate.]. elemIndices. elem. zipWith. or. (!!). findIndices p :: (a > Bool) > [a] > [Int] = [ i  (x. init. . unlines. isSuffixOf. deleteFirstsBy.[]((:). inits.. delete. find. .186 CHAPTER 17. zip7. span. LIST UTILITIES 17. []). minimumBy. unzip3 ) where import Maybe( listToMaybe ) infix 5 \\ elemIndex elemIndex x elemIndices elemIndices x find find p findIndex findIndex p findIndices findIndices p xs nub nub :: Eq a => a > [a] > Maybe Int = findIndex (x ==) :: Eq a => a > [a] > [Int] = findIndices (x ==) :: (a > Bool) > [a] > Maybe a = listToMaybe . zipWith5. drop. insertBy. words. (++). p x ] :: Eq a => [a] > [a] = nubBy (==) . all. isPrefixOf. genericSplitAt. zipWith6.This is builtin syntax map. foldl1. lines. and. minimum. dropWhile.. sort. notElem. mapAccumR. maximum. findIndex. maximumBy. intersect.. reverse. replicate. unzip6. nubBy. genericDrop. partition..zip xs [0. zip. mapAccumL. genericReplicate.and what the Prelude exports . union. zip3. genericLength.i) <. splitAt. (\\). tail. length. findIndices. filter. scanl. unwords. foldl. any. break. zip4. unzip. scanl1. repeat. foldr1. product. sum. unzip4. nub. concat. concatMap. unzip7. filter p :: (a > Bool) > [a] > Maybe Int = listToMaybe . unfoldr. null. foldr. cycle. transpose. groupBy. last. head. lookup. deleteBy. scanr1. zipWith4. sortBy. zipWith7. unionBy. scanr. zip6. group. takeWhile.
"ss".g.9. transpose [[1. adjacent .[]] = [[1.3].2].xs.xss] is not the same as (map head xss) because the former discards empty sublists inside xss transpose :: [[a]] > [[a]] transpose [] = [] transpose ([] : xss) = transpose xss transpose ((x:xs) : xss) = (x : [h  (h:t) <. e.4].[a]) = (filter p xs.4."i"] group :: Eq a => [a] > [[a]] group = groupBy (==) .17."i".5]."ss".xss]) : transpose (xs : [t  (h:t) <. .[5]] .transpose is lazy in both rows and columns. and works for nonrectangular ’matrices’ .elements."i"..[3. LIBRARY LIST nubBy nubBy eq [] nubBy eq (x:xs) delete delete deleteBy deleteBy eq x [] deleteBy eq x (y:ys) (\\) (\\) deleteFirstsBy deleteFirstsBy eq union union unionBy unionBy eq xs ys intersect intersect intersectBy intersectBy eq xs ys intersperse intersperse sep [] intersperse sep [x] intersperse sep (x:xs) 187 :: (a > a > Bool) > [a] > [a] = [] = x : nubBy eq (filter (\y > not (eq x y)) xs) :: Eq a => a > [a] > [a] = deleteBy (==) :: (a > a > Bool) > a > [a] > [a] = [] = if x ‘eq‘ y then ys else y : deleteBy eq x ys :: Eq a => [a] > [a] > [a] = foldl (flip delete) :: (a > a > Bool) > [a] > [a] > [a] = foldl (flip (deleteBy eq)) :: Eq a => [a] > [a] > [a] = unionBy (==) :: (a > a > Bool) > [a] > [a] > [a] = xs ++ deleteFirstsBy eq (nubBy eq ys) xs :: Eq a => [a] > [a] > [a] = intersectBy (==) :: (a > a > Bool) > [a] > [a] > [a] = [x  x <. filter (not ."i".Note that [h  (h:t) <. p) xs) .group "Mississippi" == ["M".group splits its list argument into a list of lists of equal.For example.[2.xss]) partition partition p xs :: (a > Bool) > [a] > ([a]. any (eq x) ys] :: = = = a > [a] > [a] [] [x] x : sep : intersperse sep xs ."pp".
tails xs returns the . "c". "bc".e.b) > a : unfoldr f b :: (Ord a) => [a] > [a] = sortBy compare :: (a > a > Ordering) > [a] > [a] = foldr (insertBy cmp) [] :: (Ord a) => a > [a] > [a] = insertBy compare mapAccumR mapAccumR f s [] mapAccumR f s (x:xs) unfoldr unfoldr f b sort sort sortBy sortBy cmp insert insert .g. LIST UTILITIES :: (a > a > Bool) > [a] > [[a]] = [] = (x:ys) : groupBy eq zs where (ys.y:ys) where (s’. y ) = f s x (s’’. c)) > a > [b] > (a. y:ys) where (s’’...zs) = span (eq x) xs list of initial segments of xs. ["abc". inits "abc" == inits inits [] inits (x:xs) . ys) = mapAccumR f s xs :: (b > Maybe (a. []) = (s’’.b)) > b > [a] = case f b of Nothing > [] Just (a.e.y ) = f s’ x (s’.g. tails "abc" == tails tails [] tails xxs@(_:xs) CHAPTER 17. []) = (s’’."ab".""] :: [a] > [[a]] = [[]] = xxs : tails xs :: = = = Eq a => [a] > [a] > Bool True False x == y && isPrefixOf xs ys isPrefixOf isPrefixOf [] _ isPrefixOf _ [] isPrefixOf (x:xs) (y:ys) isSuffixOf isSuffixOf x y mapAccumL mapAccumL f s [] mapAccumL f s (x:xs) :: Eq a => [a] > [a] > Bool = reverse x ‘isPrefixOf‘ reverse y :: (a > b > (a. c)) > a > [b] > (a. [c]) = (s."a". shortest first. longest first."abc"] :: [a] > [[a]] = [[]] = [[]] ++ map (x:) (inits xs) list of all final segments of xs. [c]) = (s. ["".inits xs returns the .188 groupBy groupBy eq [] groupBy eq (x:xs) .ys) = mapAccumL f s’ xs :: (a > b > (a.
xs’’) error "List.xs’’) :: (Integral a) => a > [b] > [b] = xs = [] = = genericDrop (n1) xs error "List.genericSplitAt: negative argument" genericSplitAt (n1) xs .minimumBy: empty list" = foldl1 min xs where min x y = case cmp x y of GT > y _ > x :: (Integral a) => [b] > a = 0 = 1 + genericLength xs :: (Integral a) => a > [b] > [b] = [] = [] = = x : genericTake (n1) xs error "List.9.genericDrop: negative argument" :: (Integral a) => a > [b] > ([b]. LIBRARY LIST insertBy :: (a > a > insertBy cmp x [] = [x] insertBy cmp x ys@(y:ys’) = case cmp x GT > _ > maximumBy maximumBy cmp [] maximumBy cmp xs Ordering) > a > [a] > [a] 189 y of y : insertBy cmp x ys’ x : ys :: (a > a > Ordering) > [a] > a = error "List.maximumBy: empty list" = foldl1 max xs where max x y = case cmp x y of GT > x _ > y :: (a > a > Ordering) > [a] > a = error "List.genericTake: negative argument" minimumBy minimumBy cmp [] minimumBy cmp xs genericLength genericLength [] genericLength (x:xs) genericTake genericTake _ [] genericTake 0 _ genericTake n (x:xs)  n > 0  otherwise genericDrop genericDrop 0 xs genericDrop _ [] genericDrop n (_:xs)  n > 0  otherwise genericSplitAt genericSplitAt 0 xs genericSplitAt _ [] genericSplitAt n (x:xs)  n > 0  otherwise where (xs’.xs) = ([].[]) = = = (x:xs’.[b]) = ([].17.
[b].....c.bs.b.) :: [a] > [b] > [c] > [d] > [e] > [f] > [(a.d.b:bs.) :: [a] > [b] > [c] > [d] > [e] > [(a.c.cs..b.) :: [a] > [b] > [c] > [d] > [e] > [f] > [g] > [(a..[d]) = foldr (\(a.e.d) ˜(as.[c].d)] = zipWith4 (.d. LIST UTILITIES :: (Integral a) => [b] > a > b = x = = = genericIndex xs (n1) error "List.c.f.b.genericIndex: negative argument" error "List.190 genericIndex genericIndex (x:_) 0 genericIndex (_:xs) n  n > 0  otherwise genericIndex _ _ genericReplicate genericReplicate n x zip4 zip4 zip5 zip5 zip6 zip6 zip7 zip7 CHAPTER 17..c.ds) > (a:as.e)] = zipWith5 (..f)] = zipWith6 (.c:cs.d:ds)) ([].genericIndex: index too large" :: (Integral a) => a > b > [b] = genericTake n (repeat x) :: [a] > [b] > [c] > [d] > [(a.b..[]) zipWith7 zipWith6 .g)] = zipWith7 (...c.d.c..b.b.e.[].d)] > ([a]..) zipWith4 :: (a>b>c>d>e) > [a]>[b]>[c]>[d]>[e] zipWith4 z (a:as) (b:bs) (c:cs) (d:ds) = z a b c d : zipWith4 z as bs cs ds zipWith4 _ _ _ _ _ = [] zipWith5 :: (a>b>c>d>e>f) > [a]>[b]>[c]>[d]>[e]>[f] zipWith5 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) = z a b c d e : zipWith5 z as bs cs ds es zipWith5 _ _ _ _ _ _ = [] :: (a>b>c>d>e>f>g) > [a]>[b]>[c]>[d]>[e]>[f]>[g] zipWith6 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs) = z a b c d e f : zipWith6 z as bs cs ds es fs zipWith6 _ _ _ _ _ _ _ = [] :: (a>b>c>d>e>f>g>h) > [a]>[b]>[c]>[d]>[e]>[f]>[g]>[h] zipWith7 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs) (g:gs) = z a b c d e f g : zipWith7 z as bs cs ds es fs gs zipWith7 _ _ _ _ _ _ _ _ = [] unzip4 unzip4 :: [(a.[]..
b.e.d.d:ds.c:cs.[].ds.bs.17.[]) unzip7 unzip7 .e:es.[d].f) ˜(as.es.ds.g:gs)) ([].e)] > ([a].cs.[d].c.[].f.c.[e]) = foldr (\(a.es) > (a:as.d:ds.[].bs.[]) 191 unzip6 unzip6 :: [(a.e.b:bs.b.[b].[b].b.fs.ds.c.e:es)) ([].c:cs.f:fs.d.cs.d.e.f.[e].g) ˜(as.[].[c].[f]) = foldr (\(a.[b].[e].c.d:ds.b:bs.fs) > (a:as.[g]) = foldr (\(a.[].es.[c].e) ˜(as.[].[].e:es.b.d.9.[c].c:cs.[].[]. LIBRARY LIST unzip5 unzip5 :: [(a.c.d.[].f:fs)) ([].f)] > ([a].[d].gs) > (a:as.b.c.[f].g)] > ([a].b:bs.cs.[].[]) :: [(a.bs.[].e.b.d.
LIST UTILITIES .192 CHAPTER 17.
fromMaybe. fromJust. listToMaybe.. catMaybes. 193 . isNothing. A correct result is encapsulated by wrapping it in Just.Chapter 18 Maybe Utilities module Maybe( isJust.. which would cause the expression to become monadic.. maybeToList. Just). as would happen if error were used.and what the Prelude exports Maybe(Nothing. Other operations on Maybe are provided as part of the monadic classes in the Prelude. isNothing fromJust fromMaybe listToMaybe maybeToList catMaybes mapMaybe :: :: :: :: :: :: :: Maybe a > Bool Maybe a > a a > Maybe a > a [a] > Maybe a Maybe a > [a] [Maybe a] > [a] (a > Maybe b) > [a] > [b] The type constructor Maybe is deﬁned in Prelude as data Maybe a = Nothing  Just a The purpose of the Maybe type is to provide a method of dealing with illegal or optional values without terminating the program. mapMaybe. maybe ) where isJust. and without using IOError from the IO monad. . an incorrect result is returned as Nothing.
catMaybes. mapMaybe. isNothing..ms ] :: (a > Maybe b) > [a] > [b] = catMaybes . map f .and what the Prelude exports Maybe(Nothing. Just). maybe ) where isJust isJust (Just a) isJust Nothing isNothing isNothing fromJust fromJust (Just a) fromJust Nothing fromMaybe fromMaybe d Nothing fromMaybe d (Just a) maybeToList maybeToList Nothing maybeToList (Just a) listToMaybe listToMaybe [] listToMaybe (a:_) catMaybes catMaybes ms mapMaybe mapMaybe f :: Maybe a > Bool = True = False :: Maybe a > Bool = not .. isJust :: Maybe a > a = a = error "Maybe. fromMaybe.1 Library Maybe module Maybe( isJust..fromJust: Nothing" :: a > Maybe a > a = d = a :: Maybe a > [a] = [] = [a] :: [a] > Maybe a = Nothing = Just a :: [Maybe a] > [a] = [ m  Just m <. fromJust. maybeToList. MAYBE UTILITIES 18.194 CHAPTER 18. listToMaybe. .
ord. and other printable characters. toLower. readLitChar. isDigit. the full set of Unicode character attributes is not accessible in this library.. isLower. isOctDigit. . isSpace. isHexDigit. isHexDigit. numeric digits. isDigit. The ﬁrst 128 entries of this character set are identical to the ASCII set. isLatin1. toLower :: Char > Char digitToInt :: Char > Int intToDigit :: Int > Char ord chr :: Char > Int :: Int > Char lexLitChar :: ReadS String readLitChar :: ReadS Char showLitChar :: Char > ShowS This library provides a limited set of operations on the Unicode character set. with the next 128 entries comes the remainder of the Latin1 character set. toUpper. isAlphaNum.Chapter 19 Character Utilities module Char ( isAscii. other alphabetic. lower case alphabetic. isUpper. For the purposes of Haskell. isControl. isAlpha. String ) where isAscii. isPrint. lexLitChar. isUpper. showLitChar. isLatin1. isSpace. isAlphaNum :: Char > Bool toUpper.. intToDigit. chr. Unicode characters may be divided into ﬁve general categories: nonprinting.. isPrint. isAlpha. digitToInt.and what the Prelude exports Char. any 195 . isOctDigit. isControl. isLower. This module offers only a limited view of the full Unicode character set.
. The function lexLitChar does the reverse. The function readLitChar does the same.’9’. . CHARACTER UTILITIES alphabetic character which is not lower case is treated as upper case (Unicode actually has three cases: upper. toLower converts a letter to the corresponding lowercase letter.e. leaving any other character unchanged. isOctDigit. The function showLitChar converts a character to a string using only printable characters. and title). For example: showLitChar ’\n’ s lexLitChar "\\nHello" readLitChar "\\nHello" = = = "\\n" ++ s [("\\n". using Haskell sourcelanguage escape conventions. lower. Similarly. but in addition converts the to the character that it encodes. "Hello")] [(’\n’. ’0’.’F’). here are the predicates which return True: Character Type Lower Case Alphabetic Other Alphabetic Digits Other Printable Nonprinting Predicates isPrint isPrint isPrint isPrint isAlphaNum isAlphaNum isAlphaNum isAlpha isAlpha isLower isUpper The isDigit.196 CHAPTER 19.15.. Numeric digits may be part of identiﬁers but digits outside the ASCII range are not used by the reader to represent numbers. Any Unicode letter which has an uppercase equivalent is transformed. ’a’.. ’A’. returning the sequence of characters that encode the character. The ord and chr functions are fromEnum and toEnum restricted to the type Char. intToDigit and digitToInt convert between a single digit Char and the corresponding Int. leaving any other character unchanged. and isHexDigit functions select only ASCII characters.’f’. digitToInt operates fails unless its argument satisﬁes isHexDigit. intToDigit fails unless its argument is in the range 0. and generates lowercase hexadecimal digits. "Hello")] Function toUpper converts a letter to the corresponding uppercase letter. For each sort of Unicode character. The isSpace function recognizes only white characters in the Latin1 range.. but recognises both upper and lowercase hexadecimal digits (i.
. lexLitChar.’A’. isUpper. ord.’a’. isUpper. readHex) import UnicodePrims . isPrint.1. isHexDigit. chr. isLatin1. toUpper. import Numeric (readDec. isControl. isLatin1. isPrint. isAlpha.and what the Prelude exports Char. isAlphaNum. String ) where import Array . .1 Library Char module Char ( isAscii. isAlpha.Only Latin1 spaces recognized isUpper isLower isAlpha c isDigit c isOctDigit c isHexDigit c isAlphaNum = = = = = = = primUnicodeIsUpper primUnicodeIsLower . lexDigits. isControl.digitToInt: not a digit" . isAlphaNum :: Char > Bool isAscii c isLatin1 c isControl c isPrint = = = = c < ’\x80’ c <= ’\xff’ c < ’ ’  c >= ’\DEL’ && c <= ’\x9f’ primUnicodeIsPrint isSpace c = c ‘elem‘ " \t\n\r\f\v\xA0" .. ..Digit conversion operations digitToInt :: Char > Int digitToInt c  isDigit c = fromEnum c .Used for character name table. readLitChar. readOct.fromEnum ’a’ + 10  c >= ’A’ && c <= ’F’ = fromEnum c ... LIBRARY CHAR 197 19.fromEnum ’0’  c >= ’a’ && c <= ’f’ = fromEnum c .’z’ isUpper c  isLower c c >= ’0’ && c <= ’9’ c >= ’0’ && c <= ’7’ isDigit c  c >= ’A’ && c <= ’F’  c >= ’a’ && c <= ’f’ primUnicodeIsAlphaNum .Source of primitive Unicode functions. isDigit. isOctDigit. toLower.fromEnum ’A’ + 10  otherwise = error "Char.Charactertesting operations isAscii. showLitChar. isDigit. isHexDigit.19. isSpace. isSpace. isLower. intToDigit.’Z’ . digitToInt. isOctDigit. isLower.
ord ’@’).t) <.s)] readEsc readEsc readEsc readEsc readEsc readEsc readEsc readEsc readEsc readEsc readEsc readEsc readEsc readEsc readEsc readEsc :: ReadS Char (’a’:s) = [(’\a’.s)] (’\’’:s) = [(’\’’.readOct s] (’x’:s) = [(chr n.t) <.s)] (’t’:s) = [(’\t’.s’) <.s)] (’f’:s) = [(’\f’.Character code functions ord :: Char > Int ord = fromEnum chr chr :: Int > Char = toEnum .s)] (’b’:s) = [(’\b’.10) error "Char.s)] (’n’:s) = [(’\n’.s)] (’\\’:s) = [(’\\’.s)] (’v’:s) = [(’\v’.t) <.Text functions readLitChar :: ReadS Char readLitChar (’\\’:s) = readEsc s readLitChar (c:s) = [(c. t)  (n.ys) readEsc match match (x:xs) (y:ys)  x == y match xs ys . ([].s)] (’ˆ’:c:s)  c >= ’@’ && c <= ’_’ = [(chr (ord c . CHARACTER UTILITIES toEnum (fromEnum ’0’ + i) toEnum (fromEnum ’a’ + i .s’)  (c.s)] (’"’:s) = [(’"’.Casechanging operations toUpper :: Char > Char toUpper = primUnicodeToUpper toLower :: Char > Char toLower = primUnicodeToLower . mne) <. t)  (n.s)] (’r’:s) = [(’\r’.[a]) = match xs ys = (xs.readHex s] s@(c:_)  isUpper c = let table = (’\DEL’. "DEL") : assocs asciiTab in case [(c. t)  (n.intToDigit: not a digit" .readDec s] (’o’:s) = [(chr n.[match mne s]] of (pr:_) > [pr] [] > [] _ = [] :: (Eq a) => [a] > [a] > ([a].table. s)] s@(d:_)  isDigit d = [(chr n.198 intToDigit :: Int > Char intToDigit i  i >= 0 && i <= 9 =  i >= 10 && i <= 15 =  otherwise = CHAPTER 19.
’ ’) ["NUL". "SI". protectEsc isDigit (shows (ord c)) showLitChar ’\DEL’ = showString "\\DEL" showLitChar ’\\’ = showString "\\\\" showLitChar c  c >= ’ ’ = showChar c showLitChar ’\a’ = showString "\\a" showLitChar ’\b’ = showString "\\b" showLitChar ’\f’ = showString "\\f" showLitChar ’\n’ = showString "\\n" showLitChar ’\r’ = showString "\\r" showLitChar ’\t’ = showString "\\t" showLitChar ’\v’ = showString "\\v" showLitChar ’\SO’ = protectEsc (== ’H’) (showString "\\SO") showLitChar c = showString (’\\’ : asciiTab!c) protectEsc p f = f . cont where cont cont asciiTab = listArray (’\NUL’.c]. "CAN". s) lexLitChar (c:s) lexLitChar "" = = [([c]. "ENQ". "NAK". lexEsc s@(c:_)  isUpper c = [span isCharName s] lexEsc _ = [] isCharName c = isUpper c  isDigit c prefix c (t. "DC4".Numeric escapes lexEsc (’o’:s) = [prefix ’o’ (span isOctDigit s)] lexEsc (’x’:s) = [prefix ’x’ (span isHexDigit s)] lexEsc s@(d:_)  isDigit d = [span isDigit s] . "ETX". "SO".Very crude approximation to \XYZ. "SOH". "US".s)] . "EM". "FS". "DLE". "GS". "ACK". "CR".s) = (c:t.s)] lexEsc (’ˆ’:c:s)  c >= ’@’ && c <= ’_’ = [([’ˆ’. LIBRARY CHAR showLitChar :: Char > ShowS showLitChar c  c > ’\DEL’ = showChar ’\\’ .s)] [] . "DC1". "LF". "STX".1. "DC3". "BEL". "DC2". "SUB". "SYN". "FF". "SP"] s@(c:_)  p c = "\\&" ++ s s = s "EOT". "RS". 199 lexLitChar :: ReadS String lexLitChar (’\\’:s) = map (prefix ’\\’) (lexEsc s) where lexEsc (c:s)  c ‘elem‘ "abfnrtv\\\"’" = [([c]. "BS". "VT". "HT".19. "ETB". "ESC".
200 CHAPTER 19. CHARACTER UTILITIES .
201 .
msum. filterM. zipWithM. liftM3. > m c) > [a] > [b] > > m c) > [a] > [b] > > m a) > a > [b] > m Bool) > [a] > m [a] [c]) m [c] m () a :: MonadPlus m => [m a] > m a :: Monad m => (a > b) > (m a > m b) :: Monad m => (a > b > c) > (m a > m b :: Monad m => (a > b > c > d) > (m a > m b > m c > m d) :: Monad m => (a > b > c > d > e) > (m a > m b > m c > m d > :: Monad m => (a > b > c > d > e > f) (m a > m b > m c > m d > > m c) m e) > m e > m f) . ap. . liftM. unless. ) where class Monad m => MonadPlus m where mzero :: m a mplus :: m a > m a > m a join guard when unless ap mapAndUnzipM zipWithM zipWithM_ foldM filterM msum liftM liftM2 liftM3 liftM4 liftM5 :: :: :: :: :: :: :: :: :: :: Monad m => m (m a) > m a MonadPlus m => Bool > m () Monad m => Bool > m () > m () Monad m => Bool > m () > m () Monad m => m (a > b) > m a > m b Monad Monad Monad Monad Monad m m m m m => => => => => (a (a (a (a (a > > > > > m b b b m (b. join. liftM4. liftM2. guard. (>>). MONAD UTILITIES Chapter 20 Monad Utilities module Monad ( MonadPlus(mzero.202 CHAPTER 20. sequence. mapM. return. liftM5. sequence_. fail).and what the Prelude exports Monad((>>=).c)) > [a] > m ([b]. foldM. when... mapAndUnzipM.. Functor(fmap). zipWithM_. (=<<). mplus). mapM_.
for example.20.1 Naming conventions The functions in this library use the following naming conventions: A postﬁx “M” always stands for a function in the Kleisli category: m is added to function results (modulo currying) and nowhere else. for example: sum :: Num a => [a] > a msum :: MonadPlus m => [m a] > m a 20. Thus (in the Prelude): sequence :: Monad m => [m a] > m [a] sequence_ :: Monad m => [m a] > m () A preﬁx “m” generalises an existing function to a monadic form. NAMING CONVENTIONS 203 The Monad library deﬁnes the MonadPlus class. Thus. So. Lists and the Maybe type are instances of MonadPlus. and provides some useful operations on monads.2 Class MonadPlus The MonadPlus class is deﬁned as follows: class Monad m => MonadPlus m where mzero :: m a mplus :: m a > m a > m a The class methods mzero and mplus are the zero and plus of the monad. 20.1. filter :: (a > Bool) > [a] > [a] filterM :: Monad m => (a > m Bool) > [a] > m [a] A postﬁx “_” changes the result type from (m a) to (m ()). thus: instance MonadPlus Maybe where mzero = Nothing Nothing ‘mplus‘ ys = ys xs ‘mplus‘ ys = xs instance MonadPlus [] mzero = [] mplus = (++) where .
xm ] == do a2 <.3] liftM2 (+) (Just 1) Nothing = Nothing In many situations.2. liftM2 (+) [0. The when and unless functions provide conditional execution of monadic expressions.] (lines cts) The foldM function is analogous to foldl. except that its result is encapsulated in a monad. The function arguments are scanned left to right... putStr ": ".f a2 x2 . It is used to remove one level of monadic structure.3 Functions The join function is the conventional monad join operator. projecting its bound argument into the outer level. foldM f a1 [x1. putStrLn line) [1. preﬁxing each line with its line number.204 CHAPTER 20. Note that foldM works from lefttoright over the list arguments. This function is mainly used with complicated data structures or a statetransforming monad.f a1 x1 a3 <.2] = [0... f am xm If righttoleft evaluation is required. This could be an issue where (>>) and the “folded function” are not commutative. returning the result as a pair of lists. For example.readFile nm zipWithM_ (\i line > do putStr (show i). x2. For instance the following function displays a ﬁle. For example.1] [0. the liftM operations can be replaced by uses of ap. when debug (putStr "Debugging\n") will output the string "Debugging\n" if the Boolean value debug is True.. and otherwise do nothing. the input list should be reversed. listFile :: String > IO () listFile nm = do cts <. .1. The monadic lifting operators promote a function to a monad. MONAD UTILITIES 20. which promotes function application. The mapAndUnzipM function maps its ﬁrst argument over a list.. . The zipWithM function generalises zipWith to arbitrary monads.
20. xn 205 ...3. FUNCTIONS return f ‘ap‘ x1 ‘ap‘ ... ‘ap‘ xn is equivalent to liftMn f x1 x2 .
.. mapM. zipWithM. foldM. liftM3. liftM5. filterM.The MonadPlus class definition class (Monad m) => MonadPlus m mzero :: m a mplus :: m a > m a > m a .Functions msum msum xs join join x when when p s unless unless p s ap ap guard guard p :: MonadPlus m => [m a] > m a = foldr mplus mzero xs :: (Monad m) => m (m a) > m a = x >>= id :: (Monad m) => Bool > m () > m () = if p then s else return () :: (Monad m) => Bool > m () > m () = when (not p) s :: (Monad m) => m (a > b) > m a > m b = liftM2 ($) :: MonadPlus m => Bool > m () = if p then return () else mzero = = ys xs where where mapAndUnzipM :: (Monad m) => (a > m (b. fail). guard. [c]) mapAndUnzipM f xs = sequence (map f xs) >>= return .and what the Prelude exports Monad((>>=).Instances of MonadPlus instance MonadPlus Maybe where mzero = Nothing Nothing ‘mplus‘ ys xs ‘mplus‘ ys instance MonadPlus [] mzero = [] mplus = (++) .4 Library Monad module Monad ( MonadPlus(mzero. sequence_. liftM2. .c)) > [a] > m ([b]. ap. Functor(fmap).206 CHAPTER 20. unzip . mapAndUnzipM. sequence. return. unless. mplus). liftM. liftM4. when. (=<<). ) where . mapM_. (>>). MONAD UTILITIES 20.. zipWithM_. join. msum.
a.a. e’ <.20.b. return (f a’ b’ c’ d’) } :: (Monad m) => (a > b > c > d > e > f) > (m a > m b > m c > m d > m e > m f) = \a b c d e > do { a’ <. LIBRARY MONAD 207 zipWithM :: (Monad m) => (a > b > m c) > [a] > [b] > m [c] zipWithM f xs ys = sequence (zipWith f xs ys) zipWithM_ :: (Monad m) => (a > b > m c) > [a] > [b] > m () zipWithM_ f xs ys = sequence_ (zipWith f xs ys) foldM :: (Monad m) => (a > b > m a) > a > [b] > m a foldM f a [] = return a foldM f a (x:xs) = f a x >>= \ y > foldM f y xs filterM :: Monad m => (a > m Bool) > [a] > m [a] filterM p [] = return [] filterM p (x:xs) = do { b <.filterM p xs. b’ <.a.c. return (if b then (x:ys) else ys) } liftM liftM f liftM2 liftM2 f liftM3 liftM3 f liftM4 liftM4 f liftM5 liftM5 f :: (Monad m) => (a > b) > (m a > m b) = \a > do { a’ <.a.b.d. return (f a’ b’ c’) } :: (Monad m) => (a > b > c > d > e) > (m a > m b > m c > m d > m e) = \a b c d > do { a’ <.b. d’ <.p x. ys <. b’ <.c. return (f a’ b’) } :: (Monad m) => (a > b > c > d) > (m a > m b > m c > m d) = \a b c > do { a’ <.b. b’ <. c’ <. b’ <. return (f a’ b’ c’ d’ e’) } . return (f a’) } :: (Monad m) => (a > b > c) > (m a > m b > m c) = \a b > do { a’ <. d’ <. c’ <.a.e.d. c’ <.4.c.
MONAD UTILITIES .208 CHAPTER 20.
209 .
isFullError. getLine.implementationdependent data SeekMode ReadMode  WriteMode  AppendMode  ReadWriteMode deriving (Eq. hIsWritable.ReadWriteMode). instance Eq Handle where .SeekFromEnd). isEOF. Show) NoBuffering  LineBuffering BlockBuffering (Maybe Int) deriving (Eq. Ix. INPUT/OUTPUT Chapter 21 Input/Output module IO ( Handle. hGetBuffering.. FilePath. hGetContents. ioError. Enum. Show) stdin. hPutChar. bracket_. stderr. stdout. writeFile. hIsReadable. BufferMode(NoBuffering. stderr :: Handle openFile hClose :: FilePath > IOMode > IO Handle :: Handle > IO () . Bounded. hLookAhead. putChar. Ord. readLn ) where import Ix(Ix) data Handle = . isAlreadyExistsError. userError. hIsSeekable. Ix. hGetLine.AppendMode. stdin.. Ord.. readFile.. interact. print.implementationdependent . catch. Read. isIllegalOperation. hSeek.. hWaitForInput. Read. instance Show HandlePosn where data IOMode data BufferMode = =  = . Enum.. try.WriteMode. appendFile.and what the Prelude exports IO. ioeGetHandle. IOError. readIO.. instance Show Handle where . hFlush. hPutStr. hPutStrLn.implementationdependent . isUserError. IOMode(ReadMode. hIsClosed. HandlePosn. . bracket. hIsOpen. hSetPosn. isPermissionError. hGetChar. Show) AbsoluteSeek  RelativeSeek  SeekFromEnd deriving (Eq. hIsEOF.210 CHAPTER 21. putStrLn.. hGetPosn. getContents.. openFile. Read. hFileSize. ioeGetErrorString.. getChar.RelativeSeek. Bounded. putStr.. stdout. ioeGetFileName. hSetBuffering. isEOFError. hPrint. data HandlePosn = . isDoesNotExistError. isAlreadyInUseError. hReady. instance Eq HandlePosn where . SeekMode(AbsoluteSeek.LineBuffering. hClose.BlockBuffering).implementationdependent .. Ord.
Some related operations on ﬁle systems . Commonly used I/O functions such as print are part of the standard prelude and need not be explicitly imported. This library contain more advanced I/O features.211 hFileSize hIsEOF isEOF isEOF hSetBuffering hGetBuffering hFlush hGetPosn hSetPosn hSeek hWaitForInput hReady hReady h hGetChar hGetLine hLookAhead hGetContents hPutChar hPutStr hPutStrLn hPrint hIsOpen hIsClosed hIsReadable hIsWritable hIsSeekable isAlreadyExistsError isDoesNotExistError isAlreadyInUseError isFullError isEOFError isIllegalOperation isPermissionError isUserError ioeGetErrorString ioeGetHandle ioeGetFileName try bracket bracket_ :: :: :: = :: :: :: :: :: :: :: :: = :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: Handle > IO Integer Handle > IO Bool IO Bool hIsEOF stdin Handle > BufferMode > IO () Handle > IO BufferMode Handle > IO () Handle > IO HandlePosn HandlePosn > IO () Handle > SeekMode > Integer > IO () Handle > Int > IO Bool Handle > IO Bool hWaitForInput h 0 Handle > IO Char Handle > IO String Handle > IO Char Handle > IO String Handle > Char > IO () Handle > String > IO () Handle > String > IO () Show a => Handle > a > IO () Handle Handle Handle Handle Handle > > > > > IO IO IO IO IO Bool Bool Bool Bool Bool IOError IOError IOError IOError IOError IOError IOError IOError > > > > > > > > Bool Bool Bool Bool Bool Bool Bool Bool :: IOError > String :: IOError > Maybe Handle :: IOError > Maybe FilePath :: IO a > IO (Either IOError a) :: IO a > (a > IO b) > (a > IO c) > IO c :: IO a > (a > IO b) > IO c > IO c The monadic I/O system used in Haskell is described by the Haskell language report.
the library provides functions to interrogate and construct values in IOError: isAlreadyExistsError – the operation failed because one of its arguments already exists. opening the same ﬁle twice for writing might give this error). The bracket function captures a common allocate. deallocate idiom in which the deallocation step must occur even in the case of an error during computation. which is already being used (for example.212 are contained in the Directory library. isAlreadyInUseError – the operation failed because one of its arguments is a singleuse resource. This is an abstract type. isPermissionError – the operation failed because the user does not have sufﬁcient operating system privilege to perform that operation. ioeGetFileName which returns Just if the error value refers to ﬁle . Any computation which returns an IO result may fail with isIllegalOperation. the string is implementationdependent.1 I/O Errors Errors of type IOError are used by the I/O monad. INPUT/OUTPUT 21. For “user” errors (those which are raised using fail). and ioeGetErrorString which returns a string. isFullError – the operation failed because the device is full. In some cases. for all other errors. Three additional functions are provided to obtain information about an error value. 4 ¦ ¢ 7 ¦ ¥ 4 ¦ ¢ 7 ¦ ¥ . isUserError – a programmerdeﬁned error value has been raised using fail. compute. the string returned by ioeGetErrorString is the argument that was passed to fail. Additional errors which could be raised by an implementation are listed after the corresponding operation. These are ioeGetHandle which returns Just if the error value refers to handle and Nothing otherwise. This is similar to trycatchﬁnally in Java. In this case it should return isIllegalOperation. isIllegalOperation – the operation is not possible. and False otherwise. isDoesNotExistError – the operation failed because one of its arguments does not exist. and Nothing otherwise. isEOFError – the operation failed because the end of ﬁle has been reached. which is True if its argument is the corresponding kind of error. The try function returns an error in a computation explicitly using the Either type. CHAPTER 21. All these functions return a Bool. an implementation will not be able to distinguish between the possible error causes.
For simplicity.2. whose precise meaning is operating system dependent. Physical ﬁles are persistent. whether the object is seekable. likewise. whether buffering is disabled. although it could in fact be a communication channel. The third (stderr) manages output to the standard error channel. A handle is readable if it manages only input or both input and output. The string produced by showing a handle is system dependent. yielding a handle which can then be used to operate on the contents of that ﬁle.21. it should include enough information to identify the handle for debugging. Each value of this type is a handle: a record used by the Haskell runtime system to manage I/O with ﬁle system objects. Once it is closed it can no longer be used for either input or output. A handle is equal according to == only to itself. any nondirectory ﬁle system object is termed a ﬁle. Most handles will also have a current I/O position indicating where the next input or output operation will occur. closed or semiclosed. Haskell deﬁnes operations to read and write characters from and to ﬁles. whether it is open. no attempt is made to compare the internal state of different handles for equality. A handle has at least the following properties: whether it manages input or output or both. directories may themselves be ﬁle system objects and could be entries in other directories.1 Standard Handles Three handles are allocated during program initialisation. This ﬁle system is a collection of named ﬁle system objects. File and directory names are values of type String. These handles are initially open.2 Files and Handles Haskell interfaces to the external world through an abstract ﬁle system. Files can be opened. Handles are in the Show and Eq classes.2. A handle is open when ﬁrst allocated. . and normally reside on disk. though an implementation cannot reuse its storage while references remain to it. In some implementations. or any other object recognised by the operating system. it is writable if it manages only output or both input and output. or enabled on a line or block basis. which may be organised in directories (see Directory). 21. The ﬁrst two (stdin and stdout) manage input or output from the Haskell program’s standard input or output channel respectively. ordered ﬁles. FILES AND HANDLES 213 21. a buffer (whose length may be zero). represented by values of type Handle.
214
CHAPTER 21. INPUT/OUTPUT
21.2.2 SemiClosed Handles
The operation hGetContents (Section 21.9.4) puts a handle into an intermediate state, semiclosed. In this state, is effectively closed, but items are read from on demand and accumulated in a special list returned by hGetContents . Any operation that fails because a handle is closed, also fails if a handle is semiclosed. The only exception is hClose. A semiclosed handle becomes closed: if hClose is applied to it;
if an I/O error occurs when reading an item from the handle;
or once the entire contents of the handle has been read.
Once a semiclosed handle becomes closed, the contents of the associated list becomes ﬁxed. The contents of this ﬁnal list is only partially speciﬁed: it will contain at least all the items of the stream that were evaluated prior to the handle becoming closed. Any I/O errors encountered while a handle is semiclosed are simply discarded.
21.2.3 File locking
Implementations should enforce as far as possible, at least locally to the Haskell process, multiplereader singlewriter locking on ﬁles. That is, there may either be many handles on the same ﬁle which manage input, or just one handle on the ﬁle which manages output. If any open or semiclosed handle is managing a ﬁle for output, no new handle can be allocated for that ﬁle. If any open or semiclosed handle is managing a ﬁle for input, new handles can only be allocated if they do not manage output. Whether two ﬁles are the same is implementationdependent, but they should normally be the same if they have the same absolute path name and neither has been renamed, for example. Warning: the readFile operation (Section 7.1) holds a semiclosed handle on the ﬁle until the entire contents of the ﬁle have been consumed. It follows that an attempt to write to a ﬁle (using writeFile, for example) that was earlier opened by readFile will usually result in failure with isAlreadyInUseError.
21.3 Opening and Closing Files
21.3.1 Opening Files
Computation openFile allocates and returns a new, open handle to manage the ﬁle . It manages input if is ReadMode, output if is WriteMode or AppendMode, and both input and output if mode is ReadWriteMode.
7
7 ¦
¥
7 ¦
¥
7 ¦
¥
¦
2 4
7 ¦
¥
¦
2 4
7 ¦
7
¥
¦
2 4
21.4. DETERMINING THE SIZE OF A FILE
¦
215
is If the ﬁle does not exist and it is opened for output, it should be created as a new ﬁle. If WriteMode and the ﬁle already exists, then it should be truncated to zero length. Some operating systems delete empty ﬁles, so there is no guarantee that the ﬁle will exist following an openFile with WriteMode unless it is subsequently written to successfully. The handle is positioned at the end of the ﬁle if is AppendMode, and otherwise at the beginning (in which case its internal I/O position is 0). The initial buffer mode is implementationdependent. If openFile fails on a ﬁle opened for output, the ﬁle may still have been created if it did not already exist. Error reporting: the openFile computation may fail with isAlreadyInUseError if the ﬁle is already open and cannot be reopened; isDoesNotExistError if the ﬁle does not exist; or isPermissionError if the user does not have permission to open the ﬁle.
21.3.2 Closing Files
makes handle closed. Before the computation ﬁnishes, if is Computation hClose writable its buffer is ﬂushed as for hFlush. Performing hClose on a handle that has already been closed has no effect; doing so not an error. All other operations on a closed handle will fail. If hClose fails for any reason, any further operations (apart from hClose) on the handle will still fail as if had been successfully closed.
¥ ¥ ¥
21.4 Determining the Size of a File
¥
For a handle in 8bit bytes (
¥
which is attached to a physical ﬁle, hFileSize 0).
returns the size of that ﬁle
21.5 Detecting the End of Input
For a readable handle , computation hIsEOF returns True if no further input can be taken ; for a handle attached to a physical ﬁle this means that the current I/O position is equal from to the length of the ﬁle. Otherwise, it returns False. The computation isEOF is identical, except that it works only on stdin.
¥ ¥
21.6 Buffering Operations
Three kinds of buffering are supported: linebuffering, blockbuffering or nobuffering. These modes have the following effects. For output, items are written out, or ﬂushed, from the internal buffer according to the buffer mode:
7 ¦
2 4
7 ¦
7 ¦
7 ¦
¦
7 ¦
2 4
7 ¦
7 ¦
7 ¦
¥
¦
7 ¦
2 4
¥
216
CHAPTER 21. INPUT/OUTPUT
linebuffering: the entire buffer is ﬂushed whenever a newline is output, the buffer overﬂows, a hFlush is issued, or the handle is closed. blockbuffering: the entire buffer is written out whenever it overﬂows, a hFlush is issued, or the handle is closed.
nobuffering: output is written immediately, and never stored in the buffer.
An implementation is free to ﬂush the buffer more frequently, but not less frequently, than speciﬁed above. The buffer is emptied as soon as it has been written out.
¥
Similarly, input occurs according to the buffer mode for handle
linebuffering: when the buffer for is not empty, the next item is obtained from the buffer; otherwise, when the buffer is empty, characters are read into the buffer until the next newline character is encountered or the buffer is full. No characters are available until the newline character is available or the buffer is full.
¥
blockbuffering: when the buffer for the buffer.
becomes empty, the next block of data is read into
nobuffering: the next input item is read and returned. The hLookAhead operation (Section 21.9.3) implies that even a nobuffered handle may require a onecharacter buffer.
For most implementations, physical ﬁles will normally be blockbuffered and terminals will normally be linebuffered.
¥
If is BlockBuffering , then blockbuffering is enabled if possible. The size of the buffer is items if is Just and is otherwise implementationdependent.
If the buffer mode is changed from BlockBuffering or LineBuffering to NoBuffering, then
¥
if
¥
if
7 ¦
7 ¦
2 4
If
is NoBuffering, then buffering is disabled if possible.
is writable, the buffer is ﬂushed as for hFlush; is not writable, the contents of the buffer is discarded.
¦
§ ©
§ ©
¦
¦
¦
2 4
If
is LineBuffering, linebuffering is enabled if possible.
2 4
¥
Computation hSetBuffering reads and writes.
¦
sets the mode of buffering for handle
7 ¦
7 ¦
.
7 ¦
7 ¦
¥
¦
7 ¦
on subsequent
2 4
21.7. REPOSITIONING HANDLES
217
Error reporting: the hSetBuffering computation may fail with isPermissionError if the handle has already been used for reading or writing and the implementation does not allow the buffering mode to be changed.
¥ ¥
Computation hGetBuffering
returns the current buffering mode for
The default buffering mode when a handle is opened is implementationdependent and may depend on the ﬁle system object which is attached to that handle.
21.6.1 Flushing Buffers
¥
Computation hFlush to the operating system.
¥
causes any items buffered for output in handle
to be sent immediately
Error reporting: the hFlush computation may fail with: isFullError if the device is full; isPermissionError if a system resource limit would be exceeded. It is unspeciﬁed whether the characters in the buffer are discarded or retained under these circumstances.
21.7 Repositioning Handles
21.7.1 Revisiting an I/O Position
returns the current I/O position of as a value of the abstract type Computation hGetPosn HandlePosn. If a call to hGetPosn returns a position , then computation hSetPosn sets the position of to the position it held at the time of the call to hGetPosn. Error reporting: the hSetPosn computation may fail with: isPermissionError if a system resource limit would be exceeded.
21.7.2 Seeking to a new Position
The offset is given in terms of 8bit bytes. If is block or linebuffered, then seeking to a position which is not in the current buffer will ﬁrst cause any items in the output buffer to be written to the device, and then cause the input buffer
¥
§
¥
SeekFromEnd: the position of
is set to offset from the end of the ﬁle.
§
7 ¦
¥
RelativeSeek: the position of
is set to offset from the current position.
§
7 ¦
¥
AbsoluteSeek: the position of
is set to .
2 4
2 4
¥
7 ¦
§
2 4
¥
Computation hSeek
sets the position of handle
depending on
. If
¡
¦
¦
7 ¦
7 ¦
7 ¦
¥
7 ¦
¡
¥
7 ¦
.
¦
7 ¦
¥
7 ¦
7 ¦
¥
is:
7 ¦
218
CHAPTER 21. INPUT/OUTPUT
to be discarded. Some handles may not be seekable (see hIsSeekable), or only support a subset of the possible positioning operations (for instance, it may only be possible to seek to the end of a tape, or to a positive offset from the beginning or current position). It is not possible to set a negative I/O position, or for a physical ﬁle, an I/O position beyond the current endofﬁle. Error reporting: the hSeek computation may fail with: isPermissionError if a system resource limit would be exceeded.
21.8 Handle Properties
The functions hIsOpen, hIsClosed, hIsReadable, hIsWritable and hIsSeekable return information about the properties of a handle. Each of these returns True if the handle has the speciﬁed property, and False otherwise.
21.9 Text Input and Output
Here we deﬁne a standard set of input operations for reading characters and strings from text ﬁles, using handles. Many of these functions are generalizations of Prelude functions. I/O in the Prelude generally uses stdin and stdout; here, handles are explicitly speciﬁed by the I/O operation.
21.9.1 Checking for Input
Computation hWaitForInput waits until input is available on handle . It returns True as soon as input is available on , or False if no input is available within milliseconds.
¥
Computation hReady .
indicates whether at least one item is available for input from handle
Error reporting: the hWaitForInput and hReady computations fail with isEOFError if the end of ﬁle has been reached.
21.9.2 Reading Input
¥ ¥
Computation hGetChar
reads a character from the ﬁle or channel managed by
Error reporting: the hGetChar computation fails with isEOFError if the end of ﬁle has been reached. The hGetLine computation fails with isEOFError if the end of ﬁle is encountered when reading the ﬁrst character of the line. If hGetLine encounters endofﬁle at any other point while reading in a line, it is treated as a line terminator and the (partial) line is returned.
¥
Computation hGetLine reads a line from the ﬁle or channel managed by getLine is a shorthand for hGetLine stdin.
¥
. The Prelude’s
7 ¦
7 ¦
7 ¦
¥
§
§
7 ¦
7¥ ¦
¥
7 ¦
7 ¦
7 ¦
7 ¦
¥
.
1 Summing Two Numbers This program reads and sums two Integers. 21. which is made semiclosed. Computation hPrint writes the string representation of and appends a newline. Error reporting: the hGetContents computation may fail with: isEOFError if the end of ﬁle has been reached. 7 ¦ 7 ¦ 7 ¦ 7 ¦ ¥ 7 ¦ ¥ 7 ¦ 7 ¦ ¥ without removing it 7 ¦ § . ¥ Error reporting: the hLookAhead computation may fail with: isEOFError if the end of ﬁle has been reached. or isPermissionError if another system resource limit would be exceeded.3 Reading Ahead ¥ Computation hLookAhead returns the next character from handle from the input buffer.10.9.4 Reading The Entire Input 7 ¦ Computation hGetContents of the channel or ﬁle managed by ¥ returns the list of characters corresponding to the unread portion . ¥ © © ¥ Computation hPutStr ¥ writes the string to the ﬁle or channel managed by § . EXAMPLES 219 21. 21.10.9. 21. blocking until a character is available.21. hPutStr and hPrint computations may fail with: isFullError if the device is full.9. Char 7 ¦ 7 ¦ ¥ .10 Examples Here are some simple examples to illustrate Haskell I/O.5 Text Output ¥ writes the character to the ﬁle or channel managed by Computation hPutChar acters may be buffered if buffering is enabled for . the ﬁle or channel managed by given by the shows function to Error reporting: the hPutChar. 21.
f2] <. This program will not allow a ﬁle to be copied to itself.220 import IO CHAPTER 21.Providing a type signature avoids reliance on . INPUT/OUTPUT main = do hSetBuffering stdout NoBuffering putStr "Enter an integer: " x1 <. This version uses characterlevel I/O.x2 readNum = readLn 21.hGetChar h1 hPutChar h2 (toUpper c) copyFile h1 h2 An equivalent but much shorter version.hIsEOF h1 if eof then return () else do c <.getArgs h1 <.the defaulting rule to fix the type of x1.readNum putStr "Enter another integer: " x2 <. import IO import System import Char( toUpper ) main = do [f1.10.2 Copying Files A simple program to create a copy of a ﬁle. with all lowercase characters translated to uppercase.openFile f2 WriteMode copyFile h1 h2 hClose h1 hClose h2 copyFile h1 h2 = do eof <.readNum putStr ("Their sum is " ++ show (x1+x2) ++ "\n") where readNum :: IO Integer . using string I/O is: .openFile f1 ReadMode h2 <. Note that exactly two arguments must be supplied to the program.
try m after x case rs of Right r > return r Left e > ioError e .f return (Right r)) (return .before rs <.Just provide an implementation of the systemindependent . try try f :: IO a > IO (Either IOError a) = catch (do r <.before rs <.11.readFile f1 writeFile f2 (map toUpper s) 221 21.try (m x) after x case rs of Right r > return r Left e > ioError e .export list omitted } where .21.f2] <.11 Library IO module IO {.getArgs s <. LIBRARY IO import System import Char( toUpper ) main = do [f1.actions that IO exports.variant of the above where middle computation doesn’t want x bracket_ :: IO a > (a > IO b) > IO c > IO c bracket_ before after m = do x <. Left) bracket :: IO a > (a > IO b) > (a > IO c) > IO c bracket before after m = do x <.
INPUT/OUTPUT .222 CHAPTER 21.
223 .
removeDirectory.. doesDirectoryExist. writable.. ... getPermissions. executable. createDirectory. setCurrentDirectory. executable..224 CHAPTER 22. renameDirectory. getCurrentDirectory. getDirectoryContents. setPermissions. . DIRECTORY FUNCTIONS Chapter 22 Directory Functions module Directory ( Permissions( Permissions. > > > > > IO () IO () IO () FilePath > IO () FilePath > IO () createDirectory removeDirectory removeFile renameDirectory renameFile getDirectoryContents getCurrentDirectory setCurrentDirectory doesFileExist doesDirectoryExist getPermissions setPermissions getModificationTime :: :: :: :: :: FilePath FilePath FilePath FilePath FilePath :: FilePath > IO [FilePath] :: IO FilePath :: FilePath > IO () :: FilePath > IO Bool :: FilePath > IO Bool :: FilePath > IO Permissions :: FilePath > Permissions > IO () :: FilePath > IO ClockTime . getModificationTime ) where import Time ( ClockTime ) data Permissions = Permissions { readable. searchable ). . searchable :: Bool } instance instance instance instance Eq Ord Read Show Permissions Permissions Permissions Permissions where where where where . readable.. renameFile. removeFile.. doesFileExist.. writable.
If the directory already exists. however. Computation renameFile changes the name of an existing ﬁle system object from to . Neither path ¦ ¦ 7 7 2 2 7 7 ¦ 7 2 ¦ 7 ¤§ 2 ¦ ¤§ creates a new directory Computation createDirectory near to empty as the operating system allows. In some operating systems.. Error reporting.” under POSIX).). removes an existing directory . it is removed as if by removeDirectory. considered to form part of the directory contents. A conformant implementation need not support renaming directories in all situations (for instance. inaccessible. removal of the root directory). renaming to an existing directory. The implementation Computation removeDirectory may specify additional constraints which must be satisﬁed before a directory can be removed (for instance. If the object already exists. it is atomically replaced by the object. each of which is a named reference to a ﬁle system object (ﬁle. but all such entries are considered to form part of the directory contents. in particular. the directory has to be empty. Note that. removes the directory entry for an existing ﬁle . It is not legal for an implementation to partially remove a directory unless the entire directory is removed. A conformant implementation need not support directory removal in all situations (for instance. it may also be possible to have paths which are relative to the current directory. Each ﬁle system object is referenced by a path. or may not be in use by other processes). or isDoesNotExistError if the new directory’s parent does not exist. or have some administrative function (for instance. all other permissible errors are described below. The createDirectory computation may fail with: isPermissionError if the user is not permitted to create the directory. it is atomically replaced by the directory. if an implementation does not support an operation it should raise an isIllegalOperation.” or “. The removeDirectory and removeFile computations may fail with: isPermissionError if the user is not permitted to remove the ﬁle/directory. this library does not distinguish between physical ﬁles and other nondirectory objects. but the constraints must be documented.1. or as £ ¦ ¦ ¦ 7 7 7 2 2 £ £ ¦ ¦ £ £ ¦ ¦ £ ¦ . “. If the directory is neither the directory nor an alias of the directory. There is normally at least one absolute path to each ﬁle system object. where is Computation removeFile not itself a directory. Some entries may be hidden. Any Directory operation could raise an isIllegalOperation. The implementation may specify additional constraints which must be satisﬁed before a ﬁle can be removed (for instance. Entries in subdirectories are not. Computation renameDirectory changes the name of an existing directory from to . directory etc. A directory contains a series of entries. ¦ ¦ 7 2 £ ¦ ¤§ ¦ ¤§ 7 ¦ 2 ¦ which is initially empty. Error reporting. or across different physical devices). or isDoesNotExistError if the ﬁle/directory does not exist. as described in Section 21. the ﬁle may not be in use by other processes). isAlreadyExistsError if the directory already exists.225 These functions operate on directories in the ﬁle system. Although there may be ﬁle system objects other than ﬁles and directories. All such objects should therefore be treated as if they are ﬁles.
or if either argument to renameFile is a directory. but the constraints must be documented. Note that to change some. The getDirectoryContents and getCurrentDirectory computations may fail with: isPermissionError if the user is not permitted to access the directory. Each entry in the changes . If the operating system has a notion of current directories. or isDoesNotExistError if the ﬁle/directory does not exist. and for ﬁles the searchable ﬁeld will be False. getPermissions and setPermissions get and set these permissions.226 CHAPTER 22. respectively. the executable ﬁeld will be False. or isDoesNotExistError if the directory does not exist. and False otherwise. and False otherwise. Note that directories may be searchable without being readable. The getModificationTime operation returns the clock time at which the ﬁle/directory was last modiﬁed. getCurrentDirectory returns an absolute path to the current directory of the calling process. makeReadable f = do p <. but not to examine the directory contents. but not all permissions. doesFile(Directory)Exist. Error reporting. not as an absolute path. Error reporting. a construct on the following lines must be used. renaming across different physical devices). Error reporting. if permission has been given to use them as part of a path. ¦ ¦ . The operation doesFileExist returns True if the argument ﬁle exists and is not a directory. A conformant implementation need not support renaming ﬁles in all situations (for instance. setCurrentDirectory the current directory of the calling process to . or isDoesNotExistError if the directory does not exist. Error reporting.getPermissions f setPermissions f (p {readable = True}) The operation doesDirectoryExist returns True if the argument ﬁle exists and is a directory. Permissions apply both to ﬁles and directories. and getModificationTime may fail with: isPermissionError if the user is not permitted to access the appropriate information. The Permissions type is used to record whether certain operations are permissible on a ﬁle/directory. or isDoesNotExistError if the ﬁle/directory ¤§ If the operating system has a notion of current directories. get(set)Permissions. DIRECTORY FUNCTIONS may refer to an existing directory. The renameDirectory and renameFile computations may fail with: isPermissionError if the user is not permitted to rename the ﬁle/directory. ¦ ¤§ ¤§ ¤§ ¤§ ¦ ¦ Computation getDirectoryContents returned list is named relative to the directory returns a list of all entries in . For directories. setCurrentDirectory may fail with: isPermissionError if the user is not permitted to change directory to that speciﬁed.
. or isDoesNotExistError if the ﬁle/directory does not exist.227 does not exist. The setPermissions computation may also fail with: isPermissionError if the user is not permitted to change the permission for the speciﬁed ﬁle or directory.
DIRECTORY FUNCTIONS .228 CHAPTER 22.
Any System operation could raise an isIllegalOperation. 0 on a POSIXcompliant system). In particular. Read. some values of may be prohibited (for instance. getProgName. Note that. If variable is undeﬁned.Chapter 23 System Functions module System ( ExitCode(ExitSuccess. exitWith. exitFailure ) where data ExitCode = ExitSuccess  ExitFailure Int deriving (Eq. in particular. ExitSuccess indicates successful termination. all other permissible errors are described below. Computation getProgName returns the name of the program as it was invoked. getArgs. The exact interpretation of is operatingsystem dependent. the isDoesNotExistError exception is raised. The ExitCode type deﬁnes the exit codes that a program can return. if an implementation does not support an operation it must raise an isIllegalOperation. Computation getArgs returns a list of the program’s command line arguments (not including the program name). Computation getEnv returns the value of the environment variable . as described in Section 21. and ExitFailure indicates program failure with value . 229 ¤ ¢ ¦ ¦ 2 2 ¤ ¢ ¦ 2 ¤ ¢ ¦ 2 . Show) getArgs getProgName getEnv system exitWith exitFailure :: :: :: :: :: :: IO [String] IO String String > IO String String > IO ExitCode ExitCode > IO a IO a This library describes the interaction of the program with the operating system. getEnv.ExitFailure). system. Ord.1.
exitWith bypasses the error handling in the I/O monad and cannot be intercepted by catch. Otherwise. and ExitFailure to mean that the program encountered a problem from which it ). if any program terminates without calling exitWith explicitly. any open or semiclosed handles are ﬁrst closed. but the program should return ExitSuccess to mean normal completion. could not recover. The caller may interpret the return code as it wishes. SYSTEM FUNCTIONS ¦ ¦ Computation exitWith terminates the program. it is treated identically to the computation ( >> exitWith ExitSuccess) ‘catch‘ \ _ > exitFailure 7 ¢ § 0 § § S ¢ ¦ 2 ¦ 2 4 Computation system the command . returning to the program’s caller. The value exitFailure is equal to exitWith (ExitFailure where is implementationdependent. If a program terminates as a result of calling error or because its value is otherwise determined to be . Before the program terminates. ¦ returns the exit code produced when the operating system processes 4 7 ¢ § 0 § § S ¢ ¡ ¡ .230 CHAPTER 23. then it is treated identically to the computation exitFailure.
231 .
February. July.Wednesday.Monday. TimeDiff(TimeDiff. ctYDay. getClockTime.. ctTZName.Saturday).Implementationdependent data Month = January  February  March  April  May  June  July  August  September  October  November  December deriving (Eq. instance Eq ClockTime where . ctMin. Integer. Month(January. Ord. Ord. ctTZ.October. ctSec. toUTCTime. CalendarTime(CalendarTime. ctPicosec. diffClockTimes. Ix. Ord. ctHour.August. tdPicosec). formatCalendarTime ) where import Ix(Ix) data ClockTime = . Bool data CalendarTime = CalendarTime { ctYear ctMonth ctDay. tdYear.. DATES AND TIMES Chapter 24 Dates and Times module Time ( ClockTime. ctHour. Show) data Day = Sunday  Monday  Tuesday  Wednesday  Thursday  Friday  Saturday deriving (Eq. Bounded.. toClockTime. Month. Int.September. Day. tdMin.May.December).Friday. Read. ctMin. Read.. Read. Ix. tdPicosec :: Integer } deriving (Eq.April. tdMonth. tdSec. Show) :: :: :: :: :: :: :: :: :: Int. ctWDay. Ord. ctDay. Day(Sunday.. Show) .. Int. ctSec ctPicosec ctWDay ctYDay ctTZName ctTZ ctIsDST } deriving (Eq. Read. ctMonth. ctYear. . tdHour. toCalendarTime. Int.Tuesday.June. ctIsDST). tdSec :: Int. Enum.March. tdMonth. instance Ord ClockTime where . tdDay. String.November. Enum. addToClockTime. calendarTimeToString. tdMin. tdHour. Show) data TimeDiff = TimeDiff { tdYear. Bounded. tdDay.232 CHAPTER 24.Thursday.
§ § © S§ ¤ § § § t ¢ £ ¦ ¤ § 8¥¥8 8 8¥¥8 8 ¤ ¢ ¤ £ 8¥¥8 8 8¥¥8 8 8¥¥8 8 8¥¥8 8 8 8 ¥¥8 8 8 ¥¥8 Allows for two Leap Seconds 364 in nonLeap years Variation from UTC in seconds § § ¦ 4 ¢ ¦ E ¡ § .233 . The expression addToClockTime adds a time difference and a clock time to yield a new clock time. The numeric ﬁelds have the following ranges. and False otherwise. including timezone information. ClockTime is an abstract type. The ﬁeld is True if Daylight Savings Time would be in effect. toCalendarTime is in the IO monad. It follows RFC 1129 in its use of Coordinated Universal Time (UTC). The TimeDiff type records the difference between two clock times in a userreadable way. The expression diffClockTimes the difference between two clock times and as a TimeDiff. CalendarTime is a userreadable and manipulable representation of the internal ClockTime type.Functions on times getClockTime :: IO ClockTime addToClockTime diffClockTimes toCalendarTime toUTCTime toClockTime calendarTimeToString formatCalendarTime :: TimeDiff > ClockTime > ClockTime :: ClockTime > ClockTime > TimeDiff :: :: :: :: :: ClockTime > IO CalendarTime ClockTime > CalendarTime CalendarTime > ClockTime CalendarTime > String TimeLocale > String > CalendarTime > String The Time library provides standard functionality for clock times. used for the system’s internal clock time. Clock times may be compared directly or converted to a calendar time CalendarTime for I/O or other manipulations. The returns difference may be either positive or negative. Function getClockTime returns the current time in its internal representation. Function toCalendarTime converts to a local time. Because of this dependence on the local environment. modiﬁed by the timezone and daylight savings time settings in force at the time of conversion. Value ctYear maxInt ctDay 1 ctHour 0 ctMin 0 ctSec 0 ctPicosec 0 ctYDay 0 ctTZ 89999 Range maxInt 31 23 59 61 365 89999 £ Comments PreGregorian dates are inaccurate The ﬁeld is the name of the time zone.
Ord.Monday. tdDay. tdPicosec). ctHour. .May. July.. ctPicosec. diffClockTimes. tdMin.Wednesday. tdSec. CalendarTime(CalendarTime. getClockTime. Bounded. Enum. ctSec.1 Library Time module Time ( ClockTime.March.November.Tuesday. Enum...). Function calendarTimeToString formats calendar times using local conventions and a formatting string. ctYear. Read.August. Month(January. Ix..December).Friday.Implementationdependent data Month = January  February  March  April  May  June  July  August  September  October  November  December deriving (Eq.Thursday.. instance Ord ClockTime where . Bounded. ctMin. Ix. ctMonth. ctTZName.defaultTimeLocale) import Char ( intToDigit ) data ClockTime = . TimeDiff(TimeDiff. addToClockTime. toClockTime.April. . instance Eq ClockTime where . ctTZ. Read. ctDay. and ﬁelds. tdHour. tdMonth.September. ctWDay. Show) data Day = Sunday  Monday  Tuesday  Wednesday  Thursday  Friday  Saturday deriving (Eq. toCalendarTime.234 § CHAPTER 24. ctIsDST). t © S§ 24.. Show) ¢ £ 4 ¢ E ¡ 7 § § ¢ G § 7 ¢ ( § . calendarTimeToString.June. toUTCTime. Ord..February. Day(Sunday. . toClockTime converts into the corresponding internal ClockTime ignoring the contents of the . tdYear. DATES AND TIMES Function toUTCTime converts into a CalendarTime in standard UTC format.Saturday).October. ctYDay. formatCalendarTime ) where import Ix(Ix) import Locale(TimeLocale(.
String. tdHour. Int. tdMonth.. :: ClockTime = . ctHour...Implementationdependent :: CalendarTime > String = formatCalendarTime defaultTimeLocale "%c" . ctSec ctPicosec ctWDay ctYDay ctTZName ctTZ ctIsDST } deriving (Eq. Bool data TimeDiff = TimeDiff { tdYear. Show) 235 :: :: :: :: :: :: :: :: :: Int. .Implementationdependent :: CalendarTime > ClockTime = . Ord. Day. :: ClockTime = . tdMin. tdSec :: Int.Implementationdependent > IO CalendarTime .24. tdPicosec :: Integer } deriving (Eq. Month. :: ClockTime = . ctMin... Int.. LIBRARY TIME data CalendarTime = CalendarTime { ctYear ctMonth ctDay.Implementationdependent :: TimeDiff = .Implementationdependent > CalendarTime . Integer.Implementationdependent > ClockTime > TimeDiff .. Int. . Show) getClockTime getClockTime addToClockTime addToClockTime td ct diffClockTimes diffClockTimes ct1 ct2 toCalendarTime toCalendarTime ct toUTCTime toUTCTime ct toClockTime toClockTime cal calendarTimeToString calendarTimeToString :: IO ClockTime = . Read.. > ClockTime > ClockTime .1. tdDay... Read. Ord...
fromEnum wday) ‘div‘ 7) show (let n = fromEnum wday in if n == 0 then 7 else n) decode ’V’ = let (week. .236 CHAPTER 24. days) = (yday + 7 ..if fromEnum wday > 0 then fromEnum wday .Implementationdependent show2 ((yday + 7 .. DATES AND TIMES formatCalendarTime :: TimeLocale > String > CalendarTime > String formatCalendarTime l fmt ct@(CalendarTime year mon day hour min sec sdec wday yday tzname _ _) = doFmt fmt where doFmt (’%’:c:cs) = decode c ++ doFmt cs doFmt (c:cs) = c : doFmt cs doFmt "" = "" to12 :: Int > Int to12 h = let h’ = h ‘mod‘ 12 in if h’ == 0 then 12 else h’ decode decode decode decode decode decode decode decode decode decode decode decode decode decode decode decode decode decode decode decode decode decode decode decode decode decode decode ’A’ ’a’ ’B’ ’b’ ’h’ ’C’ ’c’ ’D’ ’d’ ’e’ ’H’ ’I’ ’j’ ’k’ ’l’ ’M’ ’m’ ’n’ ’p’ ’R’ ’r’ ’T’ ’t’ ’S’ ’s’ ’U’ ’u’ = = = = = = = = = = = = = = = = = = = = = = = = = = = fst (wDays l !! fromEnum wday) snd (wDays l !! fromEnum wday) fst (months l !! fromEnum mon) snd (months l !! fromEnum mon) snd (months l !! fromEnum mon) show2 (year ‘quot‘ 100) doFmt (dateTimeFmt l) doFmt "%m/%d/%y" show2 day show2’ day show2 hour show2 (to12 hour) show3 yday show2’ hour show2’ (to12 hour) show2 min show2 (fromEnum mon+1) "\n" (if hour < 12 then fst else snd) (amPm l) doFmt "%H:%M" doFmt (time12Fmt l) doFmt "%H:%M:%S" "\t" show2 sec .1 else 6) ‘divMod‘ 7 in show2 (if days >= 4 then .
LIBRARY TIME week+1 else if week == 0 then 53 else week) decode ’W’ = show2 ((yday + 7 . show2’.24. intToDigit (x ‘rem‘ 10)] show2’ x = if x < 10 then [ ’ ’.if fromEnum wday > 0 then fromEnum wday .1. show3 :: Int > String show2 x = [intToDigit (x ‘quot‘ 10). intToDigit x] else show2 x show3 x = intToDigit (x ‘quot‘ 100) : show2 (x ‘rem‘ 100) 237 .1 else 6) ‘div‘ 7) decode ’w’ = show (fromEnum wday) decode ’X’ = doFmt (timeFmt l) decode ’x’ = doFmt (dateFmt l) decode ’Y’ = show year decode ’y’ = show2 (year ‘rem‘ 100) decode ’Z’ = tzname decode ’%’ = "%" decode c = [c] show2.
DATES AND TIMES .238 CHAPTER 24.
Chapter 25 Locale module Locale(TimeLocale(. amPm :: (String. Show) defaultTimeLocale :: TimeLocale full and abbreviated week days full and abbreviated months AM/PM symbols formatting strings The Locale library provides the ability to adapt to local conventions. it supports only time and date information as used by calendarTimeToString from the Time library.. String)]. String)]. defaultTimeLocale) where data TimeLocale = TimeLocale { wDays :: [(String. String). 239 . timeFmt. Ord. time12Fmt :: String } deriving (Eq. At present. months :: [(String. dateTimeFmt. dateFmt.).
240
CHAPTER 25. LOCALE
25.1 Library Locale
module Locale(TimeLocale(..), defaultTimeLocale) where data TimeLocale = TimeLocale { wDays :: [(String, String)], months :: [(String, String)], amPm :: (String, String), dateTimeFmt, dateFmt, timeFmt, time12Fmt :: String } deriving (Eq, Ord, Show) full and abbreviated week days full and abbreviated months AM/PM symbols formatting strings
defaultTimeLocale :: TimeLocale defaultTimeLocale = TimeLocale { wDays = [("Sunday", "Sun"), ("Monday", "Mon"), ("Tuesday", "Tue"), ("Wednesday", "Wed"), ("Thursday", "Thu"), ("Friday", "Fri"), ("Saturday", "Sat")], months = [("January", ("March", ("May", ("July", ("September", ("November", "Jan"), "Mar"), "May"), "Jul"), "Sep"), "Nov"), ("February", ("April", ("June", ("August", ("October", ("December", "Feb"), "Apr"), "Jun"), "Aug"), "Oct"), "Dec")],
amPm = ("AM", "PM"), dateTimeFmt = "%a %b %e %H:%M:%S %Z %Y", dateFmt = "%m/%d/%y", timeFmt = "%H:%M:%S", time12Fmt = "%I:%M:%S %p" }
Chapter 26
CPU Time
module CPUTime ( getCPUTime, cpuTimePrecision ) where getCPUTime cpuTimePrecision :: IO Integer :: Integer
Computation getCPUTime returns the number of picoseconds of CPU time used by the current program. The precision of this result is given by cpuTimePrecision. This is the smallest measurable difference in CPU time that the implementation can record, and is given as an integral number of picoseconds.
241
242
CHAPTER 26. CPU TIME
243
244
CHAPTER 27. RANDOM NUMBERS
Chapter 27
Random Numbers
module Random ( RandomGen(next, split, genRange), StdGen, mkStdGen, Random( random, randomR, randoms, randomRs, randomIO, randomRIO ), getStdRandom, getStdGen, setStdGen, newStdGen ) where  The RandomGen class class RandomGen genRange :: g next :: g split :: g g where > (Int, Int) > (Int, g) > (g, g)
 A standard instance of RandomGen data StdGen = ...  Abstract instance RandomGen StdGen where ... instance Read StdGen where ... instance Show StdGen where ... mkStdGen :: Int > StdGen  The Random class class Random a where randomR :: RandomGen g => (a, a) > g > (a, g) random :: RandomGen g => g > (a, g) randomRs :: RandomGen g => (a, a) > g > [a] randoms :: RandomGen g => g > [a] randomRIO :: (a,a) > IO a randomIO :: IO a instance instance instance instance instance instance Random Random Random Random Random Random Int Integer Float Double Bool Char where where where where where where ... ... ... ... ... ...
 The global random generator newStdGen :: IO StdGen setStdGen :: StdGen > IO () getStdGen :: IO StdGen getStdRandom :: (StdGen > (a, StdGen)) > IO a
without being concerned that the generator returned by (say) next might have a different range to the generator passed to next.27. 27. AND THE STDGEN GENERATOR 245 The Random library deals with the common task of pseudorandom number generation. or to get different results on each run by using the systeminitialised generator. The class RandomGen provides a common interface to such generators. but very little work has been done on statistically robust implementations of split ([1. then .Int) next :: g > (Int. or by supplying a seed from some other source. and a new generator. The class Random provides a way to extract particular values from a random number generator. . g) . The library makes it possible to generate repeatable results. g) split :: g > (g. The library is split into two layers: A core random number generator provides a supply of bits. For example. The split operation allows one to obtain two independent random number generators. ¦ ¡ ¡ . It is required that: The second condition ensures that genRange cannot examine its argument. The next operation returns an Int that is uniformly distributed in the range returned by genRange (including both end points).1.4] are the only examples we know of).1 The RandomGen class. by starting with a speciﬁed initial random number generator.maxBound) The genRange operation yields the range of values returned by the generator. class RandomGen g where genRange :: g > (Int. That in turn allows an implementation to make a single call to genRange to establish a generator’s range.Default method genRange g = (minBound. THE RANDOMGEN CLASS. the Float instance of Random allows one to generate random values of type Float. when passing a random number generator down to recursive calls). This is very useful in functional programs (for example. – genRange – If genRange . and hence the value it returns can be determined only by the instance of RandomGen. and the StdGen generator The class RandomGen provides a common interface to random number generators.
mkStdGen :: Int > StdGen The StgGen instance of RandomGen has a genRange of at least 30 bits. It guarantees to consume only a ﬁnite portion of the string. The result of repeatedly using next should be at least as statistically robust as the “Minimal Standard Random Number Generator” described by [2. Implementations of the above form do not meet the speciﬁcation.3]. Until more is known about implementations of split. Implementation warning. then g1 and g2 should be independent. In general. the read instance of StdGen has the following properties: It guarantees to succeed on any string. The Show/Read instances of StdGen provide a primitive way to save the state of a random number generator. split g = (g. In addition. RANDOM NUMBERS The Random library provides one instance of RandomGen.. of course. all we require is that split deliver generators that are (a) not identical and (b) independently robust in the sense just given. by mapping an Int into a generator. Programmers may. Again...246 CHAPTER 27. .. instance Read StdGen where . The function mkStdGen provides an alternative way of producing an initial generator.. split returns g itself and a new generator derived from g. the abstract data type StdGen: data StdGen = .Abstract instance RandomGen StdGen where . variantOf g) Here. supply their own instances of RandomGen... read may be used to map an arbitrary string (not necessarily one produced by show) onto a value of type StdGen. but in fact they are both equal to variantOf g. Different argument strings are likely to result in different results. instance Show StdGen where . It is required that read (show g) == g.... A superﬁcially attractive implementation of split is instance RandomGen MyGen where . But now consider these two apparentlyindependent generators: g1 = snd (split g) g2 = snd (split (fst (split g))) If split genuinely delivers independent generators (as speciﬁed). distinct arguments should be likely to produce distinct generators. .
a) > IO a randomIO :: IO a .. a) > g > [a] randoms :: RandomGen g => g > [a] randomRIO :: (a. produce an inﬁnite list of random values. . randomIO = getStdRandom random randomRIO range = getStdRandom (randomR range) instance instance instance instance instance instance Random Random Random Random Random Random Int Integer Float Double Bool Char where where where where where where ..g’) = random g randomRs = .. depending on the implementation and the interval. but they may be. random does the same as randomR..2 The Random class With a source of random number supply in hand. For continuous types there is no requirement that the values and are ever produced. – For fractional types. g) randomRs :: RandomGen g => (a. THE RANDOM CLASS 247 27. . but does not take a range. together with a new generator. the range is (arbitrarily) the range of Int.similar. a) > g > (a. – For Integer... and do not return a new generator.... The plural versions. randomRs and randoms. – For bounded types (instances of Bounded.. . . .. the range is normally the whole type. It is unspeciﬁed what happens if .. and returns a random value uniformly distributed in the closed interval .Default methods randoms g = x : randoms g’ where (x. randomR takes a range and a random number generator . g) random :: RandomGen g => g > (a.2. the range is normally the semiclosed interval ¦ ¨ § ¨¥ 2 7 § ¨¥ £ § ¨¥ 2 7 2 7 § ¨¥ 2 7 .27.. the Random class allows the programmer to extract random values of a variety of types: class Random a where randomR :: RandomGen g => (a... .. such as Char).
randomRIO and randomIO. Comm ACM. July 1998. pp8788. for example. [2] SK Park. StdGen)) > IO a getStdGen and setStdGen get and set the global random number generator. . 27. 2(2):203212. It is initialised automatically in some systemdependent fashion. use the global random number generator (see Section 27. getStdRandom uses the supplied function to get a value from the current global random generator. newStdGen applies split to the current global random generator. and returns the other. updates it with one of the results. Comm ACM 31(10). To get deterministic behaviour.sbg. pp8289.good ones are hard to ﬁnd”.ac.248 CHAPTER 27.mat. pp11921201.6)) References [1] FW Burton and RL Page. “Two fast implementations of the minimal standard random number generator”.3 The global random number generator There is a single. and KW Miller. rollDice gets a random integer between 1 and 6: rollDice :: IO Int rollDice = getStdRandom (randomR (1.3). “Random number generators . For example.at/ is a great source of information. global random number generator of type StdGen. or Linux’s kernel random number generator. Journal of Functional Programming. implicit. ACM SIGSIM Simulation Digest 28(1). RANDOM NUMBERS The IO versions. held in some global variable maintained by the IO monad. respectively. “Don’t trust parallel Monte Carlo”. The Web site http://random. Jan 1990. April 1992. setStdGen getStdGen newStdGen getStdRandom :: :: :: :: StdGen > IO () IO StdGen IO StdGen (StdGen > (a. Oct 1988. 33(1). “Distributed random number generation”. [4] P Hellekalek. [3] DG Carta. by using the time of day. and updates the global generator with the new generator returned by the function. use setStdGen.
[11] Unicode Consortium. PrenticeHall International. Texas. Addison Wesley. 1958. Jones. [12] P.. A gentle introduction to Haskell.B.M. Technical Report YALEU/DCS/RR901. pages 248–256. Typing Haskell in Haskell. and J. Peterson. San Francisco. [7] Mark P. Version 3. 5(1). Hindley.. 146:29–60. [9] P. The principal type scheme of an object in combinatory logic. Austin. Haskell Workshop. Englewood Cliffs. Fax´ n A static semantics for Haskell Journal of Functional Programming. September 1981. August 1978. 2000. Albuquerque. e [5] J. January 1982. Co. January 1995.L. CACM. 1987.Bibliography [1] J. Reading. 21(8):613–641. January 1989. Principal values and branch cuts in complex APL. [6] P. Fasel. Jr. Feys. pages 207–212. Jones. [10] S. Principal type schemes for functional programs. In Proceedings of the 9th ACM Symposium on Principles of Programming Languages. May 1996. MA. October 1999. Milner. Combinatory Logic. A system of constructor classes: overloading and implicit higherorder polymorphism. Can programming be liberated from the von Neumann style? A functional style and its algebra of programs. Backus. Curry and R. Penﬁeld. 2002. Journal of Functional Programming. [2] H. J.R. [8] Mark P. Yale University. Wadler and S. Paris. Damas and R. The Implementation of Functional Programming Languages. N. Hudak. In APL ’81 Conference Proceedings. pages 60–76.0. In Proceedings of the 16th ACM Symposium on Principles of Programming Languages. New Jersey. Blott. 249 . [4] KF. The Unicode Standard. [3] L. Transactions of the American Mathematical Society. Peyton Jones. How to make ad hoc polymorphism less ad hoc. NorthHolland Pub. Amsterdam. December 1969.
250 BIBLIOGRAPHY .
91. 177 !!. 84. 9. 79. 12 \b. 84. !. 109 _. 104. 55. 230 ˆ. 206 apat. 80 (. 91. 55. 104. 44. 104.). 31. 153 251 § 7 3¢ §§ ¢ ¦ . 91. 88. 55. 119 alt. 55. Code Index entries that refer to nonterminals in the Haskell syntax are shown in an entities are shown in typewriter font. 142 :. 104. 104. 151. 104. 19 function. 110 $!. 109 ˆˆ. 119 ANYseq. 12 . 129 ap. 104. 175–177 /=. 109 >>=.Index font.. 104. see aspattern [] (nil). 104. 104. 177 accumArray. 104. 155. 82. 187 \. 55. 55. 55. 109 @. 91. 104. 92. 55. 142 >. 153 &&. 66 abs. 233. 97. 104. 139 ambiguous type. 104. 90. 106 acosh. 110 /. 55. 140 appendFile. see function application operator. 55. 88. 104. 139 alts. 82. 139 algebraic datatype. 106 addToClockTime. Ordinary index entries are shown in a roman font. 55. 67. 91. see lambda abstraction \&. 20–23. 81. 106 //. 105. 104. 80 (). 235 aexp. 110 %. 51. 156 ::. 91. 104. 55. 97. 105 AbsoluteSeek. 12 \\. 92. 84. 174. 88. 55. 9. 173. 142 >>. 55. 91. 45. see irrefutable pattern abbreviated module. 25. 104. 214 application. 176. 55. 109 ==. 25. 62 and. 105. 126 AppendMode. 90. 151. 173. 110 (. 105 **. 43. 142 >=. see trivial type and unit expression *. 80 :+. 104. 12 \r. 186. 91.). 116 $. 180. 12 \v. 17. 76 accum.. 84. see also negation . 80 \\. 97. 90. 175. 92. 92. 104. 110 ˜. 115 . 93. 12 \f. 55. 30 <. 104. 141 all. 174. 217 abstract datatype. 129 any. 55. 142 =<<. 81. 55. see operator application approxRational. 81. 173. 202. see also + pattern ++. 91. see wildcard pattern . 12 \n. 55. 55. 9. 55. 55. 177 acos. 79. 119 ANY. 129 any. 142 <=. 173. 90. 16. 91. 182 \a. 115. 106 +. 12 \t.
156 conop. 79. 114 atan. 17. 10. 177 bracket. 25 INDEX catch. 107 changing the directory. 12. 51. 173. 79 literal syntax. 49 clock time. 47. 33 ascDigit. 129 asin. 197. 130 ASCII character set. 110 Char (module). 140 concat. 215 closure. 9. 155. 48 class environment. 12. 9. 130 coercion. see simple pattern binding body. see ASCII character set transparent. 130 conjugate. 40. 39. 121. 176 array. 193. 174. 67 with an empty where part. 173. 156 class. 9 nested. 194 cdecl. see transparent character set charesc. 143 instance for Char. 129 ascii. 129 ascSymbol. 176. 12 character set ASCII. 226 Char (datatype). 137 ceiling. 137 basic input/output. 18. 47. 136 cntrl. 177 aspattern (@). 111 bounds. 9 comment. 156 con. 130 chr. 41 class declaration. 23. 174 Array (module). 110 boolean. 84. 79. 129 closing a ﬁle. 234 closecom. see pattern binding simple pattern. 95 binding. 221 break.252 arithmetic operator. 80 Array (datatype). 195. 12. 9. 38. 90 arithmetic sequence. 104. 31. 9. 91. 137 class assertion. 9. 106 atype. 91. 173 accumulated. 38. 211. 93. 9 endofline. 174 derived. 42 class method. 98. 7 ascLarge. 18. 161. 137 cdecls. 235 calendarTimeToString. 235 case expression. 142 Complex (module). 89. 47. 21 conid. 115 conditional expression. 198 cis. 92. 232 ClockTime (datatype). 38. 155. 129 compare. 234 char. 210 CalendarTime (datatype). 11. 174. 174. 221 bracket_. 115 concatMap. 92. 130 character. 173. 155. 9. 93 comment. 230 catMaybes. 38. 79 Bounded (class). 74 cname. 106 assocs. 211. 105 derived instance. see function binding pattern. 161. 41. 48. 106 atan2. 140 . 66. 93. 195. 47 class. 233. 232. 37 function. 17. 118 btype. 129 ascSmall. 91. 177 asTypeOf. 125. 12. 106 asinh. 136 Bool (datatype). 232. 173. 197 array. 69. 40. 137 BufferMode (datatype). 108 atanh. 91.
180. see also instance declaration deriving. 55. 187 deleting directories. 235 ctHour. 26. 224 Directory (module). 226 curry. 50. 137 declaration. 141. 234 dclass. 43 datatype. 225 deleting ﬁles. 214 ctDay. see data declaration recursive. 195. 184. 104. 58 decls. see default declaration 253 ﬁxity. 80. 118 dropWhile. 9.INDEX const. 24 within an instance declaration. 43. 108 . 110 constr. see class declaration datatype. 174. 232. 240 Day (datatype). 224 Double (datatype). 182. 177 encodeFloat. 240 dateTimeFmt. 93. 241 cpuTimePrecision. 91. 117 dashes. 59 cos. 118 e. 182. 93. 92. 130 context. 47 within a let expression. see ﬁxity declaration import. 91. 51 defaultTimeLocale. 239. 225 creating a ﬁle. 153 dependency analysis. 43. 93 CPU time. 241 createDirectory. 81. 106 do expression. 10. 81. 233. 43 data declaration. see abstract datatype algebraic. 213. 241 CPUTime (module). 111 either. 167 Either (datatype). 163 doesDirectoryExist. 138 decimal. 138 constrs. 182. 224 doesFileExist. vii cycle. 37 class. 56. 224 div. 43. 235 digit. see import declaration instance. 180. 239. 49 declaration group. 38. 51. 38 constructor expression. 41. 186 elems. see data declaration default. 114 Curry. 138 diffClockTimes. 130 decl. 224. 38. 225 denominator. 43. 90. 106 cosine. see instance declaration within a class declaration. 11. 91. 235 ctIsDST. 41 context. 145 default declaration. see recursive datatype renaming. see newtype declaration dateFmt. 180. 106 divMod. 108 default class method. 137 context reduction.. 115. 240 delete. 106 cosh. 48. 151. 180. 180. 129 digitToInt. 187 deleteFirstsBy. 184. 55. 43 abstract. 232. 91. 235 ctMin. 112 drop. 97 doDiv. 137 decodeFloat. 92. 232. see algebraic datatype declaration. 173. 119 elemIndex. 197 directories. 81. 129 data constructor. 239. 232. 27. 40 consym. 186 elemIndices. 235 current directory. 92. Haskell B. 58 derived instance. 138 constructor class. 187 deleteBy. 232. 9. 111 elem. 89.
254 end of ﬁle. 17 error. 108 floatToDigits. 180. 67. 202. 43. 130 even. 65 Enum (class). 44 construction. 215 entity. 94. see type expression unit. 54. 104 derived instance. 229 exitFailure. 66 exports. see unit expression expression typesignature. 28 selection. 81 Eq (class). 21. 92. 15 case. 81. 138 ﬁle. 29 ﬁelddecl. 91 export. 86. 224 execution time. 105 enumFromTo. 28. 108 Floating (class). 182. see label. 170 enumFrom. 162 expts. 229 ExitFailure. 88. 89. 16. 229 EQ. 92. 19. 89. 154 superclass of Integral. 52 expt. 49. 229 . 158 superclass of RealFloat. 186 findIndex. 89. 4. 186 findIndices. 79 fbind. see type environment environment variables. 241 ExitCode (datatype). see simple case expression type. 105 derived instance. 92. 164 ﬁeld label. 113 instance for Float. 111 instance for Double. 207 find. 215 ﬁle system. 86. 17. 27 update. see conditional expression let. 97. 166 ¡ ¢ ¡ . 108 ﬂoating literal pattern. 186 ﬁxity. 114. 18 ﬁxity. 30. 139 exp. 106 enumeration. 229 ExitSuccess. 105 enumFromThenTo. 230 escape. 136 export list. 110 superclass of Num. 105 environment class. 12 floatDigits. 51. 108 exception handling. 109. see case expression conditional. 125 filter. 92. 93. 159. 104 error. 93. 86. 30. 91. 142 instance for Char. 12. 86. 24–26. 112 ﬂoat. 19. 180. 91. 51. 92. 113 instance for Ratio. 137 ﬁxity declaration. 48. 16. 105 enumFromThen. 51. 212 False. 213 FilePath (type synonym). 163 f. 115 filterM. 86. 93. 4. 106 exponent. 139 fexp. 67. 16. 180. 142 instance for Array. 110 Float (datatype). 139 exp. 99. see class environment type. 139 FFFormat (datatype). 33 floatRadix. 106 instance for Complex. 229 exitWith. 54 flip. 177 instance for Char. 105 superclass of Ord. see let expression simple case. 82. 91. 98 executable. 167 fail. 108 exponentiation. 38. 108 floatRange. 213 ﬁle buffering. 136 v INDEX expression.
115 hexadecimal. 229 getChar. 138 gdpat. 244. 9. 140 fpats. 225 getEnv. 189 genRange. 181. 91. 93. 106 fst. 248 graphic. 181. 116 foldl1. 210 HandlePosn (datatype). 49. 109 instance for []. 140 Fractional (class). 229 getStdGen. 86. 181. 162 fromRational. 106 instance for Complex. 181. 87. 138 gap. 54. 248 getStdRandom. 189 genericReplicate. 23. 91. 188 GT. 206 Handle (datatype). 113 instance for Array. 229 getLine. 236 formatRealFloat. 241 getCurrentDirectory. 18. 3 formatCalendarTime. 25. 224 getPermissions. 47. 224. 11. 137 generalization. 129 255 . 139 gdrhs. vii. 3 Haskell kernel. 109. 18. 117 formal semantics. 157 instance for Ratio. 59 generalization preorder. 189 genericIndex. 108 gcon.INDEX floor. 96. 94. 89. 189 genericTake. 87 funlhs. 80. 177 instance for IO. 90. 18. 107 ﬂushing a ﬁle buffer. 92. 25. 194 fromRat. 181. 225 getDirectoryContents. 159. 90. 56. 40. 18 gd. 233. 92. 105 fromIntegral. 23 genericDrop. 207 foldr. 56. 55. 137 guard. 153 superclass of Floating. 114 function. 125 getClockTime. 12. vii Functor (class). 109 fromJust. 31. 183. 125 getCPUTime. 106 superclass of RealFrac. 176 foldl. 140 gconsym. 87. 194 fromMaybe. 210. 4 hClose. 130 hexit. 202. 111 instance for Maybe. 187 groupBy. 129 group. 42 generator. 130 gcd. 217 fmap. 193. 210 handles. 193. 9. 213 Haskell. 105 fromInteger. 107 fromEnum. 40. 244. 56 function type. 81 gtycon. 41 functional language. 38. 92. 181. 81 function binding. 91. 215 head. 31. 224 getProgName. 162 fromRat’. 219 getArgs. 9. 96. 181. 34 guard. 224. 202. 96. 181. 91. 233. 111 functor. 138 gendecl. 18. 117 foldr1. 184. 116 foldM. 190 genericSplitAt. 190 genericLength. 245 get the contents of a ﬁle. 244. 25. 165 formfeed. 125 getModificationTime. 235 getContents. 129 fpat.
197 isDigit. 212 ioError. 218 hSeek. 211. 218 hIsReadable. 181. 181. 169.256 hFileSize. 137 idecls. 193. 219 hGetLine. 174. 125 IOMode (datatype). 218 hGetContents. 215 isEOF. 195. 33. 116 inits. 197 isDoesNotExistError. see conditional expression imagPart. 147 INDEX input/output. 195. 210 input/output examples. 219 hPutStrLn. 70 HindleyMilner type system. 38. 49. 126 intersect. 211. 219 hPutStr. 218 hGetPosn. 197 isIllegalOperation. 211. 211. 211 hReady. 212. 195. 194 . 211. 211. 81. 210. 49 Int (datatype). 211. 112 integer. 138 instance declaration. 214. 136 import. 217 hSetBuffering. 58 hIsClosed. 66. 212. 24. 81. 183. 38. 211. 212 isJust. 69. 171. 214 irrefutable pattern. 137 identiﬁer. 211. 217 hWaitForInput. 215 hFlush. 184. 69 impspec. 212 isFullError. 218 hLookAhead. 181. 177 init. 189 inst. 110 idecl. 218 hIsSeekable. 69. 215 isAscii. 49. 197 isAlreadyExistsError. 195. 183. 218 hIsEOF. 92. 81. 197 isControl. 218 I/O. 169. 219 inRange. 49. 211. 181. 211. 212 IOError (datatype). 181. 218 hIsWritable. 197 isAlphaNum. 98. 106 interact. 184. see also derived instance importing and exporting. 49. 182. 125. 212 ioeGetFileName. 219 hPrint. 156 impdecl. 173. 172 insert. 96. 211. 212 ioeGetHandle. 216 hSetPosn. 71 with an empty where part. 211. 112 Integer (datatype). 187 intToDigit. 217 hiding. 221 ioeGetErrorString. 12 integer literal pattern. 211. 183. 92. 211. 155. 4. 211. 211. 187 intersperse. 211. 211. 181. 211. 211. 211. 69. 89. 215 isEOFError. 211. 211. 188 inlining. 211. 163 Integral (class). 57 isAlpha. 212 isAlreadyInUseError. 216. 34. 136 impdecls. 215 hIsOpen. 195. 210 I/O errors. 211. 9 ifthenelse expression. 91. 188 insertBy. 217 hGetBuffering. 38. 195. 111 IO (module). 211. 210. 211. 212 isHexDigit. 198 IO. 217 hGetChar. 195. 171. 89. 172 indices. 212 id. 50. 211. 211. 187 intersectBy. 211. 136 import declaration. 136 index. 210 IO (datatype). 33 integerLogBase. 219 hPutChar. 211.
81 magnitude. 181. 65 main. 197 isUserError. 176. 139 libraries. 91. 21. 197 isPermissionError. 44. 181. 172 Ix (module). 195. 210. 207 v 257 liftM2. 207 linear pattern. 129 literal pattern. 109 match. 172 instance for Int. 91 logBase. 81 kind. 64 kind inference. 117 Ix (class). 207 liftM3. 197 isSuffixOf. 197 isSpace. 202. 159. 50. 23 lex. 202. 168 lexeme. 197 isLower. 19 large. 177 listToMaybe. 129 lexical structure. 184. 31. 212. 170 instance for Char. 88. 88. 129 last. 140 LT. 193. 234. 105. 116 layout. 9. 234 ixmap. 176. 39. 171. 115 mapAccumL. 202. 172 instance for Integer. 9. 193. 74 liftM. 32 literate comments. 56 lines. 188 mapAccumR. 24 in do expressions. 197 isNothing. 211. 127 maximum. 240 locale. 194 mapM_. 111 v § ¢ £ 7¡ ¡ ¢ ¡ 7 . 215 isPrefixOf.INDEX isLatin1. 239 log. 181. 92. 143 maximal munch rule. 91. 41 listArray. 183. 92 magnitude. 195. 202. 219 lookup. 134 Locale (module). 188 isPrint. 202. 80 list type. 106 lookahead. 189 Maybe (datatype). 195. 13. 199 . 207 liftM4. 119 . 188 isUpper. 172 derived instance. 9. see also offside rule lcm. 26 in list comprehensions. 44. 195. 173. 181. 211. 91. 239. 84. 27 lambda abstraction. 116 let expression. 142 maxBound. 180. 104. 174. 23. 65 making directories. 31. 80 list comprehension. 169. 195. 19. 173. 81. 186 list. 232. 45. 109 Left. 206 mapM. 56 linearity. 12. 40. 122 lexDigits. 155. 195. 194 literal. 31. 119 maximumBy. 207 liftM5. 45. 81 length. 9. 40. 202. 183. 7 lexLitChar. 188 mapAndUnzipM. 193. 19. 106 logarithm. 109 mapMaybe. 16. 118 List (module). 202. 177 join. 89. 86. 181. 156 Main (module). 40. 194 isOctDigit. 130. 225 map. 176. 206 Just. 64 label. 50. 195. 169. 198 max. 173. 212 iterate. 172.
153 Numeric (module). 105 negation. 9. 140 opencom. 202. 108 offside rule. 194 maybe. 187 null. 234 moving directories. 11 translation of literals. 178 instance for Char. 206 instance for Maybe. 136 module. 193. 119 Ord (class). 34. 155. 214 operating system commands. 55. 206 msum. 46 INDEX next. 57 name qualiﬁed. 244. 180. 186 nubBy. 130. 105 instance for Complex. 181. 113 octal. 84. 84. 10. 198 Ordering (datatype). 13. 119 minimumBy. 157 instance for Ratio. 17. 143 minimum. 106 superclass of Real. 19. 104. 111 superclass of MonadPlus. 111 instance for Ratio. 230 operator. see qualiﬁed name special. 38. 81. 66. 153 superclass of Fractional. 193. 129 openFile. 32–34. 202. 129 negate. 195. 161. 9. 88. 137 or. 129 odd. 184. 33. 232. 5. 159. 91. 186. 32. 81. 113 numericEnumFromTo. 202. 110 notElem. 244. 91. 20 newconstr. 153 superclass of Real. 225 mplus. 79. 60. 156 mkStdGen. 210. 91. 26. 138 newline. 88. 113 numericEnumFromThenTo. 111 maybeToList. 182. 206 mzero. 189 mkPolar. 54. 104. 89 literal syntax. 9. 136 Monad (class). 206 + pattern. 18 numerator. 119 Nothing. 51. 206 monad. 111 instance for Maybe. 19 operator application. 90. 89. see also layout op. 54. 109 instance for []. 52. 113 numericEnumFromThen. 89. see special name namespaces. 9. 61 monomorphism restriction. 95 MonadPlus (class). 19 ops. 66. 142 minBound.258 Maybe (module). 106 modid. 168 not. 202. 55. 104 derived instance. 61 Month (datatype). 151. 113 instance for IO. 142 instance for Array. 206 monomorphic type variable. 18. 197 numeric type. 105. 90 numericEnumFrom. 214 opening a ﬁle. 16. 27. 244. 184. see class method min. 225 moving ﬁles. 116 Num (class). 248 newtype declaration. 89. 202. 11. 180. 9. 194 method. 65 module. 81 nub. 206 instance for []. 91. 105 ord. 246 mod. 19. 46. 90. 115. 112 ¢ ¦ . 129 newStdGen. 11. 245 nonnull. 206 Monad (module). 121. 10 ncomment. 130 octit. 105 number.
93. 130 qual. 161 Rational (type synonym). 125 PreludeIO (module). 11. 11. 31. 11. 103. 140 path. 140 qvarid. 217 RandomGen. 55. 125 qcon. 155. 151. 91. 18. 130 qtycon. 79. 115 PreludeText (module). 92. 91.INDEX otherwise. 75 Prelude (module). 30 overloaded constant. 140 qtycls. 151 Read (class). 18. 42. 156 physical ﬁle. 125 putStrLn. 247 randomR. 139 qualiﬁed name. 103 PreludeBuiltin (module). 247 randomRIO. 125 product. 244. 51. 25. 140 qconid. 75. 105 Prelude implicit import of. 229 program name. 169. 43. 3 properFraction. 31. 247 randoms. 106 quotRem. 96. 9. see + pattern refutable. see irrefutable pattern linear. 244. 155. 103. 18. 178 ¢ ¦ ¢ ¦ § ¢ £¡ . 151. 34 Permissions (datatype). 11. 119 program. 244. see constructed pattern ﬂoating. 51 partition. 247 randomRs. 96. see aspattern _. 106 polar. 143 instance for [a]. see refutable pattern pattern binding. 18. 90. 244. 183. 103. 96. 19. 47 defaults. 140 pat. 130 Random (class). 171. 130 qconop. 121 derived instance. 229 program structure. 169. 153 rational numbers. 23 quantiﬁcation. 247 Random (module). 96. 53 print. 130 qvarop. see integer literal pattern irrefutable. 172 Ratio (datatype). 156 polling a handle for input. 147 precedence. 103. 11. 41 quot. 140 qvarsym. 72 qualiﬁer. 171. 57 patternmatching. 247 random access ﬁles. 244 random. 4 pragmas. 23. 30 @. 125 PreludeList (module). see patternmatching overloading. 11. 85. 11. 104. 244. 91. 181. 218 polymorphic recursion. 224 phase. 151 Ratio (module). 213 pi. 130 qop. 18. 107 putChar. 245 randomIO. 140 qconsym. 153. 54 polymorphism. 125 putStr. 244. 70. 103. 187 . see wildcard pattern constructed. 38 overloaded pattern. 110 overloaded functions. 121 principal type. 106 qvar. see also ﬁxity pred. see linear pattern + . 172 rangeSize. 129 v 259 program arguments. 225 pattern. 247 range. see ﬂoating literal pattern integer. 124 instance for Array.
159. 225 renaming ﬁles. 92. 88. 123 instance for Integer. 104. 10. 86. 214 readOct. 224. 90. 122 ReadS (type synonym). 106 removeDirectory. 159. 108 realPart. 56. 94. 88. 130 return. 154 read. 217 rem. 108 RealFrac (class). 217 seeking a ﬁle. 85. 217 SeekMode (datatype). 89. 224. 124 v v § ¡ ¢ £¡ ¢ ¡ ¤ ¤ . 225 removing ﬁles. 88. 218 readInt. 225 renameDirectory. 117 reservedid. 110 sequence. 107 instance for Ratio. 10. 143 readLitChar. 96. 248 setting the directory. 164 reading a directory. 164 readParen. 143 instance for [a]. 138 Right. 119 . 81 round. 31. 117 replicate. 126. 159. 164 readEsc. 123 instance for Int. 225 renameFile. 117 scontext. 137 searchable. 214 readFloat. 109 reverse. 109 recip. 20. 130 reservedop. 162 scanl. 140 INDEX scaleFloat. 168 readHex. 85. 224. 117 scanr1. see also operator application SeekFromEnd. 116 scanr. 93. 224 readDec. 123 instance for Ratio. 159. 210. 106 recursive datatype. 46 refutable pattern. 224. 225 repeat. 109 setCurrentDirectory. 122 readable. 121. 85. 198 readFile. 124 instance for Double. 123 instance for Float. 105 instance for Ratio. 91.260 instance for Char. 122 readSigned. 92. 139 rhs. 224. 153 superclass of Integral. 121 derived instance. 85. 55. 225 removing directories. 217 semantics formal. 92. 126 ReadMode. 121 reads. 154 superclass of RealFloat. 16. 76 seq. 93. 224 setStdGen. 198 readLn. 91. 33 RelativeSeek. 109 sequence_. 159. 92. 166 . 195. 126 readList. see formal semantics semiclosed handles. 156 realToFrac. 226 reading from a ﬁle. 81. 92. 86. 159. 225 renaming directories. 214 separate compilation. 85. 107 roundTo. 104. 155. 106 superclass of RealFrac. 96. 225 setPermissions. 121. 91. 225 removeFile. 214 Real (class). 226 Show (class). 107 RealFloat (class). 244. 143 ReadWriteMode. 51. 85. 163 readsPrec. 224 section. 108 scaleRat. 10. 116 scanl1. 164 readIO. 97.
82 String (type synonym). 119 superclass. 232. 115 tails. 235 tdPicosec. 213 stdout. 92. 48. 121. 245 splitAt. 111 string. 235 tdMonth. 163 showList. 91. 80. 122 showEFloat. 163 showInt. 118 sqrt. 91. 12 transparent. 181. 130 subtract. 46. 163 showParen. 159. 41. 215 small. 118 special. 124 instance for Double. 106 sine. 43. 9. 45 strictness ﬂags. 237 showChar. 85. 188 sortBy. 229 system. 183. 26. 213 stmt. 106 tdDay. 92 signature. 164 showHex. 91. 123 instance for HandlePosn. 199 showOct. 121. 92. 123 instance for Int. 80. 105 sum. 139 stmts. 129. 93 sinh. 91. 137 simpletype. 159. 93 tanh. 237 show3. 26. 164 showGFloat. 129 span. 210. 232. 9. 105 show. 129 tail. 123 instance for Ratio. 159. 213 standard prelude. 237 show2’. 123 instance for Float. 188 space. 122 ShowS (type synonym). 12. 85. 210. 178 instance for Char. 118 tan. 235 tdHour. 106 standard handles. see type signature signdecl. 117 takeWhile. 159. 232. 108 succ. 106 tangent. 159. 49 symbol. 121 show2. see also Prelude stderr. see transparent string string. 143 showString. 9. 154 superclass of Num. 163 showsPrec. 127 System (module). 244. 86. 106 size of ﬁle. 130 synonym. 159. 53 significand. 62 simpleclass. 86. 129 snd. 79 literal syntax. 94. 164 showFloat. 45. 85. 246 stdin. 210 instance for Integer. 85. 139 strictness ﬂag. 85. 91. 114 sort. 122 showSigned. 105 simple pattern binding. 122 sign. 181. 235 261 .INDEX instance for Array. 188 take. 91. 9. 213 StdGen (datatype). 184. 183. 181. 232. 121 shows. 232. 164 showFFloat. 138 sin. 129 split. 159. 108 signum. 9. 159. 57. see type synonym syntax. 163 showIntAtBase. 229 tab. 159. 143 showLitChar. 74. 210. 235 tdMin. 244. 195.
103. 232. 93. 10. 38. 130 varop. see principal type INDEX trivial. 202. 206 unlines. 9. 4. 230 the ﬁle system. 93. 140 . 125 valdefs. 4. 119 unzip. 22. 80. 198 toUTCTime. 81. 22 uniWhite. 4 var. 198 topdecl (class). 12 UnicodePrims (module). 46 topdecl (type). 120 unzip3. see trivial type unit expression. 181. 86. 233. 119 until. see constructed type function. 130 uncurry. 180. 49. 17. 38. 140 varid. 45 topdecl. see ambiguous type constructed. 181. 130 type. 181. see tuple type type. 129 unless. 239. 9. see list type monomorphic. 235 transpose. 190 unzip5. see monomorphic type numeric. 184. 40. 136 toRational. 240 TimeLocale (datatype). 38. 51 topdecl (instance). 45. see trivial type tuple. 91. 49 value. 180. 114 unwords. 211. 188 Unicode character set. see function type list. 129 uniSymbol. 120 unzip4. 98. 187 unionBy. 7. 9. 187 trigonometric function. 129 unit datatype. 43 topdecl (default). 224 Time (module). 114 undefined. 233. 185. 224. 232. 9. 17. 235 timeFmt. see numeric type principal. 46 tyvar. see newtype declaration type signature. 235 toEnum. 187 uniSmall. 106 toLower. 22. 41. 39. 240 TimeDiff (datatype). 240 to12. 41. 130 tycon. 137 type class. 40. 92. 40. 43 type environment. 53 for an expression. 42 ambiguous. 233. 9. 11. 239. 42 type expression. 107 try. 232 time12Fmt. 66. 11. 11. 235 toClockTime. 47 topdecl (data). 18. 49 topdecl (newtype). 197 uniDigit. 105 toUpper. 40 type renaming. 239. 67. 195. 182. 80 tuple type. 114 unfoldr. 234 time. 42. 11. 232 time of day. 181. 195. 236 toCalendarTime. 235 terminating a program. 79 truncate. 41 tycls. 181. 81 True. 129 union. 136 topdecls. 49.262 tdYear. see class type constructor. see expression typesignature type synonym. 191 unzip7. 17. 18. 191 unzip6. 105 toInteger. 191 userError. 181. 93 trivial type. see also datatype recursive. 129 uniLarge. 183. 221 tuple. 232.
190 zipWith7. 206 whitechar. 190 zip6. 9. 190 zipWith5. 190 zip7. 202. 126. 129 when. 120 zipWith3. 9. 97. 181. 202. 80. 185. 53. 10.INDEX vars. 181. 129 whitespace. 224 writeFile. 190 zip5. 137 varsym. 129 wildcard pattern (_). 207 263 . 207 zipWithM_. 214 WriteMode. 190 zipWith. 120 zipWith4. 181. 202. 181. 214 zip. 120 zip4. 130 vertab. 31 words. 185. 118 writable. 38. 181. 120 zip3. 9. 129 whitestuff. 9. 181. 190 zipWithM. 181. 181. 190 zipWith6.
This action might not be possible to undo. Are you sure you want to continue?