This action might not be possible to undo. Are you sure you want to continue?
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
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170 15. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 Lexical Syntax . . . . . . . . . 11 Compiler Pragmas 147 11. . . . . . . . . . . . . . . . . . .1 Library Complex . . . . . . . . . . . . . . . . . . 10. . . . .2 Incremental Array Updates . . . . . . . . . . . . . . . . . . . . . . . . . . 147 II The Haskell 98 Libraries 149 12 Rational Numbers 151 12. . . . .4 Library Numeric . . . 159 160 161 161 161 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10. . . .2 Library Ix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Showing functions 14. . . . . . . . . . . . . . . . . . . . .5 ContextFree Syntax . . . . 9. . . . 15 Indexing Operations 169 15. . . . . . . . . . . . . . . . . . . . . 14. . . . . . . . . . . . . . . . . . . . . . . . . . .4 Literate comments . . . . . . . . . . . . . . . . . . . . . . .1 Deriving Instances of Ix . . . . . . . . . . . . . . . . . . . . . . . .1 Inlining . . . . . . . . . . .1 Accumulated Arrays 16. . .3 Derived instances of Bounded . . . . . . . . . .1 Array Construction . . . . . . . . . . .5 An Example . . . . . . . . . . . . . . . 147 11. .2 Specialization . . . . . .3 Miscellaneous . . . . . . . . 153 13 Complex Numbers 155 13. . . . . . 156 14 Numeric 14. . . . . . . . . . . . . . . . . . . . . . .1. . . . . . .2 Reading functions . . . . . . . . . . . . . . . . . . . . .3 Derived Arrays . . . . . . . . . . . 9. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .iv 9 Syntax Reference 9. . . . . . . 10. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3 Layout . . . . 9. . . 14. . . . . . . . . . . . . . . . . . . . .4 Library Array . 172 16 Arrays 16. . CONTENTS 127 127 128 130 134 136 141 142 142 143 143 145 . . . . . . . . .1 Notational Conventions 9. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16.1 Library Ratio . . . .1 Derived instances of Eq and Ord . . . . . . . . . . . . . . . . . . . . . . . . .4 Derived instances of Read and Show 10. . . . . . . . . . 173 174 174 175 176 176 . . . . . . . . . . . . . . . . . . . . . . . . . . 16. . . . . . . . . 16. . .2 Derived instances of Enum . 10 Speciﬁcation of Derived Instances 10. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . 21. . . . . . . 17. .7.1 Standard Handles . . . . . . . . . . . . . . . . .7. . . . 21. . . . . . . .3 File locking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4 Determining the Size of a File . . . . . . . . . . . . . . . . . . . . . . . . . .1 Naming conventions 20. . . . . . . . . . . . . . . . . . . . . . . .1 Revisiting an I/O Position 21. . . . . . . . . . . . . . . .2 Closing Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17. . . . . . . . . 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 . . . . . . . . . . . . . . . . . . . . . . . 21. . . . . . . . . . . . . .3 Functions . . . . . . . . . . . . . . . . . . . . . . . 21. . .3 Opening and Closing Files . .3 List transformations . . . . . . . . . . . . . . . .2 Reading Input . . . . . . .7 The “generic” operations 17. . . .1 I/O Errors .9 Library List . . . . . . v 179 182 182 183 183 184 184 185 185 186 . . . . . . . . . . . . . . . . . . . 21. . . . . . . . . . . . . . . . . . . . . . . . . .4 unfoldr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4 Reading The Entire Input . . . . . . . . .2 Class MonadPlus . .2 Files and Handles . . . . . . . . . . . . . . . . 21. . . . . . . . . . . .5 Text Output . . 197 20 Monad Utilities 20. . . . . . . . . .CONTENTS 17 List Utilities 17. 21. . . . . . . . .5 Detecting the End of Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4 Library Monad . 20. . . . . . . . . . . . . . . . . . .1 Library Char . . . . . . . . . . . . . . . 17.3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2. . . . . . . . . . . . . . . . . . .1 Flushing Buffers . . . . . . . . . . .9. . . . . . . . . . . . . . . . . . . . 21. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17. . . . . . . . . . . 21. . . . . . . . . . . . . . . . . . . . . . . . . . . .2. . . . 21. . . . . . . . . . . . . .9. 21. . .9. .8 Handle Properties . . . . . . . . . . . . . . 21.6 Buffering Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2. .1 Indexing lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6. . . . . . . . . .7 Repositioning Handles . . . . . 21. . . . . . . . . . 20. . . . . . .6 The “By” operations . . 21. . . . . . . . . . . . . . . . . . . .1 Opening Files . . . . . . . . . . . . . . . . . . . . . . .3. . . . . . 17. . .9 Text Input and Output . . . . . . . 17. . . . . . .9. . . . . . 21 Input/Output 21. . . . . . . . .2 “Set” operations .5 Predicates .8 Further “zip” operations . . . . . . 18 Maybe Utilities 193 18. . . . . . . . . .1 Library Maybe . . . . . . . . . . . . . 21. . . . . . . . . . . . . . . . . . . . .2 Seeking to a new Position 21. . . . . .3 Reading Ahead . . . . . . . . . . . . . . . . . . . . . 21. . . . . . . . . . . . . . . . . . . .2 SemiClosed Handles . . . 21. . . . . .1 Checking for Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17. . . . 194 19 Character Utilities 195 19. . . . . . .9. . . . . . .
219 219 220 221 223 229 24 Dates and Times 231 24. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Library Locale . . . . . . . . . . . . . . . . . . . . . . . . . . . . .vi 21. . . . . CONTENTS . . . .10Examples . . . . . . . . . . . . . . . . . 22 Directory Functions 23 System Functions . . . . . . . . . 21.11Library IO . . . . .10. . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Library Time . . .2 The Random class . . . . . . . . . . .2 Copying Files . . . .3 The global random number generator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 The RandomGen class. . . . . . . . . . . . . . . . . . . . . . and the StdGen generator 27. . . . . . . . . . . . . . . . . . . . . . . . . . . . Index . . . . . . . . . . . . . . . . . . . . . . . . . References . . 234 25 Locale 239 25.1 Summing Two Numbers 21. . . . . . . . . . . . 21. . . . 27. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241 243 245 247 248 249 251 . . . . . . . . . . . .10. . . . . . . . . . . 240 26 CPU Time 27 Random Numbers 27. . . .
Curry and Robert Feys in the Preface to Combinatory Logic [2]. Anyone should be permitted to implement the language and distribute it to whomever they please. 4. It should be based on ideas that enjoy a wide consensus. It was decided that a committee should be formed to design such a language. named after the logician Haskell B.PREFACE vii Preface “Some half dozen persons have written technically on combinatory logic. It should be completely described via the publication of a formal syntax and semantics. It should reduce unnecessary diversity in functional programming languages. and a vehicle through which others would be encouraged to use functional languages. Since some of our fellow sinners are among the most careful and competent logicians on the contemporary scene. and excessive condensation would be false economy here. even more than it is ordinarily. a stable foundation for real applications development. we regard this as evidence that the subject is refractory. purely functional programming languages. May 31. 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. 3. It should be suitable for teaching. have published something erroneous. This document describes the result of that committee’s efforts: a purely functional programming language called Haskell. Goals The committee’s primary goal was to design a language that satisﬁed these constraints: 1. It should be freely available. and applications. Oregon. including ourselves. research. Curry whose work provides the logical basis for much of ours. to discuss an unfortunate situation in the functional programming community: there had come into being more than a dozen nonstrict. 1956 In September of 1987 a meeting was held at the conference on Functional Programming Languages and Computer Architecture (FPCA ’87) in Portland. and most of these.” Haskell B. Thus fullness of exposition is necessary for accuracy. . all similar in expressive power and semantic underpinnings. including building large systems. 2. 5. providing faster communication of new ideas.
Clarify obscure passages. With reluctance. If these program were to be portable. a set of libraries would have to be standardised too. The Haskell 98 Language and Library Reports were published in February 1999. making some simpliﬁcations. make small changes to make the overall language more consistent. By the time Haskell 98 was stabilised. 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).4). it was decided that a stable variant of Haskell was needed.viii PREFACE Haskell 98: language and libraries The committee intended that Haskell would serve as a basis for future research in language design. and is called “Haskell 98”. The original Haskell Report covered only the language. with the following goals: Correct typographical errors. A separate effort was therefore begun by a distinct (but overlapping) committee to ﬁx the Haskell 98 Libraries. It is not a . As Haskell becomes more widely used. Haskell has indeed evolved continuously since its original publication. The original committees ceased to exist when the original Haskell 98 Reports were published. It is intended to be a “stable” language in sense the implementors are committed to supporting Haskell 98 exactly as speciﬁed. many typographical errors and infelicities had been spotted. for the foreseeable future. This document is the outcome of this process of reﬁnement. and removing some pitfalls for the unwary. and hoped that extensions or variants of the language would appear. and constitutes the ofﬁcial speciﬁcation of both. so every change was instead proposed to the entire Haskell mailing list. incorporating experimental features. the Report has been scrutinised by more and more people. Haskell 98 was conceived as a relatively minor tidyup of Haskell 1. I took on the role of gathering and acting on these corrections. and I have adopted hundreds of (mostly small) changes as a result of their feedback. At the 1997 Haskell Workshop in Amsterdam.4. Revising the Haskell 98 Reports After a year or two. Resolve ambiguities. This task turned out to be much. It includes both the Haskell 98 Language Report and the Libraries Report. there had been four iterations of the language design (the latest at that point being Haskell 1. together with a standard library called the Prelude. By the middle of 1997. this stable language is the subject of this Report. much larger than I had anticipated.
Instead. including: monadic state. at the time of writing there are Haskell implementations that support: Syntactic sugar. The entire text of both Reports is available online (see “Haskell resources” below). recursive donotation. lexically scoped type variables. including: . or use Haskell for teaching. metaprogramming facilities. including: multiparameter type classes. exceptions. Control extensions.org gives access to many useful resources. going well beyond Haskell 98. Haskell 98 does not impede these developments. concurrency. including: pattern guards. can do so in the knowledge that Haskell 98 will continue to exist. existential types. Extensions to Haskell 98 Haskell continues to evolve. Haskell Resources The Haskell web site http://haskell. so that those who wish to write text books. For example. local universal polymorphism and arbitrary ranktypes. and some familiarity with functional languages is assumed. Type system innovations. There is more besides.PREFACE ix tutorial on programming in Haskell such as the ‘Gentle Introduction’ [6]. functional dependencies. it provides a stable point of reference.
by an active community of researchers and application programmers.x PREFACE Online versions of the language and library deﬁnitions. Building the language Haskell was created. Microsoft Research Ltd) . via the Haskell mailing list. Chalmers University) Thomas Johnsson (Chalmers University) Mark Jones (Yale University. University of Nottingham. devoted a huge amount of time and energy to the language. Those who served on the Language and Library committees. in particular. including a complete list of all the differences between Haskell 98 as published in February 1999 and this revised version. suggest improvements to. Tutorial material on Haskell. and criticise the language or its presentation in the report. Oregon Graduate Institute) Erik Meijer (Utrecht University) Rishiyur Nikhil (MIT) John Peterson (Yale University) Simon Peyton Jones [editor] (University of Glasgow. You are welcome to comment on. Applications of Haskell. Details of the Haskell mailing list. 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. Implementations of Haskell. Here they are. Contributed Haskell tools and libraries. Oregon Graduate Institute) Dick Kieburtz (Oregon Graduate Institute) John Launchbury (University of Glasgow. and continues to be sustained.
Sigbjorn Finne. Kent Karlsson. Graeme Moss. Tom Thomson. Christian Maeder. Landin’s ISWIM. Bob Hiromoto.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. Rinus Plasmeijer. Jan Kort. Nic Holt. Manuel Chakravarty. ML and Standard ML. Felix Schroeter. Mark Lillibridge. Ketil Malde. Andreas Rossberg. Paul Otto. Ian Poole. Christian Sievers. Dylan Thurston. Lauren Smith. APL. it is right to acknowledge the inﬂuence of many noteworthy programming languages developed over the years. AnttiJuhani Kaijanaho. Finally. Mark Carroll. Chris Okasaki. John Robson. Stuart Wray. Ken Takusagawa. . Simon Thompson. Bjarte M. Alexander Jacobson. Michael Marte. Gofer. and Bonnie Yantis. Simon B. Chris Fasel. Chris Dornan. Tommy Thorn. Pablo Lopez. Michael Webber. Mike Gunter. Stephen Price. Larne Pekowsky. Ian Holyer. dozens of other people made helpful contributions. Mark Tullsen. Laura Dutton. Bjorn Lisper. Michael Schneider. Hans Aberg. the following languages were particularly inﬂuential: Lisp (and its modernday incarnations Common Lisp and Scheme). Although it is difﬁcult to pinpoint the origin of many ideas. Østvold. Dean Herington. Franklin Chen. SiauCheng Khoo. Orjan Johansen. Klemens Hemm. Nick North. Id. Pradeep Varma. Feliks Kluzniak. Randy Hudson. Josef Svenningsson. Olaf Lubeck. Marcin Kowalczyk. Stephen Blott. Raman Sundaresh. Jeff Lewis. Sten Anderson. Tony Davie. Tony Warnock. Gary Memovich. Robert Jeschofnik. Craig Dickson. Olaf Chitil. Jones. Clean. Guy Cousineau. Stef Joosten. Amir Kishon. Jerzy Karczmarczuk. Keith Wansbrough. Andy Gill. and Turner’s series of languages culminating in Miranda 1 . Thomas Hallgren. Ralf Hinze. Patrick Sansom. Paul Callaghan. George Russell. Andy Moran. Dave Parrott. Fergus Henderson. Satish Thatte. Nimish Shah. Magnus Carlsson. Sisal. John Meacham. Ross Paterson. Duke Briscoe. Mike Joy. Malcolm Wallace. Wolfram Kahl. Rick Mohr. Mark Hall. David Tweed. Chris Clack. They are as follows: Kris Aerts. Hope and Hope . Ian Lynagh. Mike Thyer. Richard Kelsey. Carl Witty. In addition. Jose Labra. Tom Blenko. Julian Seward. Richard Bird. Jim Mattson. Jan Skibinski. and others on the lambda calculus. Randy Michelsen. Rosser. Cordy Hall. Arthur Norman. Michael Fryers. Sandra Loosemore. Libor Skarvada. Sven Panne. Matt Harden. Curry. Patrik Jansson. 1 Miranda is a trademark of Research Software Ltd. Stefan Kahrs. Henrik Nilsson. Without these forerunners Haskell would not have been possible. aside from the important foundational work laid by Church. Backus’s FP [1]. Pat Fasel. Simon Marlow. Sergey Mechveliani. some small but many substantial.
xii Simon Peyton Jones Cambridge. September 2002 PREFACE .
Part I The Haskell 98 Language 1 .
.
At the next lower level are expressions. Haskell is both the culmination and solidiﬁcation of many years of research on nonstrict functional languages.1 Program Structure In this section. userdeﬁned algebraic datatypes. and ﬂoatingpoint numbers. This includes such issues as the nature of programming environments and the error messages returned for undeﬁned programs (i. programs that formally evaluate to ). a module system. and ﬁxity information. At the topmost level a Haskell program is a set of modules. Haskell provides higherorder functions. We leave as implementation dependent the ways in which Haskell programs are to be manipulated. The top level of a module consists of a collection of declarations. a monadic I/O system.” 4. An expression denotes a value and has a static type. 1. 3. expressions are at the heart of Haskell programming “in the small. 1.Chapter 1 Introduction Haskell is a general purpose. datatypes. of which there are several kinds. The lexical structure captures the concrete representation of Haskell programs in text ﬁles. purely functional programming language incorporating many recent innovations in programming language design. list comprehensions. 3 . including lists. etc. arrays. Declarations deﬁne things such as ordinary values. This report deﬁnes the syntax for Haskell programs and an informal abstract semantics for the meaning of such programs. nonstrict semantics. deﬁned in Chapter 2. and a rich set of primitive datatypes. arbitrary and ﬁxed precision integers. interpreted. patternmatching. described in Chapter 3. type classes. all described in Chapter 4. Modules provide a way to control namespaces and to reuse software in large programs. static polymorphic typing. we describe the abstract syntactic and semantic structure of Haskell. described in Chapter 5. 2. compiled. At the bottom level is Haskell’s lexical structure. as well as how it relates to the organization of the rest of the report.e.
which describes the standard builtin datatypes and classes in Haskell. the result is a program written in a small subset of Haskell that we call the Haskell kernel. 1. Generally the italicized names are mnemonic. Technically.3 Values and Types An expression evaluates to a value and has a static type. 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. so the language includes no mechanism for detecting or acting upon errors. If these translations are applied exhaustively. and Chapter 7. etc. which discusses the I/O facility in Haskell (i. The translation of each syntactic structure into the kernel is given as the syntax is introduced. and permits not only parametric polymorphism (using a traditional HindleyMilner type structure) but also ad hoc polymorphism. Although the kernel is not formally speciﬁed. However. it is essentially a slightly sugared variant of the lambda calculus with a straightforward denotational semantics.4 CHAPTER 1. the speciﬁcation of derived instances. Errors in Haskell are semantically equivalent to .1. the concrete syntax.e. for declarations. the type system allows userdeﬁned datatypes of various sorts. implementations will probably try to provide useful information about errors. as then else . Also. such as for expresin if sions. the meaning of such syntactic sugar is given by translation into simpler constructs. INTRODUCTION This report proceeds bottomup with respect to Haskell’s syntactic structure. they are not distinguishable from nontermination.2 The Haskell Kernel Haskell has adopted many of the convenient syntactic structures that have become popular in functional programming. . how Haskell programs communicate with the outside world). for types. Values and types are not mixed in Haskell. The chapters not mentioned above are Chapter 6. In this Report. This modular design facilitates reasoning about Haskell programs and provides useful guidelines for implementors of the language. See Section 3. or overloading (using type classes). there are several chapters describing the Prelude. and pragmas supported by most Haskell compilers. literate programming. ¥ ¢ § £ ¤ ¡ ¢ ¦ 1. However.
and type classes refer to entities related to the type system. class. the other four kinds of names are identiﬁers beginning with uppercase letters. . There are two constraints on naming: 1. for example. Names for variables and type variables are identiﬁers beginning with lowercase letters or underscore. NAMESPACES 5 1. Int may simultaneously be the name of a module. and constructor within a single scope. those for type variables.4 Namespaces There are six kinds of names in Haskell: those for variables and constructors denote values. type constructors. 2. These are the only constraints.4.1. An identiﬁer must not be used as the name of a type constructor and a class in the same scope. and module names refer to modules.
INTRODUCTION .6 CHAPTER 1.
. This syntax depends on properties of the Unicode characters as deﬁned by the Unicode consortium. BNFlike syntax is used throughout. although usually the context makes the distinction clear. source programs are currently biased toward the ASCII character set used in earlier versions of Haskell. there is no implicit space between juxtaposed symbols. 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 [.. Haskell compilers are expected to make use of new versions of Unicode as they are made available.]. Haskell uses the Unicode [11] character set. However.Chapter 2 Lexical Structure In this chapter.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. 7 § ¢ £¡ ¨ ¥¥8 8 8 1 &§ ¢ £¡ A !§ 7 3¢ 8 8 8 @¥¥9 £ § )'% $ " 0(&§#!§ £§ ¢§ ¡ £¡ ¢ ¢ ¦ £¤ ¡ §¥ § § £¡ §¥ § § £ ¦¤ ¢ ¡ ¨ ¦¤ ¢ ¡ ©§¥ § § £ ¢ £ ¡ 7 3¢ ¡§ 7 3¢ 6 4¤ ¦ 2 5 § 3©¦ . we describe the lowlevel lexical structure of Haskell. Most of the details may be skipped in a ﬁrst reading of the report. all whitespace is expressed explicitly. 2.
§§ § § ¦ £$ § § § © ¢ 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 Lexical Program Structure 8 ( ) . .˜ 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 ¢ ¡ . [ ] ` { } ¤ ¤© ¤ ¥ § 2 " § ! ¢ §¢ © ¥¢ ¤ ¤ © ¦ 7 ¦ 43¤ 3§ ¢ 32 ¡ © ¢ § ¦ ¨¦¤ © § ¥ £ ¤¢ ¡ ¤¥ § ¦ § ¤ § § 7 3§ ¢ ¤ 7 4¦ ¢ ¡ ¢ 7 . / < = > ? \ ˆ  .{} 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. 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 ¡ ! # $ % & * + .
In an ordinary comment.or } within a string or within an endofline comment in that code will interfere with the nested comments. “{” starts a nested comment despite the trailing dashes.2. and. because both of these are legal lexemes. the longest possible lexeme satisfying the production is read. ) and extends to the following newline. the character sequences “{” and “}” have no special signiﬁcance.3 Comments Comments are valid whitespace. Nested comments may be nested to any depth: any occurrence of the string “{” within the nested comment starts a new nested comment. each “{” is matched by a corresponding occurrence of “}”. hence. although = is reserved. Instead. cases is not. COMMENTS 9 Lexical analysis should use the “maximal munch” rule: at each point. The sequence of dashes must not form part of a legal lexeme. as explained in Chapter 11. in a nested comment. Nested comments are also used for compiler pragmas. © § ¥ § ¨¦£ Any kind of is also a proper delimiter for lexemes. then any occurrence of {. the ﬁrst unmatched occurrence of the string “}” terminates the nested comment. “>” or “” do not begin a comment. are not valid in Haskell programs and should result in a lexing G E HTC Characters not in the category error. == and ˜= are not. although case is a reserved word. Similarly. 2. a sequence of dashes has no special signiﬁcance. For example.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 ’ . 2. A nested comment begins with “{” and ends with “}”. Within a nested comment.g. An ordinary comment begins with a sequence of two or more consecutive dashes (e.3. No legal lexeme starts with “{”. The comment itself is not lexically analysed. for example. terminated by “}”. however “foo” does start a comment. If some code is commented out using a nested comment. So.
Notice that a colon by itself.5). underscores. Underscore. digits. and Name are three distinct identiﬁers (the ﬁrst two are variable identiﬁers. Identiﬁers are case sensitive: name.4): those that begin with a lowercase letter (variable identiﬁers) and those that begin with an uppercase letter (constructor identiﬁers). Identiﬁers are lexically distinguished into two namespaces (Section 1. the last is a constructor identiﬁer). is reserved solely for use as the Haskell list constructor. : :: = \  <. all operators are inﬁx.b]”. An operator symbol starting with any other character is an ordinary identiﬁer. naMe. : : : .4): An operator symbol starting with a colon is a constructor. and are lexically distinguished into two namespaces (Section 1.10 CHAPTER 2. although each inﬁx operator can be used in a section to yield partially applied operators (see Section 3. and can occur wherever a lowercase letter can. Compilers that offer warnings for unused identiﬁers are encouraged to suppress such warnings for identiﬁers beginning with underscore. such as “[]” and “[a. Other than the special syntax for preﬁx negation. and single quotes. this makes its treatment uniform with other parts of list syntax. “:”.> @ ˜ => Operator symbols are formed from one or more symbol characters. All of the standard inﬁx operators are just predeﬁned symbols and may be rebound. “_” all by itself is a reserved identiﬁer. 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 %§ ¢ %§ ¤ . is treated as a lowercase letter.. This allows programmers to use “_foo” for a parameter that they expect to be unused. 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. as deﬁned above. However. “_”.
This f. . variables and constructors have inﬁx forms. (qualiﬁed ‘.+ is an inﬁx operator with the same ﬁxity as the deﬁnition of + in the Prelude (Section 4.g f.5. Namespaces are also discussed in Section 1.4.5 Numeric Literals §§ § § 2 § § § 2 §§ § § § § § ¦ ¦ 6 7 ¢ ¦ ¢ § 2 73§ ¢ 4 4§ ¨ e E +  ¨ § 32 ¦ ¦ ¢ ¡ .. and the other four by identiﬁers beginning with capitals.4. for example. Prelude.. NUMERIC LITERALS 11 Variables and type variables are represented by identiﬁers beginning with small letters. but not type variables or module names. 2.g (qualiﬁed ‘g’) f . F. the other four do not. (two tokens) F. Qualiﬁed names are discussed in detail in Chapter 5. F. type constructor and type class names. 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 ¢ . Sample lexical analyses are shown below. .’) F . . Lexes as this f . . This applies to variable.. ¦ ¢ ¦ ¢ § 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 ¥ %§ ¢ ¡ ¦ ! . g (three tokens) F.2). (two tokens) The qualiﬁer does not change the syntactic treatment of a name. constructor. ¦ ¤ § `¨ Since a qualiﬁed name is a lexeme. . no spaces are allowed between the qualiﬁer and the name.2. also.g F. A name may optionally be qualiﬁed in certain circumstances by prepending them with a module identiﬁer..
Numeric escapes such as \137 are used to designate the character with decimal representation 137.2. “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.4. are also provided. octal (e. \x37) representations are also allowed. Integer literals may be given in decimal (the default). and “vertical tab” (\v). Note that a single quote ’ may be used in a string.4. For example. 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. a double quote " may be used in a character. numeric escape characters in strings consist of all consecutive digits and may be of arbitrary length. The category also includes portable representations for the characters “alert” (\a). Thus "\&" is equivalent to "" and the character ’\&’ is disallowed.g. this ensures that a decimal point cannot be mistaken for another use of the dot character. Negative numeric literals are discussed in Section 3. “new line” (\n). The typing of numeric literals is discussed in Section 6. “backspace” (\b). Further equivalences of characters are deﬁned in Section 6. including control characters such as \ˆX. octal (preﬁxed by 0o or 0O) or hexadecimal notation (preﬁxed by 0x or 0X). A string may include a “gap”—two backslants enclosing white characters—which is ignored. © 7 3¢ 4§ ¤ ¥ ¢ 4§ ¢¡ ¥ § 2 ¦ ¢ 7 3¢ ¦ 7 ¢ © © ¡5¢ ¡ 5¢ ¢ ¨£¡ ) © © ¡ 5¢ ¢ ¨£¡ § §#¥¦£ ¤ ¥ § ¨¦£ § ¥ © y ¢ 2¤ ¢ u ¢ ¤§ ¦ © © § ¨¥ § ¨¥ ¤ ¢ ¦ ¤ ¡§¢ ¤ ¡ §¢ 7 ¥ 6 6 6 6 6 6 6 § @§ © ¢ © ¤ ¥ ¢ © ¡ §¢ #¦ § ¤ § © 7 ¤ ¤ ¡ ¤ § 5¢¦ ¢ ¢ ¥ ¥ . as in "Hello". as in ’a’. but must be escaped in a character. but must be escaped in a string.1. “horizontal tab” (\t). “form feed” (\f). is parsed as a string of length 1. Similarly. the one ambiguous ASCII escape code. LEXICAL STRUCTURE There are two distinct kinds of numeric literals: integer and ﬂoating. 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). A ﬂoating literal must contain digits both before and after the decimal point. 2. \o137) and hexadecimal (e. Floating literals are always decimal. similarly. Escape codes may be used in characters and strings to represent special characters. \ must always be escaped.g. Consistent with the “maximal munch” rule.1. and strings between double quotes. Escape characters for the Unicode character set.12 CHAPTER 2. "\SOH".
7. do. As an example.2. and \ˆX. an empty list “{}” is inserted. The layout (or “offside”) rule takes effect whenever the open brace is omitted after the keyword where. which can be freely mixed within one program.7). the braces and semicolons are inserted as follows. let. and if it is indented less. This allows both layoutsensitive and layoutinsensitive styles of coding. a control character. For each subsequent line. Also. The meaning of this augmented program is now layout insensitive. A close brace is also inserted whenever the syntactic category containing the layout list ends. b = 2 g y = exp2 in exp1 making a.pop. and layout processing occurs for the current level (i.3 gives a more precise deﬁnition of the layout rules. where the . When this happens. Given these rules. even if a line is indented to the left of an earlier implicit open brace.1 shows a (somewhat contrived) module and Figure 2. 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). b and g all part of the same layout list. a single newline may actually terminate several layout lists. then the layout list ends (a close brace is inserted). 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. or of.7 Layout Haskell permits the omission of the braces and semicolons used in several grammar productions. let. Haskell programs can be straightforwardly produced by other programs. if it contains only whitespace or is indented more. then a new item begins (a semicolon is inserted).2 shows the result of applying the layout rule to it. these rules permit: f x = let a = 1. 2. insert a semicolon or close brace). Figure 2. \ \a numeric escape character. Because layout is not required. Note in particular: (a) the line beginning }}. a close brace is inserted. that is. Informally stated. then instead of starting a layout. if it is indented the same amount. LAYOUT 13 "Here is a backslant \\ as well as \137. by using layout to convey the same information." String literals are actually abbreviations for lists of characters (see Section 3. do or of is less than or equal to the current indentation level. no layout processing is performed for constructs outside the braces. then the previous item is continued (nothing is inserted). The layout rule matches only those open braces that it has inserted.e. if an illegal lexeme is encountered at a point where a close brace would be legal. Section 9. Within these explicit open braces. an explicit open brace must be matched by an explicit close brace. If the indentation of the nonbrace lexeme immediately following a where.
inserted because of the column 0 indentation of the endofﬁle token.(pop Empty) is an error top :: Stack a > a top (MkStack x s) = x . LEXICAL STRUCTURE module AStack( Stack.14 CHAPTER 2. case s of {r > i r where {i x = x}}) .top :: Stack a > a .(top Empty) is an error Figure 2. pop. inserted because the end of the tuple was detected. (b) the close braces in the where clause nested within the tuple and case expression. top.size :: Stack a > Int .pop :: Stack a > (a. Stack a) . case s of r > i r where i x = x) .push :: a > Stack a > Stack a . pop.top (MkStack x s) = x } . corresponding to the depth (3) of the nested where clauses.1: A sample program module AStack( Stack. push.(pop Empty) is an error .push x s = MkStack x s . size ) where {data Stack a = Empty  MkStack a (Stack a) . push. .stkToLst (MkStack x s) = x:xs where {xs = stkToLst s }}.size s = length (stkToLst s) where {stkToLst Empty = [] . 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.(top Empty) is an error Figure 2. and (c) the close brace at the very end. top.2: Sample program with layout expanded termination of the previous line invokes three applications of the layout rule. Stack a) pop (MkStack x s) = (x.pop (MkStack x s) = (x.
index: a letter . there are some families of nonterminals indexed by precedence levels . the nonterminals . Free variables and constructors used in these translations always refer to entities deﬁned by the Prelude. Except in the case of let expressions. including their translations into the Haskell kernel. right. Similarly.Chapter 3 Expressions In this chapter. and (if it is in scope) what it is bound to. . A precedencelevel variable ranges from 0 to 9. In the syntax that follows. these translations preserve both the static and dynamic semantics. and may have a double (written as a superscript). For example actually stands for 30 productions. with 10 substitutions for and 3 for . or for left. “concatMap” used in the translation of list comprehensions (Section 3. we describe the syntax and informal semantics of Haskell expressions.or nonassociativity and a precedence level.11) means the concatMap deﬁned by the Prelude. where appropriate. an associativity variable varies over . regardless of whether or not the identiﬁer “concatMap” is in scope where the list comprehension is used. For example. ::  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 .
Consecutive unparenthesized operators with the same precedence must both be either left or right associative to avoid a syntax error. ¦ 2 ' . The grammar is ambiguous regarding the extent of lambda abstractions. .(f x)) + y let { . } in x + y y :: Int > a+b :: Int A note about parsing. } ¦ § { ( )  right section labeled construction labeled update ) ) ) ¦ .2).16 © @§ CHAPTER 3.2. . This f x .. it has the same precedence as the inﬁx . Negation is the only preﬁx operator in Haskell.. The ambiguity is resolved by the metarule that each of these constructs extends as far to the right as possible. parentheses must be added around either “ ” or “ ” when unless or . For example. } in (x + y)) (f x y) :: Int \ x > ((a+b) :: Int) + g y x + y { ..1). Figure 4. .f let z + f x \ x Parses as (f x) + (g y) (. } in x + y let { . Expressions that involve the interaction of ﬁxities with the let/lambda metarule may be hard to parse.. the expression p ¢ 8 @e § 2 ¡ ¦ p v £!e ¢ $ ¡ 2 ¢ %e p 8 Q¢ ¡ 2 p v £!e ¢ $ A ¦ ¡ § { .4.. let expressions. .. ) ] ¤ ¥ £ ¢ Q¢ ( ( [ [ [ ( ( ( ) ...4. } in (x + y) z + (let { . ] ¢ £ . EXPRESSIONS Expressions involving inﬁx operators are disambiguated by the operator’s ﬁxity (see Section 4. Sample parses are shown below.operator deﬁned in the Prelude (see Section 4. and conditionals. } ¦ .. . Given an unparenthesized expression “ ”.  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 ¢ ¢ . ] .
Programmers are advised to avoid constructs whose parsing involves an interaction of (lack of) associativity with the let/lambda metarule. so the expression must parse thus: (let x = True in (x == x)) == True 17 However. It should also display the string in some systemdependent manner. The actual program behavior when an error occurs is up to the implementation. denoted by . the error message is created by the compiler. a value of any type may be bound to a computation that.1. Operators. implementations may choose to display more or less information when an error occurs. results in an error. errors cause immediate program termination and cannot be caught by the user. Translations of Haskell expressions use error and undefined to explicitly indicate where execution time errors may occur. 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. ERRORS let x = True in x == x == True cannot possibly mean let x = True in (x == x == True) because (==) is a nonassociative operator. all Haskell types include .1 Errors Errors during expression evaluation. implementations may well use a postparsing pass to deal with ﬁxities. When undefined is used. are indistinguishable by a Haskell program from nontermination. 3. the rest of this section shows the syntax of expressions without their precedences. For the sake of clarity. That is. Constructors. so they may well incorrectly deliver the former parse. Since Haskell is a nonstrict language.3. when demanded. When evaluated. The messages passed to the error function in these translations are only suggestions. 3. and Literals ¤ ¢ ¤ § § 7 3¢ ¦ 2 7 6 ¡ ¢ S ¢ variable general constructor .2 Variables.
An operator is a function that can be applied using inﬁx syntax (Section 3.4. a ﬂoating point literal stands for an application of fromRational to a value of type Rational (that is. an operator symbol can be converted to an ordinary identiﬁer by enclosing it in parentheses.4.% ). and foldr (*) 1 xs is equivalent to foldr (\x y > x*y) 1 xs. where fromInteger is a method in class Num (see Section 6. Translation: The integer literal is equivalent to fromInteger . These are described in Section 6. ) : Haskell provides special syntax to support inﬁx notation. such as ` `.1). If no ﬁxity declaration is given for `op ` ` then it defaults to highest precedence and left associativity (see Section 4. one can write the inﬁx application x `op y. For example. The ﬂoating point literal is equivalent to fromRational ( Ratio. (+) x y is equivalent to x + y. The integers and are chosen so that . as found in the and . EXPRESSIONS () [] (. or partially applied using a section (Section 3. An operator is either an operator symbol. such as + or $$.5).4). Ratio Integer). as deﬁned in the Ratio library. where fromRational is a method in class Fractional and Ratio.18 CHAPTER 3. Similarly. or is an ordinary identiﬁer enclosed in grave accents (backquotes).% constructs a rational from two integers.1. Special syntax is used to name some constructors for some of the builtin types. Dually. ¦ ¦ ¦ § ¦ ` ` ` ` ) ) ) ( ( ( ( ` ` ` ` ) 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 . instead of writing the preﬁx application op op x y. For example. . production for An integer literal represents the application of the function fromInteger to the appropriate value of type Integer.2).
1. ¨ ££ ¥¦£ ¡ ¨ ££ ¥¦£ ¡ ¨ £££ ¡ ¦¥ ¨ £££ ¡ ©§¦¥¤¢ \ > \ > case ( . 3. .deﬁned in the Prelude (see Table 4.in the Prelude. £ ¤ ¡ 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. the only preﬁx operator in Haskell.17. v Translation: The following identity holds: Given this translation combined with the semantics of case expressions and pattern matching described in Section 3. .3.3 Curried Applications and Lambda Abstractions > . so the parentheses may be could be a data constructor. as with any inﬁx operator. . then the result is . where the are patterns. An expression such Lambda abstractions are written \ as \x:xs>x is syntactically incorrect. preﬁx negation qualiﬁed operator .4 Operator Applications £ The special form . Because e1e2 parses as an inﬁx application of the binary operator . page 55). partial applications of data construc ) of ( . Similarly. () is syntax for (\ x y > xy). one must write e1(e2) for the alternative parsing.operator does not necessarily refer to the deﬁnition of . ¡ A ¡ 8 8 ¥¥8 ¡ ¡ £ ¡ Function application is written omitted in (f x) y.will always refer to the negate function deﬁned in the Prelude.3. There is no link between the local meaning of the . The binary . Application associates to the left. it may be rebound by the module system. ) > ¦ ¢ ¡ A !§ ¡ 8 8 ¥¥8 ¡ § \ > ¡ ¢ ¡ £5¢ ¡ ¢ S ¢ ¢ ¡ ¢¢ ¨ £§S¢0 ¡ 6 6 ¡ ¡ ¡ function application lambda abstraction ¡ ¡ ¢ 2 ¢ ¡ ¢ ¡ 0 .denotes preﬁx negation. CURRIED APPLICATIONS AND LAMBDA ABSTRACTIONS 19 3. if the pattern fails to match. Because tors are allowed. it may legally be written as \(x:xs)>x.3. The set of patterns must be linear—no variable may appear more than once in the set. However.operator and unary negation. Preﬁx negation has the same precedence as the inﬁx operator . and is syntax for negate . and does not denote (\ x > x)—one must use negate for that. unary .
5 Sections ¢ S ¤ v ¡ ¢ S ¡ v ¡ p v ¢ A5e ¡ 2  Syntactic precedence rules apply to sections as follows. () is not a section. but (+a+b) is not. As another example. (a+b+) is syntactically correct. there is a subtract function deﬁned in the Prelude such that (subtract ) is equivalent to the disallowed section. EXPRESSIONS 3. Because (+) is left associative. ( ) is legal if and only if (x ) ( )). 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 . but (+a*b) and (*(a+b)) are valid. ( )  right section ) ¡ 2 ¡ 2 ¡ 2 ¡ ¡ ¡ 2 ¢ ¡ ( ( ( ) ) left section left section right section is an expression. as described in the preceding section. However. ¢ S ¡ 2 Sections are written as ( ) or ( ).  £ ¡ ¤ ¢ ( ) negate ¡ 2 £ ¤ ¡ 2 ¢ ¡ p v £!e ¢ $ ¡ ¡ 2 ) 2 p v ¢ ¡e ¡ ) 2 p v ¢ 0e ¡ $ 2 v S ¢ ¡ ¡ 7 ¢ ¡ ¡ ¡ 2 v 6 ¡ ¢ ¡ ¡ ¢ S ¢ . The expression (+ ()) can serve the same purpose. the latter may legally be written as (+(a+b)).is treated specially in the grammar.20 Translation: The following identities hold: CHAPTER 3. and similarly for ( ). where is a binary operator and Sections are a convenient syntax for partial application of binary operators. (*a+b) is synparses in the same way as (x tactically invalid. the expression (let n = 10 in n +) is invalid because. For example. but an application of preﬁx negation. by the let/lambda metarule (Section 3).
6.7 Lists [] ( ) : . Standard operations on lists are given in the Prelude (see Section 6. is a binary operator. denoted []. The type of type of the entire conditional expression. ¢ ¢ S 8 8 ¥¥8 4 © 3¦ 2 2 ©¦ 2 4 © ¦ 3¡ 32 8 8 ¥¥8 ¡ ¦ 2 ¦ 2 ¢ ¡ [ . and the empty list is Lists are written [ . if is False. is an expression. as deﬁned in the must be Bool.6 Conditionals ¥ ¢ ¡ Translation: ¡ ¢ The following identity holds: ¥ ¢ £ ¢ ¡ ¤ where True and False are the two nullary constructors from the type Bool.3. which is also the Prelude.1. ¥ £ ¡ 3. False > } £ ¥ A conditional expression has the form if then else value of is True.1). £ ¡ £ ¢ S ¡ ¤ ¡ ¢ ¡ if then else ¢ ¡ ¡ ¡ ¥ ¢ ¡ ¡ ¢ ¡ 6 6 6 6 6 6 6 6 ¡ 2 where . ]. CONDITIONALS Translation: The following identities hold: 21 3. and otherwise. 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 ¢ . and must have the same type. ] ¢ ¡¡ £ ¥ ¢ ¡ ¢ ¡ ¡ 2 ¡¡ £ ¤ if then else case of { True > . The list constructor is :.3. . where . and Chapter 8 notably Section 8.
EXPRESSIONS where : and [] are constructors for lists. and is equivalent to .1. and cannot be hidden or redeﬁned. The types of through must all be the same (call it ).8 Tuples ¢ S (. It is the only member of that type apart from . ) Tuples are written ( .. and the type of the overall expression is [ ] (see Section 4. The unit expression () has type () (see Section 4. . . .2).2). where there are denote the same value. ) ¤ ¢ 8 8 ¥¥8 £ ¡ ¢ ¡¡ 8 8 ¥¥8 ¡ ¡ ¤ [ . respectively. . ). .1.1. . Thus (a.1. ¢ ¡ ( () ) ¦ ¤ ¢ ¡ ¢ ¡¦ § § 8 8 ¥¥8 ¤ ¢ ¡§ ¡§ 8 8 ¥¥8 8 8 ¥¥8 8 8 ¥¥8 ¡ ¦ 2 ¢ ¡ ( .1.4 and Chapter 8). as deﬁned in the Prelude (see Section 6. with precedence level 5 (Section 4.).) a b c tuple is denoted by (. .c) and (. it is considered part of the language syntax.2). . then the type of the resulting tuple is ( .2). Standard operations on tuples are given in the Prelude (see Section 6. § 3. and requires no translation. ) (see Section 4. .1. If through are the types of through . like []. It is a rightassociative operator. The constructor “:” is reserved solely for list construction. 3. Translation: ( ) is equivalent to . ) for is an instance of a tuple as deﬁned in the Prelude.5)..3).22 Translation: The following identity holds: CHAPTER 3.9 Unit Expressions and Parenthesized Expressions ¡¦ 2 The form ( ) is simply a parenthesized expression. Translation: ( . and can be thought of as the “nullary tuple” (see Section 6.b. and may be of arbitrary length .4. ] : ( : ( ( : []))) ¡ ¡ ¢ 6 6 6 6 ¡ ¦ 32 ¦ 32 ¡ ¡ § ¢ S ¢ S ¢ ¢ . The constructor for an commas.
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. . See Section 6. ] .3. § ¥ ¢ £ ¤ ¡ § § ¨ £ ¢ ¡ ¡ ¡ ¢ ¡ [ ..10 Arithmetic Sequences ¨ ¥ ¡ $ ¢ ¡ Translation: Arithmetic sequences satisfy these identities: ¡ where enumFrom. depthﬁrst evaluation of the generators in the qualiﬁer list. . . ] .3. ARITHMETIC SEQUENCES 23 3.10. ] list comprehension generator local declaration guard ¥¤ £ ¡ ¥ ¢ ¡ £ ¡ 7 3¢ ¥ ¢ 7 ¢ ¥ ¢ £ ¤ £ ¤ ¡¢ ¡¢ ¡¢ ¡ ¢ [ [ [ [ .. .1. and is an instance of class Enum. Such a list comprehension returns the list of elements produced by evaluating in the successive environments created by the nested.4 for more details of which Prelude types are in Enum and their semantics. § 3. ] denotes a list of values of type . enumFromThen. ] . where each of the has type . where is a pattern (see Section 3.17) of type v ¦ A ¥ 8 8 ¥¥8 ¡ A list comprehension has the form [  . The semantics of arithmetic sequences therefore depends entirely on the instance declaration for the type .. § generators of the form expression of type [ ] § <. .11 List Comprehensions ¦ A 8 8 ¥¥8 ¡ guards. enumFromTo... .. ] where the qualiﬁers are either and is an ¡ ¡ $ © ¢ ¡ 7 ¦ ¢ ¡ [  <let § . and enumFromThenTo are class methods in the class Enum as deﬁned in the Prelude (see Figure 6.. page 83). ¡ ¡ ¡ ¡ ¢ £¡ ¢ ¡ 6 6 6 7 ¢ 3¢ S ¡ ¢ ¡ ¢ S $ ¢ ] . ] enumFrom enumFromThen enumFromTo enumFromThenTo v The arithmetic sequence [ .
As usual.2)] ].4). which may be used as a translation into the kernel: where ranges over expressions. over qualiﬁers.(3. ]  <.2]. ok is a fresh variable. A ¦ 8 8 ¥¥8 ¡ ¦ let in ' © 7 ¡ ¡ © 7 ¦ © 7 ¥ ¦ [  let .2).12 Let Expressions ¢ ¡ © Let expressions have the general form let { . expressions.are lambda bound and are thus monomorphic (see Section 4. and introduce a nested. (3. x <. True ] if then [  let ok = [  ok _ = [] in concatMap ok let in [  [ x  x <. over listvalued expressions.x ] [ z  y <. If a qualiﬁer is a guard. and if a match fails then that element of the list is simply skipped over. Declarations are described in Chapter 4.x) <. As indicated by the translation of list comprehensions. it must evaluate to True for the previous pattern match to succeed. let (x. lexicallyscoped. over boolean over declaration lists.(3. 3.y] ] else [] ] ] 6 ¡ ¢ ¡ . variables bound by let have fully polymorphic types while those deﬁned by <.xs ] yields the list [4. For example. z <. and boolean value True.4). = = = = [ ] [  . bindings in list comprehensions can shadow those in outer scopes.24 CHAPTER 3. and over sequences of qualiﬁers.[ [(1. .17). for example: Translation: List comprehensions satisfy these identities. an implicit ˜ makes these patterns irrefutable. Pattern bindings are matched lazily. EXPRESSIONS Binding of variables occurs according to the normal pattern matching rules (see Section 3.x. are deﬁned in the Prelude. The scope of the declarations is the expression and the right hand side of the declarations. [(5. mutuallyrecursive list of declarations (let is often called letrec in other languages).y) = undefined in does not cause an executiontime error until x or y is evaluated. Thus: [ x  xs <.x. The function concatMap.4)].. ] = 7 ] ¡ 7 ¥ ¦ ' 7 ¥ ¦ 7 ' ¡ [ [ [ [  True ]  ]  . } in .5. over patterns.
4.. } in are captured by this translation: After removing all type signatures.˜ ) = ( . . not the syntactic metasymbol for alternation.. Note the use of the irrefutable patterns ˜ . 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 { . these identities hold.4. where and are patterns and expressions respectively. ) in case of ˜ > where no variable in appears free in let = fix ( \ ˜ > ) in ¡ ¢ ¨ ££ ¦¥£ ¡ § ¢ £¡ ¦ © @§ ¡ § 7 3¢ 7¡ 3 ¢ ¢ ¦ . Once done. . which may be used as a translation into the kernel: ¡ where fix is the least ﬁxpoint operator.) Each alternative consists of a pattern and its matches. . CASE EXPRESSIONS Translation: The dynamic semantics of the expression let { 25 . Each match in turn consists of a sequence of pairs of guards and bodies (expressions). . the “” is a terminal symbol. where where ¡ £ ¡ 7 3¢ ¡ ¡ ¢ ¡ ¦ ¡ ¢ 6 6 6 6 6 let = in = ¨ ¡ ¡ ¥ ¡ ¢ ¨ © ¡ ¡ ¡ ¨ ¨ © ¡ ¢ ¡ ¡ ¡ ¥ ¢ let { = let = . followed by optional bindings ( ) that scope over all of the guards and expressions of the alternative. .. . This translation does not preserve the static semantics because the use of case precludes a fully polymorphic typing of the bound variables.13 Case Expressions A case expression has the general form (Notice that in the syntax rule for .3.13. in = } in = = let (˜ . each declaration is translated into an equation of the form = . . ¥ § ¢ ¡ ¢ ¡ ¢ ¡  ¨ § ¢ ¡ > ¤ } 3 § § ¢ ¦¤ 5 § 7 3¢ %§ ¡ 4 ¦ ¨ © ¨ 5© 7 ¦ 7 ¥ ¦ © @§ ¢ £¡ ¦ ¡ A§ 7 3¢ £¡ ¦ ¢ ¢ £¡ ¢ ¡ § ¡ ¥8¥8 ¢ £¡ ¡§ 8 7 3¢ § ¢ S case . . > ¦§ of { } . The static semantics of the bindings in a let expression are described in Section 4.3. 3. ..3... using the translation in Section 4.
and hence reject the program. It has a single unambiguous parse. namely case x of { (a. and then by the guards evaluates to True. The expression case x of { (a._)  (let b = not a in b :: Bool) > a } However.26 CHAPTER 3. A note about parsing. matching continues with the next alternative. Each body must have the same type. If matches the pattern in the alternative._)  let b = not a in b :: Bool > a } is tricky to parse correctly. ¦ 3. A case expression is evaluated by pattern matching the expression against the individual alternatives. 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 <.17. ¦ ¨ .14 Do Expressions A do expression provides a more conventional syntax for monadic programming. the corresponding righthand side is evaluated in the same environment as the guard. Pattern matching is described in Section 3.17. and the type of the whole expression is that type. If one of the pattern. 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. The alternatives are tried sequentially. to avoid guards that end with a type signature — indeed that is why a contains an not an . the result is . and parsers with limited lookahead may incorrectly commit to this choice. If all the guards evaluate to False. If no match succeeds. the guards for that alternative are tried sequentially from top to bottom. . . <let . Programmers are advised.getLine return (words l) § § § ¦ 4 ¢ © %§ ¡ 4 ¥ © . EXPRESSIONS A case expression must have at least one alternative and each alternative must have at least one body. from top to bottom. the phrase Bool > a is syntactically valid as a type.3. ¦ § ¡ 7 ¦ ¢ ¡ § ¡ ¢¡ £ ¡ ¢ ¡ ¢S A § 4 §¤© 8¥8¥8 ¡ § 4 § © 4§ © © @§ do { } do expression v © 7 ¥ ¦ ¡ ¢ S 6 6 6 ¤ ¥¡ © @§ ¢ ¡ § ¡ 4§ 4§ © © ¢ ¡ . therefore. with the formal semantics of case expressions in Section 3.
© The ellipsis ". after eliminating empty : } .OK .1). 3. and update ﬁelds in a manner that is independent of the overall structure of the datatype. consider: data S = S1 { x :: Int }  S2 { x :: Int } data T = T1 { y :: Int }  T2 { y :: Bool } . a ﬁeld label can be used in more than one constructor provided the ﬁeld has the same typing in all constructors. and fail are operations in the class Monad. Within a datatype.15.2. To illustrate the last point.3). because y is given inconsistent typings in the latter. variables bound by let have fully polymorphic types while those deﬁned by <. the functions >>.1 Field Selection ¤ ¢ Field labels are used as selector functions.15. DATATYPES WITH FIELD LABELS 27 Translation: Do expressions satisfy these identities.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." stands for a compilergenerated error message. © @§ 4§ © © © @§ 4§ © © do {let . These ﬁeld labels can be used to construct. do { < © @§ 4 ¤© § = = = ¦ 4 ¤© § } = do { } _ = fail ". Different datatypes cannot share common ﬁeld labels in the same scope. } = © @§ 4 ¤© § } © @§ 4 ¤© ¡ § >> do let ok ok in let 7 ¥ ¦ © @§ 4§ 7 © @§ do { } do { . a ﬁeld label serves as a function that extracts the ﬁeld from an object. however.3. in record construction (Section 3." >>= ok in do { } { ¡ 6 ¡ ¢ S ¢ . and ok is a fresh identiﬁer. As indicated by the translation of do. When used as a variable. select from. A ﬁeld label can be used at most once in a constructor. which may be used as a translation into the kernel... 3..15 Datatypes with Field Labels A datatype declaration may optionally deﬁne ﬁeld labels (see Section 4.2) and update (Section 3. ﬁeld labels cannot be confused with ordinary variables.are lambda bound and are thus monomorphic. >>=. This shadowing only affects selector functions. preferably giving some indication of the location of the patternmatch failure. passed to fail..BAD Here S is legal but T is not. as deﬁned in the Prelude.15.
where F is a data constructor. 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.15. . then value . is deﬁned as follows: has the ﬁeld label . ¦ § v ¦ v where are all the constructors of the datatype containing a ﬁeld labeled with . it denotes F . The expression F {}. Unlike the braces used in declaration lists. undefined A 8 8 ¥¥8 ¡ 8 8 ¥¥8 ¡ ¡ ¦ ¡§ ¢ ¡ 0 { = . A ﬁeld label may not be mentioned more than once. and if appears is .) 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. Otherwise.28 Translation: x 0 CHAPTER 3. 0 v v P ¡ A 8 8 ¥¥8 ¡ ¢ ¦ ¡ ' 8 8 ¥¥8 ¡ ¡ ¡ = case x of { > . EXPRESSIONS A ﬁeld label 0 ' introduces a selector function deﬁned as: 3.1. is the default © § 8 8 ¥¥8 © ¡ § © { } = undefined ' ¡ £¢ ¡ 0 ' ¡ ¢¢ 0 Translation: ' In the binding = . © ' ¡ ¢ v § ¡ ¦ © ¡ ¢ v © ' § ¡ where is the arity of The auxiliary function § . 0 ¦ © ' ¡ ¢ v 0 § ¡ ¦ If the th component of a constructor in the binding list . the ﬁeld labels . } labeled construction . these are not subject to layout. (This is also true of ﬁeld updates and ﬁeld patterns. . and is y when some ﬁeld in has a label of or undefined otherwise. the { and } characters must be explicit. A ¥¥8 ¡ A A 8 8 ¡ ¡ ¡ ¡ > } ¦ ' ¤ ¦ ¢2 A 8 8 ¥¥8 ¡ 0 ¦ 6 6 0 ¢ ¦ ¦ ¡ ¦§ ¢ S ' ¢ 0 .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. Strict ﬁelds are discussed in Section 4. 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.
This example translates expressions using constructors in ﬁeldlabel notation into equivalent expressions using the same constructors without ﬁeld labels. .3 Updates Using Field Labels ¦ A ¦§ ¡ 0 § Values belonging to a datatype with ﬁeld labels may be nondestructively updated. T© § 8 8 ¥¥8 ¡ T© ¡ ¡ § § ¡ > ¢ ' ¢ ¡ ¢ ¡ ' ¡ ¢ { } ¡ ¡ = case of ¢ £ ¡ 8 8 ¥¥8 8 8 ¥¥8 ¡ 8 8 ¥¥8 ¡ ¡ ¡ ¦§ 0 { .15. This creates a new value in which the speciﬁed ﬁeld values replace those in the existing value.f2 :: Int}  C2 {f1 :: Int. f3. A compiletime error will result if no single constructor deﬁnes the set of ﬁeld labels used in an update. f3 = ’B’} x {f1 = 1} The ﬁeld f1 is common to both constructors in T.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.3. An execution error occurs when the value being updated does not contain all of the speciﬁed labels. At least one constructor must deﬁne all of the labels mentioned in the update. such as x {f2 = 1. f3 = ’x’}. v © ¥¥8 ¡ 8 8 where . Updates are restricted in the following ways: All labels must be taken from the same datatype.15. DATATYPES WITH FIELD LABELS 29 3.. Translation: © Using the prior deﬁnition of Here are some examples using labeled ﬁelds: data T = C1 {f1.. } labeled update . f4 = ’A’. v is the set of constructors containing all labels in . and is the arity of £ F© £ ¢ § 8 8 ¥¥8 ¡ > _ > error "Update error" T© ' £ ¡ ¢ ¡ ' ' £ ¡ ¢ . No label may be mentioned more than once. ¦ ' ¦ ' ) A9g© ¨ ¡ ¢ ¡ ¢ 6 ' ¡ ¢ S ¢ .
1. } ¦§ ¢ ¦ 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 Patterns Patterns have this syntax: § 8 8 ¥¥8 ¡§ 0 { . they are used to type an expression explicitly and may be used to resolve ambiguous typings due to overloading (see Section 4.17. Translation: 3. .30 CHAPTER 3. so deﬁning the semantics of pattern matching for case expressions is sufﬁcient. list comprehensions.1). but it is an error to give a type that is more general than. where is an expression and is a type (Section 4.3. the ﬁrst ﬁve of these ultimately translate into case expressions. the principal type. do expressions. pattern bindings.4.17 Pattern Matching Patterns appear in lambda abstractions. the declared type may be more speciﬁc than the . EXPRESSIONS 3. However. and case expressions.2). As with normal type signatures (see Section 4.4). function deﬁnitions.16 Expression TypeSignatures %§ 0 Expression typesignatures have the form :: . The value of the expression is just that of . 3. or not principal type derivable from comparable to.
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.x) = x . For example. ¢ ¡ ¢ £¡ ¢ £¡ ¤ § ¢£§¢ ¡ ¡§ ¢£¡ ¡§ ¢£¡ ¢ £¡ § _ ( ( [ ˜ wildcard parenthesized pattern tuple pattern list pattern irrefutable pattern ¢ ¤ ¢ 6 § ¢ £¡ 0 . ¢ § ._] is equivalent to: case e of { [x. it may succeed. case e of { [x. All patterns must be linear —no variable may appear more than once. PATTERN MATCHING 31 The arity of a constructor must match the number of subpatterns associated with it. For example.3. value being matched by § § ¢ ¢ § = as a name for the to . or it may diverge (i.y.ILLEGAL.17. . and outside to inside. according to the following rules: ¤ ¤ 1._.e.2 Informal Semantics of Pattern Matching Patterns are matched against values. one cannot match against a partiallyapplied constructor. It is as if an identiﬁer not used elsewhere were put in its place. and allow one to use . returning a binding for each variable in the pattern. Pattern matching proceeds from left to right. return ). ) ] ¤ ¢ £¡ ¢ § £¡ ¢ 8¥¥8 8 8 8 ¥¥8 ) . . this deﬁnition is illegal: f (x.17. Matching the pattern against a value always succeeds and binds ¤ ¢ Patterns of the form @ are called aspatterns.z] > if x==0 then True else False } > if x==0 then True else False } 3. Attempting to match a pattern can have one of three results: it may fail. For example.
constructors associated with newtype serve only to change the type of a value. 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. character.32 CHAPTER 3. and to if matching against fails or diverges. where is a different constructor to ¦ 32 A 8 8 ¥¥8 ¡ A !§ 8 8 ¥¥8 ¡ § 5. The match diverges if the comparison diverges. 1 ¦ 2 ¦ 32 7 ¦ 8 8 ¥¥8 ¡ r1 32 If the value is of the form the match fails. where newtype. If the value is of the form . The free variables in are bound to the appropriate values if matching against would otherwise succeed. resulting in the binding of to .are overloaded. Again. depending on the type of the pattern. 6. Fields not named by the pattern are ignored (matched against _). At that point the entire pattern is matched against the value. depends on the value: against a value. Matching the wildcard pattern _ against any value always succeeds. that is. . this means that no matching is done on a ˜ pattern until one of the variables in is used. The interpretation of numeric literals is exactly as described in Section 3.2. so does the overall computation. Matching a numeric.. is the same as in numeric literal patterns. EXPRESSIONS 2. if all matches succeed. Matching an + pattern (where is a variable and is a positive integer literal) against a value succeeds if >= . Matching the pattern against a value. The interpretation of the literal integer literals are allowed. or string literal pattern against a value succeeds if == . (Binding does not imply evaluation. Matching the pattern by data. the overall match succeeds. All ﬁelds listed must be declared by the constructor. except that only ¢ ¢ ¢ ¦ ¢ ¢ ¦ ¢ ¢ ¢ If the value is . ¦ 32 4. ﬁelds may not be named more than once. the functions >= and . then is matched against . 7. § § § That is. then is matched against . the match diverges. § ¦ Q32 If the value is of the form . where ¢ £¡ ¦ 32 § ¢ £¡ ¦ 32 If the value is . The match diverges if this test diverges. 8. Matching the pattern ˜ against a value always succeeds.) Operationally. 3. where == is overloaded based on the type of the pattern. the overloaded function fromInteger or fromRational is applied to an Integer or Rational literal (resp) to convert it to the appropriate type. and no binding is done. . respectively. depends on the value: is a constructor deﬁned by is a constructor deﬁned ¢ ¡ £5¢ ¢ ¡ £§¢ § ¢ ¡ £§¢ ¢ £¡ § ¢ £¡ ¢ ¡ § ¦ 2 ¢ ¡ £5¢ § ¢ ¡ £§¢ ¢ ¦ ¢ ¡ £§¢ . subpatterns are matched lefttoright against the components of the data value. the ﬁrst to fail or diverge causes the overall match to fail or diverge. and if the match fails or diverges. and fails otherwise.
But if [’a’.1) § ¢ ¡ £5¢ § ¢ ¡ £§¢ © § 7 ¢ 0 § ¢ ¡ £§¢ %¥ § ¤ § ¢ §¢ ¡ ¦ § ¤ ¢ ¡ £§¢ § ¢ @ 9.b)] > x) [(0.˜(a. ]. If the pattern [’a’. Matching a refutable pattern is strict: if the value to be matched is the match diverges. ] (\ ˜[x. Matching an irrefutable pattern is nonstrict: the pattern matches even if the value to be matched is .’x’]. PATTERN MATCHING § 33 against a value is the result of matching against . irrefutable matching: (\ ˜(x. to . All other patterns are refutable.y) > 0) (\ (x.2. These patterns may be removed or changed in future versions of Haskell. then ’a’ to match against ’x’. If the match of against fails or diverges. a wildcard. is irrefutable). and the result is a failed match. ] (0. where is a constructor deﬁned by newtype and is irrefutable @ where is irrefutable. A ﬂoating literal pattern can only be matched against a value in the class Fractional. An + pattern can only be matched against a value in the class Integral. it is a static error to match a character against a boolean).1). ¢ ¡ £§¢ ¢ ¡ £§¢ E ¤ ¢ § ¢§ ¡ £§¢ ¢ ¡ £§¢ ¢ ¦ ¤ ¢E ¢ ¦ . or of the form ˜ (whether or not (see Section 4.3). the following static class constraints hold: An integer literal pattern can only be matched against a value in the class Num. Many people feel that + patterns should not be used.’b’] is matched against [’x’. The irrefutable patterns are as follows: a variable.’b’] is matched against [ . It is sometimes helpful to distinguish two kinds of patterns.3. then Aside from the obvious static type constraints (for example. These examples demonstrate refutable vs. Matching an aspattern augmented with the binding of so does the overall match. (a.b)] > x) [(0.1). Consider the following declarations: newtype N = N Bool data D = D !Bool (\ (x:xs) > x:x:xs) (\ ˜(x:xs) > x:x:xs) (\ ˜[x. then .y) > 0) (\ ˜[x] > 0) [] (\ ˜[x] > x) [] 0 0 : : 3. attempting to match ’a’ against causes the match to 2. Here are some examples: 1.17.
v ¥ § Rule (b) matches a general sourcelanguage case expression. function deﬁnition. 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.3. 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. (e). in f :: (Int. then True is substituted for the guards in the forms. and is a newtype constructor. Subsequent identities manipulate the resulting case expression into simpler and simpler forms. ¢ ¡ 4 v ¢ 3 v ¤ 1 (\ (N True) > True) (\ (D True) > True) (\ ˜(D True) > True) True E v v ¤¢ 1 ¢ v ¡ . or pattern binding to which it is attached.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. In particular.Int) > [Int] > Int f ˜(x. and are variables. For example. Rules (d). A guard is a boolean expression that is evaluated only after all of the arguments have been successfully matched. The semantics of case expressions themselves are in turn given as a series of identities. 3. .y.34 CHAPTER 3. . and are expressions. (j). it is this rule that deﬁnes the meaning of pattern matching against overloaded constants. The guard semantics have an obvious inﬂuence on the strictness characteristics of a function or case expression.z) [a]  (a == y) = 1 both a and y will be evaluated by == in the guard. These identities all preserve the static semantics.2. In Figures 3. and are booleanvalued expressions. in Figures 3. Rule (h) in Figure 3. Any implementation should behave so that these identities hold.1–3.1.2 involves the overloaded operator ==. since that would generate rather inefﬁcient code.4). (q). and are algebraic datatype (data) constructors (including tuple constructors). this indicates that variables bound by case are monomorphically typed (Section 4.2: . regardless of whether it actually includes guards—if no guards are written.Int.1–3. and (s) use a lambda rather than a let.2. an otherwise irrefutable pattern may be evaluated because of a guard. and are patterns. and it must be true for the overall pattern match to succeed. The environment of the guard is the same as the righthandside of the caseexpression alternative.17. it is not expected that it will use them directly.
. Part 1 G @ § (f) case of { _ > . > error "No match" } ¡ ! ¨ ££ ¥¦£ © £ ¡ © ¨ © ¡ © ¨ # $£ § § (b) . _ > } $C ¨ § ££ ¦¥£ © DC ¨ ¨ @ § ¨ $C¦E£¥¥¦FC ££E © ££ © ¥¦£ C C $3 § (d) case (\ where of { ˜ > .1: Semantics of Case Expressions. PATTERN MATCHING 35 . } } .  } else ££ ¥¦£ _ £ ¡ ! § ¨ ££ ¥¥£ > case of { . }) ¡ "£ § § £ ¡ (a) case of { } where is a new variable case of { case of { _ § (\ > case of { ¥ £ ¦¤¢ ¥ £ ¦¤¢ }) . Figure 3.17. _ > } @ § @ C ¨ ¨ C § § (e) case of { @ > . where { } } then 10 > where { # ¥ ¢ 32 ( & )' ¤# ( & )' ¤# % ££ ¦¥£ © & ¤# ¡ ! where each  > © & ¤# % has the form: .3. . _ > } > ) (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 {   > > > . _ > } case of { > ( \ > ) .
_ > is a newtype constructor @ @ ¨ ¨ ¢ § § ¢ (k) case of { > . _ > } if >= then (\ > ) ( . ££ ¥¦£ @ ¨ C ££ ¦¥£ @ © C > case © ¨ of { > case _ > } @ ¨ ££ ¥¦£ © ¨ ¦ C ££ ¦¥£ © C § ¨ § (g) case of { case of { > . respectively @ @ ¨ ¨ ¤ ¨ ¤ ££ ¥¦£ § ¨ © ¨ § (n) case of { case of { # { = } > . ¦" C E £££ ¥¦¥E © C 28 ¨ E £££ ¥¦¥E @ © ¨ _ > at least one of } is not a variable. _ > } case ( ) of { > . _ > } of { > . _ > _ > }} where . _ > } @ @ © $C ££ ¥¦£ © C ££ ¦¥£ @ © 4 @ (p) @ @ ' ££ ¥¥£ § § (o) > . = . or string literal. _ > } where and are distinct data constructors of arity and . _ > } . EXPRESSIONS Figure 3. _ otherwise case of { {} > .2: Semantics of Case Expressions.) else where is a numeric literal ¡ £ @ © C ££ ¥¦£ © C £ (r) case where of { > . . _ > } if ( == ) then is a numeric. } > . _ > case of { > case of { { = } > case of { { = . character. _ > } case of { > . } > . Part 2 @ ¡ § @ C ¡ C ¡ § § (s) case of { + > . _ > } where is a newtype constructor ¢ } case § C C § (j) case of { > } ( \ > ) of { C § @ C § (i) case of { > . are new variables else } } }.36 CHAPTER 3. _ > } A @ ££ ¥¥£ ££ ¦¥£ ¥ ¥ §¨ ¨ A ¥ ¤ ¥ ¦¤ © ¨ © ¤ A § © ¨ © 5¤ ££ ¥¥£ ¥ ¤ § @ § (m) case of { { = . _ > } where is if labels the th component of . _ > is a data constructor of arity } @ C ££ ¥¦£ © © C ££ ¥¦£ © ££ ¥¦£ C © ££ ¦¥£ (q) case ( ) of { (\ > ) where is a data constructor of arity © C > . _ > } case of { > } > @ F ¡ § @ F ¡ § (h) ¡ case where of { > . are ﬁelds of constructor . is a new variable © 7¤ A ¨ £ @ ¨ ¢ £ (l) ¢ case where of { > . _ > } case of { _ _ > .
} = = 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 . = => => => => . } } © 2§ . . we describe the syntax and informal semantics of Haskell declarations. . module where 2 ¨ ©§ ¤ 5@¤32 ¢ ¡ § 2 4 ¦ ' { { { . ¦ { . } ¦ A 8 8 ¥¥8 ¡ ¦ $ ¥ £0 7 ¦ ¦ { . type data newtype class instance default ( .¦ § 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 ¦ ¦ { . . .
type classes and overloading. but the type system has been extended with type classes (or just classes) that provide a structured way to introduce overloaded functions. and ﬁxity declarations (Section 4. using normal type and data declarations.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. A class declaration (Section 4. For example. Haskell has several primitive datatypes that are “hardwired” (such as integers and ﬂoatingpoint numbers). instance. and default declarations (Section 4.1 Overview of Types and Classes Haskell uses a traditional HindleyMilner polymorphic type system to provide a static type semantics [3. newtype.(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. of the given types.1) introduces a new type class and the overloaded operations that must be supported by any type that is an instance of that class. . 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 ¡ . . consisting of value bindings. .4). and data declarations (Section 4. An instance declaration (Section 4. and nested declarations. type signatures. We introduce a new type class called Num: class Num a where (+) :: a > a > a negate :: a > a .2).38 %§ CHAPTER 4. but most “builtin” datatypes are deﬁned with normal Haskell code.3). 5]. For exposition. suppose we wish to overload the operations (+) and negate on types Int and Float. DECLARATIONS AND BINDINGS The declarations in the syntactic category are only allowed at the top level of a Haskell module (see Chapter 5). deﬁned on it. These “builtin” datatypes are described in detail in Section 6.simplified class declaration for Num . those within a let or where construct).3. whereas may be used either at the top level or in nested scopes (i.3.e. © 4. consisting of type. consisting of class.1. we divide the declarations into three groups: userdeﬁned datatypes.” We may then declare Int and Float to be instances of this class: .
type expressions are classiﬁed into different kinds. then a type of kind .1. ‘type class’ includes both the original Haskell type classes and the constructor classes introduced by Jones. ] ) . OVERVIEW OF TYPES AND CLASSES 39 instance Num Int where . Kind inference is discussed in Section 4. but in general could be any userdeﬁned function. The term ‘type class’ was used to describe the original Haskell 1.e. is the kind of types that take a type of kind and return ¤ ¥¡ 6 6 6 ¢ £¡ ¡ ¡ %§ %§ ¡ %§ ' ¢ . There is no longer any reason to use two different terms: in this report. unlike types. 4.1. ¡ ¡ ¢ ¨ ¤ ¡ B%§ ¦ 32 ¢ %§ ¡ ¤ ¡ ¡ %§ %§ ' ' The symbol represents the kind of all nullary type constructors.simplified instance of Num Float x + y = addFloat x y negate x = negateFloat x where addInt.2 Syntax of Types ¨ %§ > %§ function type %§ 8 8 ¥¥8 ¡ ¤ ¡ ¡ %§ %§ %§ ( [ ( . However. negateInt. 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.6. ‘constructor class’ was used to describe an extension to the original type classes.” More examples of type classes can be found in the papers by Jones [7] or Wadler and Blott [12]. 4.0 type system.1 Kinds To ensure that they are valid. class methods) for (+) and negate.1. The ﬁrst declaration above may be read “Int is an instance of the class Num as witnessed by these deﬁnitions (i. addFloat. and negateFloat are assumed in this case to be primitive functions. kinds are entirely implicit and are not a visible part of the language. ) tuple type list type parenthesised constructor ¤ type application ¢ ©¡ ¢ ¤ ¡ ¨§6 ¦¡ ¢ ¡ If and are kinds.simplified instance of Num Int x + y = addInt x y negate x = negateInt x instance Num Float where .4.
The main forms of type expression are as follows: 1.. IO. For example: Char. and so on.. and classes. 2. DECLARATIONS AND BINDINGS The syntax for Haskell type expressions is given above. It denotes the “nullary tuple” type. Float. and treated as types with kind . written as identiﬁers beginning with a lowercase letter. is identical to the type . Special syntax is provided to allow certain type expressions to be written in a more traditional style: § § ¤ ¢ ¡ ¡ ¢ ¡ ¤ ¡ 6 ¤ ¡ 6 ¢ ¡ 3. Since the IO type constructor has kind . and so on. also written () (see Sections 3. Int. and is a type of kind . Unlike data constructors. Type application. ) 6 2§ $ § © ¦ ¤ ¤32 ¡ %§ ¤ ¡ ¢ ¡ ¦ 32 6 %§ 6 6 6 ¦ 32 %§ unit type list constructor function constructor tupling constructors . Type variables. © S¤ Special syntax is provided for certain builtin type constructors: The trivial type is written as () and has kind . As with data constructors. If is a type of kind type expression of kind . A parenthesized type. the type expression IO a can be understood as the application of a constant.. IO a. Just as data values are built using data constructors. a process of kind inference (see Section 4. In general. .40 CHAPTER 4. Maybe and IO are unary type constructors. The list type is written as [] and has kind . The kind of a variable is determined implicitly by the context in which it appears. Integer. it follows that both the variable a and the whole expression. to the variable a. add the type constructor T to the type vocabulary.. type values are built from . Type constructors.6) is needed to determine appropriate kinds for userdeﬁned datatypes. must have kind . Most type constructors are written as an identiﬁer beginning with an uppercase letter. The tuple types are written as (. The kind of T is determined by kind inference. inﬁx type constructors are not allowed (other than (>)).5).9 and 6. . For example. having form ( ). then is a 6 6 6 6 6 () [] (>) (. the names of type constructors start with uppercase letters.). Use of the (>) and [] constants is described in more detail below. Their kinds are . and has exactly one value.1. The function type is written as (>) and has kind .).. type synonyms. (. The declarations data T . Double and Bool are type constants with kind . 4. or newtype T .
the scope of the extends as far to the right as possible. then the expressions (\ > ). which is equivalent to the type (>) . the preﬁx type constructors (>). ¡§ £§ ¡§ v § 4. we often write quantiﬁcation explicitly when denotes the type discussing the types of Haskell programs. the second component of type . A function type has the form Function arrows associate to the right. they cannot be qualiﬁed. When we write an explicitly quantiﬁed type. A tuple type has the form ( . These special syntactic forms always denote the builtin type constructors for functions. there is no explicit syntax for universal quantiﬁcation [3]. their semantics is the same as the equivalent userdeﬁned algebraic data types.. regardless of what is in scope. above. respectively. tuples. ( With one exception (that of the distinguished type variable in a class declaration (Section 4.3).8 and 6. and so on (see Sections 3. . nor mentioned in import or export lists (Chapter 5).) Although the list and tuple types have special syntax.1. It denotes the type of lists with elements of type (see Sections 3. It denotes the type of tuples with the ﬁrst component of type .) where there are commas between the parenthesis. (.1. Notice that expressions and types have a consistent syntax. and so on. 3. A context consists of zero or more class assertions. (Hence the special production. In a similar way. however.1.4. Int > Int > Float means Int > (Int > Float). [ ]. . For example. and indicates the membership of the type in the class . []. ) where . 2. the type variables in a Haskell type expression are all assumed to be universally quantiﬁed. and ( ) have the types ( > ). .7 and 6. and ). [ ]. always denote the builtin type constructors. 1. (). and lists. “gtycon”. the type expression a > a . for example. which is equivalent to the type [] .3 Syntax of Class Assertions and Contexts . A class assertion has form . A class identiﬁer begins with an uppercase letter. and has the general form A $ A 8 8 ¥¥8 ¡ $ ¡ ( ) ¤ ¢ %§ ¦ ( ) ¦ A © © ( .1)). .3. For example. If is the type of expression or pattern . means .1. which is equivalent to the type (. A list type has the form [ ]. ) £§ ¢ 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 %§ . For clarity.4). OVERVIEW OF TYPES AND CLASSES £§ ¡§ 41 £§ ¡§ > .). .
Functor f) => (a > b) > f a > f b > Bool In the third type. also holds. that can be assigned to a particular expression (in a given environment) is called its principal type. any of that are free in must also be free in . including the proper use of overloaded class methods (although certain ambiguous overloadings could arise. consider the function double: § if and only if the context ¡ ¢ ¢ 8 £ ¢ Whenever ¥ holds in the class environment. £ ¢ 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 ¢ ¥ ¡ £§ ¦ . Haskell’s extended HindleyMilner type system can infer the principal type of all expressions.1).1.16 and 4.4). in more detail.1.42 CHAPTER 4. up to the equivalence induced by the generalization preorder. £§ ¨ $ © ¢ © A value of type . For example. For example. " t ¡§ is identical to . or the application of type variable to one or more types. the constraint Eq (f a) cannot be made simpler because f is universally quantiﬁed. 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). as described in Section 4. may be instantiated at types holds. a type is of the form . Therefore. The outer parentheses may be omitted when . § § § 4. In general. Types are related by a generalization preorder (speciﬁed below). The context must only contain type variables referenced in . In general. Show a.4 Semantics of Types and Classes In this section. where is a set of type variables .3. (Wadler and Blott [12] and Jones [7] discuss type and constructor classes. 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).) The Haskell type system attributes a type to each expression in the program. DECLARATIONS AND BINDINGS where are class identiﬁers. here are some valid types: Eq a => a > a (Eq a. For convenience. we use to denote a context and we write => to indicate the type restricted by the context . In any such type. The type of an expression depends on a type environment that gives types for the free variables in . the most general type. although in this case the concrete syntax contains no =>. and each of the is either a type variable.4. we write => even if the context is empty. explicit typings (called type signatures) are usually optional (see Sections 3. Furthermore. respectively. we provide informal details of the type system.3.
An algebraic datatype declaration has the form: where is a context. } 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§ ¦ © . we describe algebraic datatypes (data declarations). This declaration introduces a new type constructor with one or more constituent data constructors .2 UserDeﬁned Datatypes In this section. double may be applied to values of type Int (instantiating to Int). In this Report. renamed datatypes (newtype declarations). ! . because Char is not normally an instance of class Num. 4.2. in which case double may indeed be applied to a Char.2. . since Num Int holds. 4. because Int is an instance of the class Num. ) ¦ § ¦ ¢ ¥ ¦ 7 A ¢ ¥ ¦ 7 { :: . 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 © ( . the unqualiﬁed term “constructor” always means “data constructor”. The user may choose to declare such an instance.4. However. and type synonyms (type declarations). USERDEFINED DATATYPES double x = x + x 43 The most general type of double is Num . double may not normally be applied to values of type Char.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)). These declarations may only appear at the top level of a module.
These components are normally accessed positionally as arguments to the constructor in expressions or patterns. it is a static error for any other type variable to appear in or on the righthandside. For example. 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. DECLARATIONS AND BINDINGS is the largest subset of that constrains only those type variables free in the types . using the record syntax (C { .3. The context in the data declaration has no other effect whatsoever..8.6. Pattern matching against ConsSet also gives rise to an Eq a constraint. }). The type variables through must be distinct and may appear in and the . For example: f (ConsSet a s) = a the function f has inferred type Eq a => Set a > a. The visibility of a datatype’s constructors (i. and is described in Section 4. to the components of a data object. The optional deriving part of a data declaration has to do with derived instances.f2 :: Int. Labelled Fields A data constructor of arity creates an object with components. A constructor with associated ﬁeld labels may still be used as an ordinary constructor. 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. 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 .44 ¢ v ¢ CHAPTER 4. A constructor deﬁnition in a data declaration may assign labels to the ﬁelds of the constructor. the declaration data Eq a => Set a = NilSet  ConsSet a (Set a) In the example given. For example. the declaration data C = F { f1. the overloaded type for ConsSet ensures that ConsSet can only be applied to values whose type is an instance of the class Eq. Constructors using ﬁeld labels may be freely mixed with constructors without them. This allows For large datatypes it is useful to assign a speciﬁc ﬁeld to be referenced independently of its location within the constructor..e. 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 . This means that may be used in type expressions with anywhere between and arguments. The arguments to the positional constructor occur in the same order as the labeled ﬁelds. features using labels are simply a shorthand for operations using an underlying positional constructor.3.
whether or not F was declared with record syntax. “!” is an ordinary varsym not a . Strictness Flags Whenever a data constructor is applied. The pattern F {} matches any value built with constructor F. Lexically.6. A label cannot be shared by more than one type in scope.4. USERDEFINED DATATYPES data C = F Int Int Bool 45 Operations using ﬁeld labels are described in Section 3. and function $! (see Section 6. denoted by an exclamation point. “!”. The type variables through must be distinct and are scoped only over . 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 ¡ $ ¡ # ¡ § § § . 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 .2 Type Synonym Declarations A type synonym declaration introduces a new type that is equivalent to an old type. 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. For example. each argument to the constructor is evaluated if and only if the corresponding type in the algebraic datatype declaration has a strictness ﬂag. 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 .2. it is a static error for any other type variable to appear in . it has special signiﬁcance only in the context of the argument types of a data declaration. . The type is equivalent to the type .15.2. Translation: A declaration of the form 4.2) if is of the form ! . Pattern matching on strictness ﬂags. 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. It has the form § $ which introduces a new type constructor. 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.
the newtype constructor is unlifted. DECLARATIONS AND BINDINGS Type constructor symbols introduced by type synonym declarations cannot be partially applied. Also. so that is the same as . The type ( ) renames the datatype .invalid .3. mechanism to make type signatures more readable. unlike type synonyms. newtype may be used to deﬁne recursive types.3. Type synonyms are a convenient. type Rec a data Circ a is allowed. A synonym and its deﬁnition are completely interchangeable. but strictly syntactic. unless an algebraic datatype intervenes. For example. Using in a pattern coerces a value from type ( ) to type .2) can be deﬁned for a type deﬁned by newtype but may not be deﬁned for a type synonym. New instances (see Section 4. Similarly. 4. 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 Datatype Renamings ¨ ¦§ § introduces a new type whose representation is the same as an existing type.invalid = = [Circ a] Tag [Rec a] is not. Unlike algebraic datatypes.17). this is not so for type synonyms. These coercions may be implemented without execution time overhead. This difference may make access to the representation less efﬁcient. whereas type Rec a type Circ a = = [Circ a] [Rec a] .46 type List = [] CHAPTER 4.2). 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§ ¦ . it is a static error to use without the full number of arguments. Although recursive and mutually recursive datatypes are allowed. type Rec a = [Rec a] is not allowed. It differs from a type synonym in that it creates a distinct type that must be explicitly coerced to or from the original type.2. The difference is reﬂected in different rules for pattern matching (see Section 3. newtype does not change the underlying representation of an object. except in the instance type of an instance declaration (Section 4. The constructor in an expression coerces a value from type to type ( ).
) 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 ).3 Type Classes and Overloading 4. .4. ( N ) is equivalent to while ( D1 ) is not equivalent to . ( d2 ) and (d2 (D2 ) ) are all equivalent to .1 Class Declarations ¨ 5© A class declaration introduces a new class and the operations (class methods) on it. type (type synonyms). A newtype declaration may use ﬁeldnaming syntax. ) ¦ § ¢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§ © © . The optional deriving part of a newtype declaration is treated in the same way as the deriving component of a data declaration. A class declaration has the general form: © $ ¢ class => where ¦ 7 ¥ ¦ A { .3.3. . © ¥ } ¦ § ¦ A© §S© 4§ © 7 8 8 ¥¥8 ¦ ( . In particular. ( n ( N ) ). though of course there may only be one ﬁeld.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. TYPE CLASSES AND OVERLOADING 47 The following examples clarify the differences between data (algebraic datatypes).3. whereas ( n ). see Section 4. ( d1 ( D1 ) ) and ( s ) are all equivalent to 42.
in particular. . in which case the type of is polymorphic in both and . op2 :: a > a (op1.48 CHAPTER 4. no other declarations are permitted in . © The class declaration introduces new class methods . is not permitted. For example: class (Read a. The default method declaration is a normal value deﬁnition. or another class method. op2) = . The may constrain only . That is. The context speciﬁes the superclasses of . they must not conﬂict with other top level bindings in scope. the ﬁxity declaration for a class method may alternatively appear at top level. Lastly. The default class method for is used if no binding for it is given in a particular instance declaration (see Section 4. v B v # v v @§ v ¢ v © The type of the toplevel class method The must mention .2). it may mention type variables other than . except that the left hand side may only be a variable or function deﬁnition. outside the class declaration. the may contain a default class method for any of the . as described below. 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). For example: class Foo a where op1. The class methods of a class declaration are precisely the for which there is an explicit type signature :: => in .. However.. Show a) => Textual a Other than these cases. it must form a directed acyclic graph. the type variable is scoped only over the class method signatures in the class body. a ﬁeld name. the only type variable that may be referred to in is . a class method can not have the same name as a top level deﬁnition. Class methods share the top level namespace with variable bindings and ﬁeld names. © 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. the may not constrain . since class methods declare toplevel values.3. DECLARATIONS AND BINDINGS $ This introduces a new class name . The superclass relation must not be cyclic.e. because the left hand side of the default declaration is a pattern. whose scope extends outside the class declaration. 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 ¦ . i.
. this is legal.. ] > . 4. It is illegal to give a binding for a class method that is not in scope.. The declarations may not contain any type signatures or ﬁxity declarations.2. The type type variables distinct.2 Instance Declarations ¨ © } § ¦ § © © %§ $ An instance declaration introduces an instance of a class...3.a) where . it is not automatically an instance of the subclass..a) where . instance C (Int.range. The declarations may contain bindings only for the class methods of . must not be a type synonym. and the must all be $ 8 8 ¥¥8 ¡ $ 1 ¢ instance => where { ¦ 2 ¢ class => where { } £%§ ¡ 4 ¦ .Ix T where range = .. module A where import qualified Ix instance Ix. The instance declaration must be given explicitly with no where part. it may be a qualiﬁed name. Let be a class declaration. since these have already v x$ $ 8 8 ¥¥8 ¡ $ $ where .3.) For example..4. (This rule is identical to that used for subordinate names in export lists — Section 5. even though range is in scope only with the qualiﬁed name Ix. but the name under which it is in scope is immaterial.. furthermore. ) ) & & ( ( [ ( { ) ¦ ¦£©¨¦§¥££ ¤ 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§ § ¦ § ¦ . The general form of the corresponding instance declaration is: This prohibits instance declarations such as: instance C (a. in particular. must take the form of a type constructor applied to simple . instance C [[a]] where . if a type is an instance of all superclasses. even though the subclass has no immediate class methods. } . TYPE CLASSES AND OVERLOADING 49 In such a case.
50 CHAPTER 4... The class and type must have the same kind. Show a) => Foo [a] where . 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.6. This example is valid Haskell. Under this assumption. 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. but it is nevertheless mandatory to write an explicit instance context. this can be determined using kind inference as described in Section 4..3. the second instance declaration is only valid if [a] is an instance of Foo under the assumption Num a. Assume that the type variables in the instance type satisfy the constraints in the instance context . then the program would be invalid. must be an instance of each of . 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 ¢ . because Eq and Show are superclasses of Num. instance Num a => Bar [a] where .... In other words. the following two conditions must also be satisﬁed: 2. If no binding is given for some class method then the corresponding default class method in the class declaration is used (if present).. Show a) => Bar [a] where . The second instance declaration is valid only if [a] is an ¨ $ # $ 8 8 ¥¥8 1. instance (Eq a. The constraints expressed by the superclass context be satisﬁed. A type may not be declared as an instance of a particular class more than once in the program. The following example illustrates the restrictions imposed by superclass instances: class Foo a => Bar a where .1). If the two instance declarations instead read like this: instance Num a => Foo [a] where . Since Foo is a superclass of Bar. In fact. instance (Eq a. As in the case of default class methods (Section 4. DECLARATIONS AND BINDINGS been given in the class declaration.. except in pathological cases it is possible to infer from the instance declaration the most general instance context satisfying the above two constraints.. if such a default does not exist then the class method of this instance is bound to undefined and no compiletime error results..
and Read. including a speciﬁcation of when such derived instances are possible. data and newtype declarations contain an optional deriving form.1. 4. since [a] is only an instance of Foo under the stronger assumption Num a. TYPE CLASSES AND OVERLOADING 51 instance of Foo under the assumptions (Eq a. 4. not all datatypes can properly support class methods in Enum. all mentioned in Figure 6." in show x . Show a). page 83. The only classes in the Prelude for which derived instances are allowed are Eq. . Enum. either via an explicit instance declaration or by including the superclass in the deriving clause. Further examples of instance declarations may be found in Chapter 8.3 Derived Instances As mentioned in Section 4.1. and Defaults for Overloaded Numeric Operations ¦ A %§ A problem inherent with Haskellstyle overloading is the possibility of an ambiguous type.3. ¢ 6 6 ¢ 8 ¢ 8 ¥ §¥ ¥ ¥ §¥ ¥ show read Show Read String String ¢ ¢ 8 8 ¥¥8 ¢ ¡ ¢ %§ default ( . It is also a static error to give an explicit instance declaration for a class that is also derived.invalid is ambiguous. Classes deﬁned by the standard libraries may also be derivable. If the form is included. A static error results if it is not possible to derive an instance declaration over a class named in a deriving form. If the deriving form is omitted from a data or newtype declaration. that is. omitting a deriving form is equivalent to including an empty deriving form: deriving ()..2. For example. Derived instances provide convenient commonlyused operations for userdeﬁned datatypes. freeing the programmer from the need to deﬁne them. then derived instance declarations are automatically generated for the datatype in each of the named classes. Bounded. derived instances for datatypes in the class Eq deﬁne the operations == and /=. then no instance declarations are derived for that datatype.4 Ambiguous Types. ) ¦ § ¡ ¡ 6 7 ¥ ¦ ¡ 2§ .. For example. When deriving a class for a type . because the types for show and read.4. and supposing that just Int and Bool are members of Read and Show. then the expression let x = read ".3. Show. using the read and show functions deﬁned in Chapter 10.3. For example. These instances are subject to the same restrictions as userdeﬁned instances. Ord. The precise details of how the derived instances are generated for each of these classes are provided in Chapter 10. But this does not hold. instances for all superclasses of must exist for .
appears only in constraints of the form . for the ambiguous expression given earlier. there is a type A !§ v § 8 8 ¥¥8 ¡§ ¢ v 2§ ¢ $ ¦ $ ¦ 8 ¢ ¥ . ) where . is Ambiguous types can only be circumvented by input from the user.. . in its type variable in that occurs in but not in . and Figure 6.1." in show (x::Bool) which disambiguates the type. Num or a subclass of Num). shows the classes deﬁned in the Prelude. is defaultable if: ¢ ¢ at least one of these classes is a numeric class. This is the purpose of the function asTypeOf (Chapter 8): ‘asTypeOf‘ has the value of . default (). One way is through the use of expression typesignatures as described in Section 3. . Such types are invalid. and all of these classes are deﬁned in the Prelude or a standard library (Figures 6. turns off all defaults in a module. § ¢ . approxSqrt x = encodeFloat 1 (exponent x ‘div‘ 2) ‘asTypeOf‘ x (See Section 6.4.16. and 8 $ ¥ We say that an expression e has an ambiguous type if. an otherwise ambiguous expression needs to be made the same type as some variable.) Ambiguities in the class Num are most common.) Each defaultable variable is replaced by the ﬁrst type in the default list that is an instance of all the ambiguous variable’s classes. where is a class.6 for a description of encodeFloat and exponent. § ¢ ¢ For example. If no default declaration is given in a module then it assumed to be: default (Integer. For example. Such expressions are considered illtyped. a static error.52 CHAPTER 4. pages 91– 92 show the numeric classes. but and are forced to have the same type. and each must be a type for which Num holds. It is a static error if no such type is found. DECLARATIONS AND BINDINGS could be satisﬁed by instantiating a as either Int in both cases. page 83. (that is. so Haskell provides another way to resolve them— with a default declaration: default ( . For example. an ambiguous type variable.. Double) The empty default declaration. rather than being given a ﬁxed type with an expression typesignature. one could write: let x = read ". Occasionally. or Bool.2–6. Only one default declaration is permitted per module. and its effect is limited to that module. the earlier expression involving show and read has an ambiguous type since its type Show Read String.3. In situations where an ambiguous type is discovered.
As mentioned in Section 4. and hence the scope of a type variable is limited to the type signature that contains it. possibly with respect to a context. Indeed. If a variable is deﬁned without providing a corresponding type signature declaration. every type variable appearing in a signature is universally quantiﬁed over that signature. as described in Section 4. these declarations contain a static error.4. which allows applications such as sqr 5 or sqr 0. if we deﬁne sqr x = x*x 0 0 0 0 0 0 then the principal type is sqr Num . %§ ¨ § S § ¢ ¢ 8 ¦ 32 ¢ 8 8 ¥¥8 ¥ :: .1 Type Signatures . or principal type .5. such as ¦ ¦ § ¢ § 6 ¢ ¢ A ¢ § 8 8 ¥¥8 ¢ 8 ¡ ¢ ¥ §¥ ¥ A §¤ v ¢ . A type signature has the form: :: => which is equivalent to asserting :: => for each from to .4. the deﬁning occurrence.2). It is also valid to declare a more speciﬁc type. to ensure that type inference is still possible. . Moreover. even if the signatures are identical. For example.1. it is invalid to give more than one type signature for one variable. For example.4. including the top level of a module. Each must have a value binding in the same declaration list that contains the type signature. in the following declarations f :: a > a f x = x :: a v B the a’s in the two type signatures are quite distinct. (The type of x is dependent on the type of f. it is invalid to give a type signature for a variable bound in an outer scope.1. there is currently since x does not have type no way in Haskell to specify a signature for a variable with a dependent type.invalid A type signature speciﬁes types for variables.4. NESTED DECLARATIONS 53 4.4 Nested Declarations The following declarations may be used in any declaration list.2. this is explained in Section 4.5.e. 4. However.5) is treated as having the corresponding inferred. ¡ => ¡ V © ¤ ¤ ¢ ¢ 6 6 7 ¥ ¦ © S¤ ¦ ¥ ¢ . and all uses of within its declaration group must have the same monomorphic type (from which the principal type is obtained by generalization.) If a given program includes a signature for a variable . It is a static error if the same type cannot also be inferred for the deﬁning occurrence of . then each use of is treated as having the declared type. i. then each use of outside its own declaration group (see Section 4.
4.1 are invalid. DECLARATIONS AND BINDINGS but now applications such as sqr 0. 0 to 9 inclusive (level 0 binds least tightly.invalid . Also like a type signature. Fixity is a property of a particular entity (constructor or variable). and infixr. A ﬁxity declaration may appear anywhere that a type signature appears and. Type signatures such as sqr :: (Num a. 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. The following deﬁnition is pathological. Type signatures can also be used to support polymorphic recursion. Polymorphic recursion allows the user to supply the more general type signature.) There are three kinds of ﬁxity. . ¦ ¡ 2 ©¦ 2 &¤ 2 A 2 ¡ ¥¥8 ¡ ¡ ¢ 2 8 8 ¡ ¡ 2 ¨ ¥ § ¦ § %§ § ¢ ¤ 6 6 6 6 7 ¥ ¦ © %§ § ¢ ¦ ¥ ¡ ¡2 2 . T a > a. and ten precedence levels. like a type signature.54 sqr :: Int > Int CHAPTER 4. a ﬁxity declaration can only occur in the same sequence of declarations as the declaration of the operator itself. declares a property of a particular operator. ﬁxity is not a property of that entity’s name. just like its type. and at most one ﬁxity declaration may be given for any operator. Table 4.4.invalid are invalid. Num b) => a > b sqr :: a > a . respectively). infixl. as they are more general than the principal type of sqr. level 9 is assumed. (Class methods are a minor exception. If the is omitted. and level 9 binds most tightly).2 Fixity Declarations © A ﬁxity declaration gives the ﬁxity and binding precedence of one or more operators. For example: §§ § ¦ ¤ § ¦ § ¦ infixl infixr infix . left. 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. non. their ﬁxity declarations can occur either in the class declaration itself or at top level.and rightassociativity (infix. Any operator lacking a ﬁxity declaration is assumed to be infixl 9 (See Section 3 for more on the use of ﬁxities). The in a ﬁxity declaration must be in the range to .1 lists the ﬁxities and precedences of the operators deﬁned in the Prelude.
‘quot‘ +. ‘div‘. <. ˆˆ.4. NESTED DECLARATIONS 55 Precedence 9 8 7 6 5 4 3 2 1 0 Left associative operators !! *. ˆ. ‘Foo. ++ ==. ‘elem‘. ‘notElem‘ &&  >>. and the nested deﬁnition of op in f’s righthand side has the default ﬁxity of infixl 9.op‘ is infix 3. /=. >. module Foo where import qualified Bar infix 3 ‘op‘ a ‘op‘ b = (a ‘Bar.. Here.op‘ is infixr 7.op‘ q) * 2 in .. ‘Bar..op‘ b) + 1 f x = let p ‘op‘ q = (p ‘Foo. (It would also be possible to give a ﬁxity to the nested deﬁnition of ‘op‘ with a nested ﬁxity declaration. ‘mod‘. >>= $.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 .4.  Nonassociative operators Right associative operators . ‘seq‘ Table 4.) 4. /.1: Precedences and ﬁxities of prelude operators module Bar( op ) where infixr 7 ‘op‘ op = . ‘rem‘. $!. >=. <=.4.. ** :.
DECLARATIONS AND BINDINGS We distinguish two cases within this syntax: a pattern binding occurs when the left hand side is a .4. Either binding may appear at the toplevel of a module or within a where or let construct. and the number of patterns in each clause must be the same. ¤ 4. 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 . the binding is called a function binding. The general form of a function binding for variable is: ¡ ¥ § ¥ § or ¡ v ¡v   = Note that all clauses deﬁning a function must be contiguous. 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 © ¥ ¤ § © ¥ ¦ ¦ ¢ £¡ ¤ . namely: .56 CHAPTER 4. The set of patterns corresponding to each match must be linear—no variable is allowed to appear more than once in the entire set. For example.3.1 Function bindings A function binding binds a variable to a function value. 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. otherwise. Alternative syntax is provided for binding functional values to inﬁx operators. . the latter.
a pattern binding is: is the same structure as for ¡ ¥ § ¢ ¥ § ¢ 8 8 ¥¥8 4 ¡ ¡ 888 v ¢ where the are new identiﬁers. A 4 ¡ A ( ) ¥ § ¢ 4 A 8 8 ¥¥8 ¡ ¡ 8 8 ¥¥8 ¡ ¡ 8 8 ¥¡ ¥8 ¢ 8 8 ¥¥8 ¡ ¢ ¢ 8 8 ¥¥8 ¡ ¢ = \ ¢ > case ( . NESTED DECLARATIONS Translation: The general binding form for functions is semantically equivalent to the equation (i. simple pattern binding): ¡ ¥ § 57 4.12. 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 . The pattern is matched “lazily” as an irrefutable pattern.4. as if there were an implicit ˜ in front of it. See the translation in Section 3. where a function bindings above. but the existence of n+k patterns sometimes confuses the issue.e. It is usually straightforward to tell whether a binding is a pattern binding or a function binding. ) of ( ) ¢ ¡ ¡ ¡ ¡ . in other words. A note about syntax.2 Pattern bindings A pattern binding binds variables to values. . A simple pattern binding has form .4.4.3.
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
¢
¥
For example. module M1(len1) where default( Int.4. Rule 2 states that the exact types of all the variables bound in a module must be determined by that module alone. Consequences The monomorphism rule has a number of consequences for the programmer. a type signature on len1 would solve the problem. 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.) This issue does not arise for nested bindings. However. 63 Rule 2 is required because there is no way to enforce monomorphic use of an exported binding. There is no danger of recomputation here. the same function deﬁned with pattern syntax: f = \x > \y > x+y requires a type signature if f is to be fully overloaded. because their entire scope is visible to the compiler.()) both f and g are monomorphic regardless of any type signatures supplied for f or g. Anything deﬁned with function syntax usually generalizes as a function is expected to. and not by any modules that import it. Rule 2 now states that the monomorphic type variable a is ambiguous.3. except by performing type inference on modules outside the current module. len1 has the monomorphic type Num a => a (by Rule 1). Double ) len1 = genericLength "Hello" module M2 where import M1(len1) len2 = (2*len1) :: Rational When type inference on module M1 is complete. Many functions are most naturally deﬁned using simple pattern bindings. in (f. Hence. len1 gets type Int.g) = ((+). STATIC SEMANTICS OF FUNCTION AND PATTERN BINDINGS The same constraint applies to patternbound functions. Thus in f x y = x+y the function f may be used at any overloading in class Num. Consider module M where len1 = genericLength "Hello" len2 = (2*len1) :: Rational . (If the above code is actually what is wanted. the user must be careful to afﬁx these with type signatures to retain full overloading. and its use in len2 is typeincorrect.5. and must be resolved using the defaulting rules of Section 4.4.
Instead. This can be achieved in much the same way as the dependency analysis for value declarations that was described in Section 4. and the type variable a is resolved to Rational when performing type inference on len2. and class deﬁnitions into dependency groups. It follows that both D and S must have kind and that every instance of class C must have kind . for instance). type inference ﬁnds that len1 has the monomorphic type (Num a => a). using the default binding . does not match the kind that is expected for an argument of Tree: type FunnyTree = Tree [] . for any kind . For example.e. and would require an extension to allow polymorphic kinds. to calculate a suitable kind for each type constructor and class appearing in a given program. The ﬁrst step in the kind inference process is to arrange the set of datatype. 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. a default of is assumed. 4. the parameter a appears as an argument of the function constructor (>) in the type of bar and hence must have kind . 6 6 6 6 9 6 6 ¡ 6 6 6 ¡ 6 9 6 6 ¡ ¡ ¡ ¡ .invalid This is important because it ensures that each constructor and class are used consistently with the same kind whenever they are in scope. . respectively. the actual kinds for these two constructors are and . i. and instead generates a static error because the kind of [].6 Kind Inference This section describes the rules that are used to perform kind inference. constructors. For example. It is possible that some parts of an inferred kind may not be fully determined by the corresponding deﬁnitions.5.64 CHAPTER 4. and classes within each group are determined using standard techniques of type inference and kindpreserving uniﬁcation [7]. respectively. For example. the following program fragment includes the deﬁnition of a datatype constructor D. For example. adding the following deﬁnition to those above does not inﬂuence the kind inferred for Tree (by changing it to . synonym. in such cases. a synonym S and a class C. in the deﬁnitions above. DECLARATIONS AND BINDINGS Here. 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. 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.
3. changing all occurrences to refer to the appropriate unique name. and its result (of type ) is discarded. Modules may reference other modules via explicit import declarations. Modules are used for namespace control.. When the program is executed. by convention. or class deﬁned in. imported into. in an environment created by a set of imports (resources brought into scope from other modules).5) is affected by module boundaries.4). For example.5. here is a threemodule program: module Main where import A import B main = A. making them available to other modules. datatypes. It exports some of these resources.. must be called Main and must export the value main. A multimodule Haskell program can be converted into a singlemodule program by giving each entity a unique name. A Haskell program is a collection of modules.. 1 65 . and then concatenating all the module bodies1 . module B where f = . etc. Modules may be mutually recursive. or perhaps exported from a module. each giving the name of a module to be imported and specifying its entities to be imported. type.Chapter 5 Modules A module deﬁnes a collection of values. and are not ﬁrst class values. First. the computation main is performed.f >> B. type synonyms. Second.. which must be a computation of type IO for some type (see Chapter 7). Rule 2 of the monomorphism restriction (Section 4. (see Chapter 4). default declarations scope over a single module (Section 4. classes. It is equivalent to the following singlemodule program: There are two minor exceptions to this statement.f module A where f = . The value of the program is the value of the identiﬁer main in module Main. one of which. We use the term entity to refer to a value.
1 Module Structure A module deﬁnes a mutually recursive scope containing declarations for value bindings.2 Export Lists ¦ ¨ A§ ¤ !¤32 ¢ S 8 8 ¥¥8 ¡ ¤32 § ¤ ¢ ¡ ( . There is one distinguished module. If this is used. consisting only of the module body. ( An abbreviated form of module. ). Chapter 4). This is followed by a possiblyempty list of toplevel declarations . CHAPTER 5. the header is assumed to be ‘module Main(main) where’. Prelude... plus a set of standard library modules that may be imported as required (see Part II). The namespace for modules themselves is ﬂat. . (see Chapter 4). A module begins with a header: the keyword module. data types. with each module being associated with a unique module name (which are Haskell identiﬁers beginning with a capital letter.6). is permitted. classes. the module name. MODULES Because they are allowed to be mutually recursive. . then the layout rule applies for the top level of the module.3) that specify modules to be imported. ) ¦ § ¦ ¦ A 2§ 7 A ¥ ¦ ¡ 4 § ¡ 7 ¥ ¦ ¡ 8 8 ¥¥8 8 8 ¥¥8 . © 5. i.e.. If the ﬁrst lexeme in the abbreviated module is not a {. etc. which is imported into all modules by default (see Section 5. optionally restricting the imported bindings..66 module Main where main = af >> bf af = . Section 5. ¦ ¦ § 5. bf = . type synonyms. . modules allow a program to be partitioned freely without regard to dependencies. 7 ¦ © ¡ 2§ © © 4§ ¡ 2§ 7 ¥ ¦ ¡ 4 § ¡ 7 ¥ ¦ § ¡ 32 ¦ 2§ ¦ ¡ 4§ ¦ ¡ 4§ { { { . The header is followed by a possiblyempty list of import declarations ( . . . } } } 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 ¢ ¡ . and a list of entities (enclosed in round parentheses) to be exported.
. one of these subordinate names is legal if and only if (a) it names a constructor or ﬁeld of . must be in scope.Maybe( Nothing.) ( module .. or class method. ) An export list identiﬁes the entities to be exported by a module declaration.. 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.2. whether declared in the module body or imported. . A type synonym is in scope. all values. ) ¦ ¦§ ¦ ¦ § ¢ ¢ ¢ ¡ ¢¨ ¦ ¦ § 2 4 ¦ 2 ¤ 3¥ %§ ¦ 72 ¨ © ¡ ¨ ¤ ¢ ¢ %§ 6 6 § ¤ ¤32 4 ¦ ¢ ¡ ¢ ¡ . The constructor In all cases. 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. may . A module implementation may only export an entity that it declares. A value. ﬁeld name. types and classes deﬁned in the module are exported. 3. which must be in scope. Entities in an export list may be named as follows: 1. A class with operations of three ways: 8 8 ¥¥8 ¢ The form names. ( .8).5. should be enclosed in parentheses to turn them into 2. For example. the following is legal module A( Mb.) ( (. ). EXPORT LISTS 67 . Operators be named by giving the name of the value as a s. ¦ declared by a type declaration may be named by the form ¡ £ 8 8 ¥¥8 ¢ £ 4. 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 ¤ ¢ ¤ ¦ § (. but not those that are imported. . the (possiblyqualiﬁed) type constructor and ﬁeld names in the second form are unqualiﬁed. If the export list is omitted. or that it imports from some other module.) names the type and all its constructors and ﬁeld names that are currently in scope (whether qualiﬁed or not). 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. The abbreviated form (. because they cannot otherwise be distinguished from type constructors.
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. item (5)). a ﬁeld name f from data type T may be exported individually (f. dequeue ) where import Stack . It is an error to use module M in an export list unless M is the module bearing the export list. ¡ £ . C. ¡ ¦ The form names the class but not the class methods.g) g = f True . 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. 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. because a local declaration brings into scope both a qualiﬁed and unqualiﬁed name (Section 5. 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. The unqualiﬁed names of the entities exported by a module must all be distinct (within their respective namespace). . A module can name its own local deﬁnitions in its export list using its own name in the “module M” syntax.) names the class and all its methods that are in scope (whether qualiﬁed or not).g. one of the (unqualiﬁed) subordinate names is legal if and only if (a) it names a class method of . names the class and some or all of its methods. In the second form. Here the module Queue uses the module name Stack in its export list to abbreviate all the entities imported from Stack. 5. or as an explicitlynamed member of its data type (T(f). item (2)).e”. For example: module Mod1( module Mod1. For example: module Queue( module Stack. For example module A ( C.5. or as an implicitlynamed member (T(. enqueue... must be in scope. but there are name clashes in the export list ¦ £ 8 8 ¥¥8 ¢ £ The form ( . item (1) above).68 CHAPTER 5. In all cases.. module B ) where import B(f) import qualified C(f. It makes no difference to an importing module how an entity was exported.1). or M is imported by at least one import declaration (qualiﬁed or unqualiﬁed). This set may be empty.. MODULES The abbreviated form (.an invalid module There are no name clashes within module A itself. For example. item(2)). or by exporting an entire module (module M.f. g. ).).
) ¨ ¨ A 5 4 ¦ ¢¥¥8 8 8 ¡ ¢ ¡ ¤ 4 ¦ ¢ (..3.. except qualiﬁers are not permitted and the ‘module ’ entity is not permitted.) form of import is used for a type or class. they may also be used as variables. Items in the list have the same form as those in export lists. .3..) refers to all of the constructors. the (. hiding ( . ¦ ¦ § ¦ ¤ ¢ A¤ 8 8 ¥¥8 . rather than Lexically.g and g (assuming C. . methods.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.) ( (. . in which case nothing except the instances is imported. A single module may be imported by more than one import declaration. The import declaration names the module to be imported and optionally speciﬁes the entities to be imported..f and C. ) ¦ ¦ ¡ ¦ 2 ¤ 37 2 ¦ ¡ © 4§ ¤ ¢ ¢ %§ %§ 2 4 6 6 6 6 ¦ ¦ § ¤ © 7 § © ¤ 32 ¡ ¡ 4 ¦ ¢ ¡ ¤ ¦ ¡ 4§ 4§ 4§ . Imported names serve as top level declarations: they scope over the entire body of the module but may be shadowed by local nontoplevel bindings.5. § 5. ¨¡ 8 8 ¥¥8 A§ ¤ 2 4§ ¢ ¡ §¤¤32 4 § 8 8¡ ¥¥8 ¡§ ¤ 2 ( . 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.) ( . ) ¦ ¨ A !§ ¤ ¦ § ¦ ¦§ ¦ 2 § § ¤ %§ 4 ¢ ¢ ¥ ¦ 7 ¨¡ © 4 § ¨ § 2 4 ¡ ¡ ¦ ¦ . “qualified” and “hiding” are each a a . The imported entities can be speciﬁed explicitly by listing them in parentheses. The ordering of import declarations is irrelevant.f (assuming B. The list must name only entities exported by the imported module. modules can import each other recursively). the terminal symbols “as”. ) ¦ ¦§ ¦ ¦ § ¢ 2 4§ .1 What is imported Exactly which entities are to be imported can be speciﬁed in one of the following three ways: 1. They have special signiﬁcance only in the context of an import declaration. and between module B and C.g and g are different entities – remember. 2 4 ¨ import qualified as . IMPORT DECLARATIONS 69 between C. 5.f are different entities). When the (. The list may be empty. or ﬁeld names exported from the module.
Entities can be excluded by using the form hiding( .’. Hence.3) on the import statement. in import M hiding (C) any constructor.+ 1) . It is an error to hide an entity that is not.3.’ as a qualiﬁer instead of ‘VeryLongModuleName. or type named C is excluded. using C in an import list names only a class or type. Data constructors may be named directly in hiding lists without being preﬁxed by the associated type. In contrast. only the qualiﬁed name of the entity is brought into scope. The qualiﬁer on the imported name is either the name of the imported module. exported by the imported module.1 describes qualiﬁed names in more detail. if ported. This also allows a different module to be substituted for VeryLongModuleName without changing the 4§ 3.This * differs from the one in the Prelude 5. ). in fact. is omitted then all the entities exported by the speciﬁed module are im A !§ ¤ 2 ¡ 4§ 8 8 ¥¥8 ¡ 4§ ¡ ¡ . which speciﬁes that all entities exported by the named module should be imported except for those named in the list. or the local alias given in the as clause (Section 5. Section 5.3. then both the qualiﬁed and unqualiﬁed name of the entity is brought into scope. 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. in import qualified VeryLongModuleName as C entities must be referenced using ‘C. Thus. © 5. If the qualified keyword is omitted. .3 Local aliases Imported modules may be assigned a local alias in the importing module using the as clause. the toplevel environment is extended.2 Qualiﬁed import For each entity imported under the rules of Section 5. Finally.3. If the import declaration used the qualified keyword. MODULES 2.++ l2 l1 * l2 = nub (l1 + l2) succ = (Prelude. For example.3. the qualiﬁer is not necessarily the name of the module in which the entity was originally declared.All Prelude names must be qualified . class.70 ¡ ¤32 § ¤ CHAPTER 5.This + differs from the one in the Prelude .5.1.
x.x.x.3.x.x A. A. A.x B.y (nothing) x. y.y (nothing) A. A.4 Examples To clarify the above import rules.y y.y x.f.y A.x. all instance declarations in scope in module A are imported (Section 5. y.4).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.y x. B. 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. 5. For example: module M where import qualified Foo as A import qualified Baz as A x = A. B. A. y.y A. IMPORTING AND EXPORTING INSTANCE DECLARATIONS 71 qualiﬁers used for the imported module. It is legal for more than one module in scope to use the same qualiﬁer. A. suppose the module A exports x and y. 5. All instances in scope within a module are always exported and any import brings all instances in from the imported . B.4 Importing and Exporting Instance Declarations Instance declarations cannot be explicitly named on import or export lists.4. provided that all names can still be resolved unambiguously. B.x x.5. A. A.f This module is legal provided only that Foo and Baz do not both export f. A.y In all cases.
3)..2 Name clashes If a module contains a bound occurrence of a name. A qualiﬁed name is brought into scope: . This allows a qualiﬁed import to be replaced with an unqualiﬁed one without forcing changes in the references to the imported names. it is illegal to write module M where M. g x = M.. that is. The deﬁning occurrence must mention the unqualiﬁed name. 4 ¦ ¢ ¦ ¦ (Section 2. there must be only one binding for f or A. whether qualified or not. For example. MODULES module.72 CHAPTER 5.5. .. an instance declaration is in scope if and only if a chain of import declarations leads to the module containing the instance declaration..f x = . 2 4 A qualiﬁed name is written as .1 Qualiﬁed names § By a top level declaration.ILLEGAL By an import declaration.ILLEGAL g x = let M. therefore. 5. Thus. Thus: module M where f x = .y = x+1 in . .5. but does bring in any instances visible in M.. import M() does not bring any new names in scope from module M.f. such as f or A.4). For example module MyInstances() where instance Show (a > b) where show fn = "<<function>>" instance Show (IO a) where show io = "<<IO action>>" 5..f x x is legal. always brings into scope the qualiﬁed name of the imported entity (Section 5.5 Name Clashes and Closure 5. it must be possible unambiguously to resolve which entity is thereby referred to. A module whose only purpose is to provide instance declarations can have an empty export list.f respectively. An import declaration. A toplevel declaration brings into scope both the unqualiﬁed and the qualiﬁed name of the entity being deﬁned.
x) module B( d. and can be referred to in A by the names d. The reference to x is ambiguous: it could mean x declared in B. NAME CLASHES AND CLOSURE 73 It is not an error for there to exist names that cannot be so resolved. b.. y ) where import D x = . B.. 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. and C.5. and c declared in C respectively. so it is not erroneous that distinct entities called y are exported by both B and C.sin x) The local declaration for sin is legal.. c = ..2). the following module is legal: module F where sin :: Float > Float sin x = (x::Float) f x = Prelude. In this case the same entity is brought into scope by two routes (the import of B and the import of C).d..x or C. y = .. even though the Prelude function sin is implicitly in scope. An error is only reported if y is actually mentioned. y ) where import D x = .x. The reference to d is unambiguously resolved to d declared in D. For example.. b = .5... module D( d ) where d = . provided that the program does not mention those names. module C( d.4... The ambiguity could be ﬁxed by replacing the reference to x by B. . x.sin (F.. c. d.d. The references to b and c can be unambiguously resolved to b declared in B.. or x declared in C. The name occurring in a type signature or ﬁxity declarations is always unqualiﬁed. There is no reference to y. c. y = . Consider the deﬁnition of tup. For example: module A where import B import C tup = (b.. x.
entities that the compiler requires for type checking or other compile time analysis need not be imported if they are not mentioned by name.sin and F. 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.74 CHAPTER 5. classes. That is. the unqualiﬁed name sin in the type signature in the ﬁrst line of F unambiguously refers to the local declaration for sin. every name explicitly mentioned by the source code must be either deﬁned locally or imported from another module. MODULES The references to Prelude. called the “Standard Prelude. However.3 Closure Every module in a Haskell program must be closed. the type checker ﬁnds the deﬁnition of T if needed whether or not it is exported. For example.sin must both be qualiﬁed to make it unambiguous which sin is meant. Whether or not T is explicitly exported. 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. these are interchangeable even when T is not in scope. That is. The Haskell system silently imports any information that must accompany an entity for type checking or any other purposes. 5. 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. 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. However. That is. the Prelude is contained in the . The only reason to export T is to allow other modules to refer it by name.5. module M2 knows enough about T to correctly type check the program.6 Standard Prelude Many of the features of Haskell are deﬁned in Haskell itself as a library of standard datatypes. 5. The type of an exported entity is unaffected by nonexported type synonyms.” In Haskell. and functions.
This means.6. Some datatypes (such as Int) and functions (such as Int addition) cannot be speciﬁed directly in Haskell. 5.6. which provide less frequently used functions and types. 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. They are simply there to help explain the structure of the Prelude module. This provision for explicit import allows entities deﬁned in the Prelude to be selectively imported. and they cannot be imported separately.2 Shadowing Prelude Names The rules about the Prelude have been cast so that it is possible to use Prelude names for nonstandard purposes. that a compiler may optimize calls to functions in the Prelude without consulting the source code of the Prelude. and so on. For example. and increasing the space of useful names available to the programmer. for example. STANDARD PRELUDE 75 module Prelude. complex numberss. The latter would be ambiguous without the hiding(null) on the . and contains an unqualiﬁed reference to null on the right hand side of nonNull. not part of the language deﬁnition. given in Chapter 8.6. every module that does so must have an import declaration that makes this nonstandard usage explicit. and most of the input/output are all part of the standard libraries. just like those from any other module. These modules are not part of Haskell 98. 5. allowing it to be more easily assimilated. they are not formally deﬁned in Chapter 8. Chapter 8 deﬁnes the module Prelude using several other modules: PreludeList. 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. if and only if it is not imported with an explicit import declaration.5. arrays. PreludeIO. nonNull :: Int > Bool null x = x == 0 nonNull x = not (null x) Module A redeﬁnes null. There are also many predeﬁned library modules. however.1 The Prelude Module The Prelude module is imported automatically into all modules as if by the statement ‘import Prelude’. These are deﬁned in Part II Separating libraries from the Prelude has the advantage of reducing the size and complexity of the Prelude. but the implementation only gives a scheme. Since the treatment of such entities depends on the implementation. For example: module A( null. nonNull ) where import Prelude hiding( null ) null. The semantics of the entities in Prelude is speciﬁed by a reference implementation of Prelude written in Haskell. they should be considered part of its implementation.
MODULES import Prelude statement.) x x h x = [x] ++ [] the explicit import Prelude() declaration prevents the automatic import of Prelude.x) g x = (. an ADT for stacks could be deﬁned as: module Stack( StkType. the Prelude is an ordinary Haskell module. push. and then makes an unqualiﬁed reference to null must also resolve the ambiguous use of null just as A does. so it refers to ++ imported from MyPrelude. in module B where import Prelude() import MyPrelude f x = (x. there is no way to redeﬁne the meaning of [x].x) and (. while the declaration import MyPrelude brings the nonstandard prelude into scope. however. empty ) where data StkType a = EmptyStk  Stk a (StkType a) push x s = Stk x s pop (Stk _ s) = s empty = EmptyStk . to hide instance declarations in the Prelude. Redeﬁning names used by the Prelude does not affect the meaning of these special constructs. for example. the use of ++ is not special syntax. pop. 5. For example. Explicit type signatures for all exported values may be necessary to deal with mutual recursion. The precise details of separate compilation are not deﬁned by this report. It is possible to construct and use a different module to serve in place of the Prelude. Other than the fact that it is implicitly imported. 5. Thus there is little danger of accidentally shadowing Prelude names.)) and lists (such as [x] and []) continues to refer to the tuples and lists deﬁned by the standard Prelude. The special syntax for tuples (such as (x. For example. in terms of a different implementation of lists.7 Separate Compilation Depending on the Haskell implementation used. For example.8 Abstract Datatypes The ability to export a datatype without its constructors allows the construction of abstract datatypes (ADTs). It is not possible. it is special only in that some objects in the Prelude are referenced by special syntactic constructs. On the other hand. Every module that imports A unqualiﬁed. one cannot deﬁne a new instance for Show Char. separate compilation of mutually recursive modules may require that imported modules contain additional information so that they may be referenced before they are compiled.76 CHAPTER 5.
empty ) where newtype StkType a = Stk [a] push x (Stk s) = Stk (x:s) pop (Stk (_:s)) = Stk s empty = Stk [] . It is also possible to build an ADT on top of an existing type by using a newtype declaration. pop. Instead. For example.5. stacks can be deﬁned with lists: module Stack( StkType. and empty to construct such values.8. they must use push. pop. ABSTRACT DATATYPES 77 Modules importing Stack cannot construct values of type StkType because they do not have access to the constructors of the type. push.
MODULES .78 CHAPTER 5.
Ord. 6. The basic boolean functions are && (and). Enum. 6.1 Booleans data Bool = False  True deriving (Read. Show. and 79 . The name otherwise is deﬁned as True to make guarded expressions more readable. Ord. The lexical syntax for characters is deﬁned in Section 2. and rationals are deﬁned in Part II. In this chapter. Type Char is an instance of the classes Read. Some deﬁnitions may not be completely valid on syntactic grounds but they faithfully convey the meaning of the underlying type. Eq.6. the Haskell deﬁnition of the type is given. Numeric types are described in Section 6. 6. Show.1. Eq.Chapter 6 Predeﬁned Types and Classes The Haskell Prelude contains predeﬁned classes. Enum. Other predeﬁned types such as arrays. When appropriate.1. complex numbers. types.  (or).2 Characters and Strings The character type Char is an enumeration whose values represent Unicode characters [11]. and not. we describe the types and classes found in the Prelude.1 Standard Haskell Types These types are deﬁned by the Haskell Prelude. Most functions are not described in detail here as they can easily be understood from their deﬁnitions as given in Chapter 8. Bounded) The boolean type Bool is an enumeration. and functions that are implicitly imported into every Haskell program.4. character literals are nullary constructors in the datatype Char.
’n’. of course. ’i’. Each tuple type has a single constructor. respectively. Show.) x y produce the same value. Ord.11. However. The toEnum and fromEnum functions. Lists are an instance of classes Read. Ord. there are the following equivalences: \a and \BEL. The Prelude and libraries deﬁne tuple functions such as zip for tuples up to a size of 7.10 and 3. and uncurry. snd.’r’. Arithmetic sequences and list comprehensions. thus. written ‘[]’ (“nil”). Ord) Lists are an algebraic datatype of two constructors. every Haskell implementation must support tuples up to size 15.3 Lists data [a] = []  a : [a] deriving (Eq. standard functions from class Enum. Functor.6. \t and \HT.Bool. and the \ˆ notation. together with the instances for Eq. A string is a list of characters: type String = [Char] Strings may be abbreviated using the lexical syntax described in Section 2. Bounded. PREDEFINED TYPES AND CLASSES Bounded. \r and \CR.1. curry. Note that ASCII control characters each have several representations in character literals: numeric escapes.’t’. The ﬁrst constructor is the null list. Ord. For example. but some Haskell implementations may restrict the size of tuples. Similar functions are not predeﬁned for larger tuples. map characters to and from the Int type.1) deﬁnes many standard list functions. \v and \VT.7. (Int. All tuples are instances of Eq.8. \f and \FF. Monad. and Show. as described in Section 3. The same holds for tuple type constructors.’ ’. that all their component types are). "A string" abbreviates [ ’A’. Bounded. The following functions are deﬁned for pairs (2tuples): fst. The constructor for a tuple is written by omitting the expressions surrounding the commas. although with special syntax.y) and (.80 CHAPTER 6. Read. The module PreludeList (see Section 8.’s’.’g’] 6. In addition. and MonadPlus. Read.1.4 Tuples Tuples are algebraic datatypes with special syntax. .) Int Bool Int denote the same type.Int) and (. are described in Sections 3. and the second is ‘:’ (“cons”). Eq. two convenient syntaxes for special kinds of lists. There is no upper bound on the size of a tuple.. and Show (provided. \b and \BS. 6. ASCII mnemonic escapes. and limit the instances associated with larger tuples. and \n and \LF. as deﬁned in Section 3. thus (x.
Show) LT  EQ  GT deriving (Eq.1. Ord.6 Function Types Functions are an abstract type: no constructors directly create functional values. The unit datatype () has one non 6.1.6. const. Ord. STRICT EVALUATION 81 6. (. flip. and MonadPlus. Monad. Enum. using the seq function: seq :: a > b > b . Ord.5 The Unit Datatype data () = () deriving (Eq. Show) Left a  Right b deriving (Eq.2 Strict Evaluation Function application in Haskell is nonstrict.7 The IO and IOError Types The IO type serves as a tag for operations (actions) that interact with the outside world. IOError is an abstract type representing errors raised by I/O operations. 6. Values of this type are constructed by the various I/O functions and are not presented in any further detail in this report. The Ordering type is used by compare in the class Ord. 6. and until. a function argument is evaluated only when required. Read. Chapter 7 describes I/O operations.2. Ord. and Part II contains many more. Bounded.3). that is. Show) The Maybe type is an instance of classes Functor.1. Read. The Prelude contains a few I/O functions (deﬁned in Section 8. See also Section 3. IO is an instance of the Monad and Functor classes. The functions maybe and either are found in the Prelude. The IO type is abstract: no constructors are visible to the user. Read.1. the nullary constructor (). Enum. Show) member. Read. 6. ($). The following simple functions are found in the Prelude: id. It is an instance of Show and Eq. Bounded.).9. 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.
because it is available at every type. provide a reasonable deﬁnition for all the class methods.3 Standard Haskell Classes Figure 6. the provision of seq has is important semantic consequences. If there is no such comment. then all class methods must be given to fully specify an instance. PREDEFINED TYPES AND CLASSES The function seq is deﬁned by the equations: seq is usually introduced to improve performance by avoiding unneeded laziness. As a consequence. . For the same reason. However. or zipWith ($) fs xs. since ordinary application (f x) means the same as (f $ x).1 shows the hierarchy of Haskell classes deﬁned in the Prelude and the Prelude types that are instances of these classes.3.3) are provided for many of the methods in standard classes. Strict datatypes (see Section 4.82 CHAPTER 6. (/=) :: x /= y x == y a > a > Bool = not (x == y) = not (x /= y) ¡¢ 0§ ' ' ¢ seq seq ' . The operator $! is strict (callbyvalue) application. since seq can be used to distinguish them. such as map ($ 0) xs. $! ($).2. $ has low. However. ($!) :: (a > b) > a > b f $ x = f x f $! x = x ‘seq‘ f x The nonstrict application operator $ may appear redundant. 6.1 The Eq Class class Eq a where (==). 6. for example: f $ g $ h x = f (g (h x)) It is also useful in higherorder situations.1) are deﬁned in terms of the $! operator. the not the same as \x > existence of seq weakens Haskell’s parametricity properties. together with the default declarations. infixr 0 $. A comment with each class declaration in Chapter 8 speciﬁes the smallest collection of method deﬁnitions that. The Prelude also deﬁnes the $ operator to perform nonstrict application. rightassociative binding precedence. so it sometimes allows parentheses to be omitted. Default class method declarations (Section 4. and is deﬁned in terms of seq.
Double Integral Int. (>) Ord All except (>) IO.3. Int. Integer. []. Float. Double RealFloat Float. IOError Num Int. Double Floating Float. Integer. (>) Read All except IO. Maybe Figure 6. STANDARD HASKELL CLASSES 83 Eq All except IO. tuples Enum (). Double Bounded Int. Ordering. Float. Double Real Int. Char. Bool. Double Fractional Float. Double Monad IO. () Ordering. (>) Show All except IO. Bool.1: Standard Haskell Classes . Integer RealFrac Float. Char. Maybe Functor IO. Integer. Float.6. [].
All basic datatypes except for functions and IO are instances of this class.Note that (min x max x y  x <= y  otherwise min x y  x <= y  otherwise y. All basic datatypes except for functions. are instances of this class. The default declarations allow a user to create an Ord instance either with a typespeciﬁc compare function or with typespeciﬁc == and <= functions. The declared order of the constructors in the data declaration determines the ordering in derived Ord instances. Instances of Eq can be derived for any userdeﬁned datatype whose constituents are also instances of Eq.84 CHAPTER 6. Instances of Ord can be derived for any userdeﬁned datatype whose constituent types are in Ord.2 The Ord Class class (Eq a) => Ord a where compare :: a > a > Ordering (<). This declaration gives default method declarations for both /= and ==. the default method for the other will make use of the one that is deﬁned. = = = = max x y) = (x.y) or (y. PREDEFINED TYPES AND CLASSES The Eq class provides equality (==) and inequality (/=) methods. each being deﬁned in terms of the other. (<=). IO. (>) :: a > a > Bool max. 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 . 6.x) y x x y The Ord class is used for totally ordered datatypes.3. If an instance declaration for Eq deﬁnes neither == nor /=. If one is deﬁned. neither default method is used. If both are deﬁned. then both will loop. and IOError. The Ordering datatype allows a single comparison to determine the precise ordering of two objects. . (>=).
A specialised variant.. where values of type String should be shown in double quotes.read: ambiguous parse" . 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.lex t] of [x] > x [] > error "PreludeText. showsPrec and showList return a StringtoString function.t) <. by providing an instance declaration. default decl for showList given in Prelude The Read and Show classes are used to convert values to or from strings. rather than between square brackets. 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.3. The method showList is provided to allow the programmer to give a specialised way of showing lists of values.reads s.. are instances of Show and Read. and returns an ordinary String. to allow constanttime concatenation of its results using function composition.read: no parse" _ > error "PreludeText. show."") <. Strings produced by showsPrec are usually readable by readsPrec. a programmer can easily make functions and IO types into (vacuous) instances of Show. 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 "" . (If desired.3.String)] ShowS = String > String class Read a where readsPrec :: Int > ReadS a readList :: ReadS [a] . This is particularly useful for the Char type. ("". STANDARD HASKELL CLASSES 85 6. is also provided. The Int argument to showsPrec and readsPrec gives the operator precedence of the enclosing context (see Section 10...3 The Read and Show Classes type type ReadS a = String > [(a.6.4)... except function types and IO types. which uses precedence context zero.) For convenience.
is also part of the Prelude. For any type that is an instance of class Bounded as well as Enum. It reads a single lexeme from the input. and returning the characters that constitute the lexeme.) If there is no legal lexeme at the beginning of the input string. The functions succ and pred return the successor and predecessor. If the input string contains only white space. (Thus lex "" = [("". which must be completely consumed by the input process.86 CHAPTER 6. The function lex :: ReadS String. enumFrom and enumFromThen should be deﬁned with an implicit bound."")].. 6. methods are used when translating arithmetic sequences (Section 3. 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. used by read.. the following should hold: The calls succ maxBound and pred minBound should result in a runtime error. For example.. see Chapter 10.] [n. Instances of Enum may be derived for any enumeration type (types whose constructors have no ﬁelds).Default declarations given in Prelude Class Enum deﬁnes operations on sequentially ordered types. discarding initial white space. lex returns a single successful “lexeme” consisting of the empty string. PREDEFINED TYPES AND CLASSES shows and reads use a default precedence of 0. toEnum 7 :: Bool is an error.n’. The read function reads input from a string.4 The Enum Class class Enum a where succ.. The enumFrom.3.. The functions fromEnum and toEnum map values from a type in Enum to and from Int.m] [n. fromEnum and toEnum should give a runtime error if the result value is not representable in the result type. returns [])..e.m] .n’. of a value.] [n. 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: . lex fails (i.10). respectively.
the list is empty if negative. ¥ ¢ For Float and Double.3. the list terminates when the next element would be less than . For the types Int and Integer. . enumFromTo ’a’ ’z’ denotes the list of lowercase letters in alphabetical order.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.3. empty if is the list [ .] is the list [LT.. The list is ¥ § ¦ § . . For all four numeric types. The increment may be zero or negative. Lists. is . Numeric types: Int. For example. For example. Bool. the digits after the decimal point may be lost. 8 8 ¥¥8 § ¤ ¤ ¡ ¡¢ 8 8 ¥¥8 § ¢¢ ¡ ¡ ¡¢ ¡ ¢ ¡ ¡¢ ¡ £ ¡ ¡ ¡ ¤ The sequence enumFrom is the list [ . and pred subtracts 1.6. If the increment is the next element would be greater than . is . For all four of these Prelude numeric types. . the semantics of the enumFrom family is given by the rules for Int above. except that the list terminates when the elements become greater than for positive increment . ]. IO. The semantics of these instances is given next. ¥ ¢ The sequence enumFromThenTo is the list [ . the enumeration functions have the following meaning: The sequence enumFromThen is the list [ . based on the primitive functions that convert between a Char and an Int. Integer. . The semantics of these instances is given by Chapter 10. ]. . all the list elements are the same. and Maybe are in this class.EQ. ]. 8 8 ¥¥8 ¤ § § ¢¥ 8 8 ¥¥8 ¤ ¥ ¥ ¢ ¡ ¢¢ £ ¥¡ § ¡ ¡¤ ¡ ¡¢ § ¡ ¡ ¢¤ ¡ ¢ ¤ § ¥ ¤ £ ¡ ¥ ¡¥ ¥ ¤ ¡ The sequence enumFromTo . STANDARD HASKELL CLASSES 87 Enumeration types: (). the list is empty if . Char: the instance is given in Chapter 8. where the increment. . succ adds 1. If the increment is positive or zero. 6. Float. or when they become less than for negative . and Ordering. where the increment. In the case of Float and Double. all of the enumFrom family of functions are strict in all their arguments. If the increment is zero. . . . [LT. £ ¡ ¥ ¤ § £ £ ¤¡ § ].GT]. It is implementationdependent what fromEnum returns when applied to a value that is too large to ﬁt in an Int. The conversions fromEnum and toEnum convert between the type and Int. the list terminates when . Double. ¤ .
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.14). fmap g k a m (m >>= k) >>= h .3). g) id fmap f . PREDEFINED TYPES AND CLASSES Instances of Functor should satisfy the following laws: All instances of Functor deﬁned in the Prelude satisfy these laws. See Chapter 7 for more information about monads. In the Prelude. 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 .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. and for IO raises a user exception in the IO monad (see Section 7. f return a >>= k m >>= return m >>= (\x > k x >>= h) fmap id fmap (f . Maybe. lists. for Maybe returns Nothing. The fail method is invoked on patternmatch failure in a do expression.3. The fail method for lists returns the empty list []. and IO are all instances of Monad.88 CHAPTER 6. “do” expressions provide a convenient syntax for writing monadic expressions (see Section 3. 6.
but not all. Bounded may also be derived for singleconstructor datatypes whose constituent types are in Bounded. The types Int. 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.3. 6. arbitrary precision integers (Integer).3.2–6. Numeric function names and operators are usually overloaded. Similarly. Float is implementationdeﬁned. indeﬁnite.4. an implementation may choose error ( .4 Numbers Haskell provides several kinds of numbers. its subclass Real is also a subclass of Ord. The class Num of numeric types is a subclass of Eq. etc. NUMBERS 89 6. These standards require considerably more complexity in the numeric structure and have thus been relegated to a library.1. since the other comparison operations apply to all but complex numbers (deﬁned in the Complex library). The Bounded class may be derived for any enumeration type. both real and complex. aspects of the IEEE ﬂoating point standard have been accounted for in Prelude class RealFloat. and double precision ﬂoating (Double). single precision ﬂoating (Float).6. The ﬁniteprecision integer type Int covers at . The results of exceptional conditions (such as overﬂow or underﬂow) on the ﬁxedprecision numeric types are undeﬁned. The class Integral contains integers of both limited and unlimited range. page 83. The standard numeric types are listed in Table 6. Some. or a special value such as inﬁnity. using several type classes with an inclusion relation shown in Figure 6. Ordering. Figure 6. Bool. Double should cover IEEE doubleprecision. In particular. The default ﬂoating point operations deﬁned by the Haskell Prelude do not conform to current language independent arithmetic (LIA) standards. the type Rational is a ratio of two Integer values. the numeric types and the operations upon them have been heavily inﬂuenced by Common Lisp and Scheme.7 The Bounded Class class Bounded a where minBound.1. since all numbers may be compared for equality. Other numeric types such as rationals and complex numbers are deﬁned in libraries. Char. maxBound :: a The Bounded class is used to name the upper and lower limits of a type.1 shows the class dependencies and builtin types that are instances of the numeric classes. and the class Floating contains all ﬂoatingpoint types. ¨ ¡£ ¤ ¡£ ¤ . The Prelude deﬁnes only the most basic numeric types: ﬁxed sized integers (Int). it is desirable that this type be at least equal in range and precision to the IEEE singleprecision type. (). maxBound and least the range minBound can be used to determine the exact Int range deﬁned by an implementation. The standard numeric classes and other numeric functions deﬁned in the Prelude are shown in Figures 6. As Int is an instance of the Bounded class. and all tuples are instances of Bounded. minBound is the ﬁrst constructor listed in the data declaration and maxBound is the last. as deﬁned in the Ratio library. a truncated value. semantically).
x ` ` y) ` rem (x `div y. x `mod y) ` ` Also available on integral numbers are the even and odd predicates: even x = odd = x ` ` 2 == 0 rem not . See Section 4. div.4 for a discussion of overloading ambiguity.3.5. respectively. An integer literal represents the application of the function fromInteger to the appropriate value of type Integer. a ﬂoating literal stands for an application of fromRational to a value of type Rational (that is.2 Arithmetic and NumberTheoretic Operations The inﬁx class methods (+). Numeric literals are deﬁned in this indirect way so that they may be interpreted as values of any appropriate numeric type. Ratio Integer).1 Numeric Literals The syntax of numeric literals is given in Section 2.4. 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.90 CHAPTER 6. rem. double precision Complex ﬂoatingpoint Table 6. divMod is deﬁned similarly: quotRem x y divMod x y = = (x `quot y. see section 3. and the unary function negate (which can also be written as a preﬁx minus sign. Similarly. while the result of ‘div‘ is truncated toward negative inﬁnity. single precision Real ﬂoatingpoint. div.1: Standard Numeric Types 6. 6. while the class method (/) applies only to fractional ones.4. The quot. 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. The class methods quot. rem. The quotRem class method takes a dividend and a divisor as arguments and returns a (quotient. even . and mod apply only to integral numbers. remainder) pair. 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. ().4) apply to all numbers. (*).
acos. div.3 Exponentiation and Logarithms The oneargument exponential function exp and the logarithm function log act on ﬂoatingpoint numbers and use base . signum fromInteger a) :: :: :: :: => Num a where a > a > a a > a a > a Integer > a 91 class (Num a. There are three twoargument exponentiation operations: (ˆ) raises any number to a nonnegative integer power. atanh :: a > a Figure 6. including zero. gcd 0 0 raises a runtime error.2: Standard Numeric Classes and Related Operations. The value of ˆ0 or ˆˆ0 is 1 for any . rem. for example gcd (3) 6 = 3. cosh. ¢ )¢ lcm is the smallest positive integer that both and divide. atan :: a > a sinh. cos. and (**) takes two ﬂoatingpoint arguments. 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. Enum a) quot. logBase returns the logarithm of in base . (). sqrt :: a > a (**). gcd is the greatest (positive) integer that divides both and . Part 1 Finally. mod quotRem. logBase :: a > a > a sin. gcd 0 4 = 4. tan :: a > a asin. sqrt returns the principal square root of a ﬂoatingpoint number. Show (+). log. 6.6. tanh :: a > a asinh. Ord a) => Real a where toRational :: a > Rational class (Real a.4. divMod toInteger => :: :: :: Integral a where a > a > a a > a > (a.4. (ˆˆ) raises a fractional number to any integer power. (*) negate abs. NUMBERS class (Eq a. ¢ ¢ ¢ ¢ ¢ ¢ ¢ ¢ ¢ . gcd (3) (6) = 3. there are the greatest common divisor and least common multiple functions. 0** is undeﬁned.
4 Magnitude and Sign A number has a magnitude and a sign.Int) encodeFloat :: Integer > Int > a exponent :: a > Int significand :: a > a scaleFloat :: Int > a > a isNaN. floor :: (Integral b) => a class (RealFrac a. Integral b) => a > b > a (ˆˆ) :: (Fractional a. Fractional b) => a > b Figure 6. Floating a) => RealFloat a where floatRadix :: a > Integer floatDigits :: a > Int floatRange :: a > (Int. Num b) => a > b realToFrac :: (Real a. isInfinite.3: Standard Numeric Classes and Related Operations.Int) decodeFloat :: a > (Integer. 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 . Fractional a) => RealFrac properFraction :: (Integral b) => a truncate.92 CHAPTER 6.a) b b class (Real a. round :: (Integral b) => a ceiling. isDenormalized. Integral b) => a > b > a fromIntegral :: (Integral a. lcm :: (Integral a) => a > a> a (ˆ) :: (Num a. PREDEFINED TYPES AND CLASSES a > > > where (b. isNegativeZero. Part 2 6. isIEEE :: a > Bool atan2 :: a > a > a gcd. The functions abs and signum apply to any number and satisfy the law: abs x * signum x == x For real numbers.4.
and is a fraction with the same type and sign as .4. floor. atan2 1. with in a type that is RealFloat. machineindependent access to the components of a ﬂoatingpoint number. tanh. logBase. For real ﬂoating and . See these references for discussions of branch cuts. where is the ﬂoatingpoint . discontinuities. floatDigits. If decodeFloat x yields ( . encodeFloat performs the inverse of this transformation. should return the same value as atan . where is the value radix. atan2 returns a value in the range [pi. note that is the simplest rational of all. approxRational takes two real fractional arguments and and returns the simplest rational number within of . then x is equal in value to .6. truncate. inclusive. in particular. truncate. **. The function decodeFloat applied to a real ﬂoatingpoint number returns the signiﬁcand expressed as an Integer and an appropriately scaled exponent (an Int). floor. The ceiling. atan2 computes the angle (from the positive xaxis) of the vector from the origin to the point . and round functions can be deﬁned in terms of properFraction. respectively. but implementors can provide a more accurate implementation. ¢ ¢ 6. truncate yields the integer nearest between and . the even integer if is equidistant between two integers.4. and floatRange give the parameters of a ﬂoatingpoint type: the radix of the representation. Class RealFloat provides a version of arctangent taking two real ﬂoatingpoint arguments. The functions floatRadix. pi]. either and are both zero or else of floatDigits x.6 Coercions and Component Extraction The ceiling. and sqrt are provided. and: is an integral number with the same sign as . The function properFraction takes a real fractional number and returns a pair such that . The class methods of class RealFloat allow efﬁcient. where a rational in reduced form is simpler than another if and . which in turn follows Penﬁeld’s proposal for APL [9]. and the lowest and highest values the exponent may assume. and implementation. the number of digits of this radix in the signiﬁcand. and round functions each take a real fractional argument and return an integral result. and furthermore. NUMBERS 93 6.5 Trigonometric Functions Class Floating provides the circular and hyperbolic sine. Every real interval contains a unique simplest rational. Default implementations of tan. The precise deﬁnition of the above functions is as in Common Lisp. the greatest integer not greater than . and tangent functions and their inverses. and floor .4. ceiling returns the least integer not less than . cosine. It follows the Common Lisp semantics for the origin when signed zeroes are supported. Two functions convert numbers to type Rational: toRational returns the rational equivalent of its real argument with full precision. and with absolute value less than 1. but implementors are free to provide more accurate implementations. round returns the nearest integer to . A default deﬁnition of atan2 is provided. ). The functions ¦ ' ¥ ¢ ¢ ¢ 0 ¦ ¦ 0 ¢ ¢ £ ¡ ¢ ' 0 ¦ ¢ 4 A ¢ ' ¢ 4 ¡ ¦¥ ' ¥ ¢ ¢ 1 ¢ ¢ ¢ ¢ 1 ¡ ¦ ¢ ¦ £ ¡ ¤ 4 4 1 £ 1 ¡ ¢ £ ¢ ¦ ¢ ¢ 0 ¢ ¦ ¢ .
Num b) => a > b realToFrac :: (Real a. PREDEFINED TYPES AND CLASSES significand and exponent together provide the same information as decodeFloat. isNegativeZero. these may all return false. exponent 0 is zero. isInfinite. For nonIEEE ﬂoating point numbers. Also available are the following coercion functions: fromIntegral :: (Integral a. isDenormalized. scaled to lie in the open interval . Fractional b) => a > b . The functions isNaN.94 CHAPTER 6. but rather than an Integer. and isIEEE all support numbers represented using the IEEE standard. significand x yields a value of the same type as x. scaleFloat multiplies a ﬂoatingpoint number by an integer power of the radix.
Haskell uses a to integrate I/O operations into a purely functional context. Haskell’s I/O monad provides the user with a way to specify the sequential chaining of actions. it is possible to write many Haskell programs using only the few simple functions that are exported from the Prelude. For example. To achieve this. Special operations (methods in the class Monad.1. recall that String is a synonym for [Char] (Section 6. © ¦ 332 § § ¤¢ © $ 7. as deﬁned in the IO library. and which are described in this section.3. From the perspective of a Haskell programmer. All I/O functions deﬁned here are character oriented.2). the abstract values are the mentioned above. may read as a single newline character.1 Standard I/O Functions Although Haskell provides fairly sophisticated I/O facilities. The order of evaluation of expressions in Haskell is constrained only by data dependencies. it is best to think of a monad as an abstract datatype. 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. In the following. return and linefeed. see Section 6.6) sequentially compose actions. two characters of input. and an implementation is obliged to preserve this order. Some operations are primitive actions. must be ordered in a welldeﬁned manner for program execution – and I/O in particular – to be meaningful. yet has all of the expressive power found in conventional programming languages. The term comes from a branch of mathematics known as category theory. These functions cannot be used portably for binary I/O. The treatment of the newline character will vary on different systems. an implementation has a great deal of freedom in choosing this order. however. 95 ¦ ¢ ¦ 32 4 7 3¢ ¦ ¢ ¦ 32 4 © ¦ 332 § § ¤¢ .Chapter 7 Basic Input/Output The I/O system in Haskell is purely functional. however. Actions. corresponding to conventional I/O operations. In the case of the I/O monad. corresponding to sequencing operators (such as the semicolon) in imperative languages.
The getLine operation raises an exception under the same circumstances as hGetLine. which is read lazily as it is needed.96 CHAPTER 7. The following program simply removes all nonASCII characters from its standard input and echoes the result on its standard output. putChar putStr putStrLn print :: :: :: :: Char > IO () String > IO () String > IO () . The readLn function combines getLine and readIO.19]]) Input Functions terminal). The getContents operation returns all user input as a single string. 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.. The entire input from the standard input device is passed to this function as its argument. Typically. deﬁned the IO library. the read operation from class Read is used to convert the string to a value. a predicate isEOFError that identiﬁes this exception is deﬁned in the IO library. BASIC INPUT/OUTPUT Output Functions These functions write to the standard output device (this is normally the user’s terminal).) main = interact (filter isAscii) .[0. For example. and the resulting string is output on the standard output device. The readIO function is similar to read except that it signals parse failure to the I/O monad instead of terminating the program. 2ˆn)  n <. The interact function takes a function of type String>String as its argument. Printable types are those that are instances of class Show.adds a newline Show a => a > IO () The print function outputs a value of any printable type to the standard output device.3) on endofﬁle. print converts values to strings for output using the show operation and adds a newline. a program to print the ﬁrst 20 integers and their powers of 2 could be written as: main = print ([(n. (The isAscii function is deﬁned in a library.
2]]) 7. 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. methods in the Monad class. The readFile function reads a ﬁle and returns the contents of the ﬁle as a string.x*x)  x <. as with getContents. for example when it is ().0.[0. A message is printed on the standard output before the program completes. Files are named by strings using some implementationspeciﬁc method to resolve strings as ﬁle names. The writeFile and appendFile functions write or append the string. to the ﬁle. their ﬁrst argument.7. The >>= operation passes the result of the ﬁrst operation as an argument to the second operation. but takes its input from "inputfile" and writes its output to "outputfile". The do notation allows programming in a more imperative syntactic style. The >> function is used where the result of the ﬁrst operation is uninteresting. To write a value of any printable type. SEQUENCING I/O OPERATIONS 97 Files These functions operate on ﬁles of characters. main = readFile "inputfile" writeFile "outputfile" (filter isAscii s) putStr "Filtering successful\n" >>= \ s > >> is similar to the previous example using interact. use the show function to convert the value to a string ﬁrst.. are used to compose a series of I/O operations. main = appendFile "squares" (show [(x.2 Sequencing I/O Operations The type constructor IO is an instance of the Monad class. on demand. as with print.1. (>>=) :: IO a > (a > IO b) > IO b (>>) :: IO a > IO b > IO b For example. The ﬁle is read lazily. their second argument. A slightly more elaborate version of the previous example would be: .2. The two monadic binding functions.
Exception propagation must be explicitly provided in a handler by reraising any unwanted exceptions.isEOFError e then return [] else ioError e) the function f returns [] when an endofﬁle exception occurs in g. otherwise. getLine is deﬁned in terms of getChar. The IO library deﬁnes functions that construct and examine IOError values. the catch function establishes a handler that receives any exception raised in the action protected by catch. Exceptions in the I/O monad are represented by values of type IOError. User error values include a string describing the error. the exception is propagated to the next outer handler. These handlers are not selective: all exceptions are caught.getLine putStr "Output file: " ofile <. in f = catch g (\e > if IO.getChar if c == ’\n’ then return "" else do s <. 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. For example. An exception is caught by the most recent handler established by catch.getLine s <. For example.getLine return (c:s) 7. . BASIC INPUT/OUTPUT main = do putStr "Input file: " ifile <.98 CHAPTER 7.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. 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. This is an abstract type: its constructors are hidden from the user. The only Prelude function that creates an IOError value is userError.3 Exception Handling in the I/O Monad The I/O monad includes a simple exception handling system. The isEOFError function is part of IO library.
(>>) fail s = ioError (userError s) The exceptions raised by the I/O functions in the Prelude are deﬁned in Chapter 21. EXCEPTION HANDLING IN THE I/O MONAD 99 When an exception propagates outside the main program. . The fail method of the IO instance of the Monad class (Section 6..6) raises a userError.7. thus: instance Monad IO where . (>>=)..3.3. the Haskell system prints the associated IOError value and exits the program.bindings for return.
BASIC INPUT/OUTPUT .100 CHAPTER 7.
Instance declarations that simply bind primitives to class methods are omitted. To take one particular example. IO. Some of the more verbose instances with obvious functionality have been left out for the sake of brevity. and three submodules. are deﬁned in a system dependent manner in module PreludeBuiltin and are not shown here. Primitives that are not deﬁnable in Haskell. nor are these three modules available for import separately. To reduce the occurrence of unexpected ambiguity errors. such as Char.. constitute a speciﬁcation only of the default method. as it pleases. such as Integral a or Num a. a number of commonlyused functions over lists use the Int type rather than using a more general numeric type. length. It constitutes a speciﬁcation for the Prelude. or less. given with class declarations. That is. part of the speciﬁcation of the Prelude. PreludeText. They do not constitute a speciﬁcation of the meaning of the method in all instances. of the Library modules. The Prelude shown here is organized into a root module. drop. and PreludeIO. 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 modules are described fully in Part II.Chapter 8 Standard Prelude In this chapter the entire Haskell Prelude is given. indicated by names starting with “prim”. This structure is purely presentational. Only the exports of module Prelude are signiﬁcant.” is often used in places where the remainder of a deﬁnition cannot be given in Haskell. The default method deﬁnitions. Many of the deﬁnitions are written with clarity rather than efﬁciency in mind. !!. Some of these modules import Library modules. Declarations for special types such as Integer. Monad. These imports are not. An implementation is not required to use this organisation for the Prelude. and it is not required that the speciﬁcation be implemented as shown here. PreludeList.. and Numeric. These functions are: take. and to improve efﬁciency. of course. 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. An ellipsis “. Prelude. 101 .
for example genericLength. The more general versions are given in the List library. with the preﬁx “generic”.102 CHAPTER 8. . and replicate. STANDARD PRELUDE splitAt.
(). Bool(False. Num((+). floatRange. module PreludeIO. module PreludeText. abs. Just). sinh. (>>). Real(toRational). Maybe(Nothing. scaleFloat.Contains all ‘prim’ values . sqrt. Enum(succ. quotRem. fromInteger). min).)((. isNegativeZero. ceiling. round. (<=). Int.. mapM_. (>=). (/=)). const. recip. div. Double. atan2). not. Char. error. significand. IO. decodeFloat. even. fst. signum. snd. EQ. True). cos. Monad((>>=). String. exp. isIEEE. Functor(fmap). acosh. toInteger). Ordering(LT. mod. cosh. etc. Floating(pi. Integral(quot. log.).103 module Prelude ( module PreludeList. Right). fromRational). return. floor). pred. curry.. rem. Ord(compare. fromEnum. enumFromThen. RealFrac(properFraction. enumFrom. fail).)). (=<<). but are denoted by builtin syntax. Trivial type: ()(()) Functions: (>) Eq((==). Either(Left. maxBound). uncurry.Unicode primitives . Rational. tan. otherwise. atan. ($!) ) where import import import import import import PreludeBuiltin UnicodePrims( primUnicodeMaxChar ) PreludeList PreludeText PreludeIO Ratio( Rational ) . Fractional((/). (<).)((.)). and cannot legally appear in an export list. undefined. truncate. []) Tuple types: (. (>). (ˆ). divMod. sin. RealFloat(floatRadix. gcd. fromIntegral. realToFrac. until. max. Float. id. acos. (ˆˆ). either. (. (. (*). enumFromThenTo). maybe. tanh. floatDigits. sequence. These builtin types are defined in the Prelude. isInfinite. flip. seq. sequence_. ($). toEnum. subtract. GT). asinh. encodeFloat. isNaN. asin. List type: []((:). logBase. lcm. Integer. asTypeOf. odd. mapM. exponent. negate. enumFromTo. Bounded(minBound. (&&). isDenormalized. (). atanh). (**).
 .Minimal complete definition: (==) or (/=) x /= y = not (x == y) x == y = not (x /= y) class (Eq a) => Ord a where compare :: a > a > Ordering (<).104 infixr infixr infixl infixl 9 8 7 6 CHAPTER 8. and cannot legally be given . ‘mod‘ +. <=. STANDARD PRELUDE .note that (min x y. instances and related functions . <.y) or (y.Standard types.Equality and Ordered classes class Eq a where (==). (<=). (>=). ‘quot‘. /=.Minimal complete definition: (<=) or compare .x) max x y  x <= y = y  otherwise = x min x y  x <= y = x  otherwise = y . > &&  >>. but its fixity is given by: infixr 5 : infix infixr infixr infixl infixr infixr 4 3 2 1 1 0 ==. ** *. >=. $!. ˆ. (/=) :: a > a > Bool .a fixity declaration. (>) :: a > a > Bool max. max x y) = (x. ‘div‘.Using compare can be more efficient for complex types. ‘rem‘.The (:) operator is builtin syntax. 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 . /. >>= =<< $. ˆˆ. classes. min :: a > a > a . ‘seq‘ .
] [n.m] .. fromEnum z] class Bounded a minBound maxBound where :: a :: a . (*) :: a > a > a negate :: a > a abs.y = x + negate x = 0 definition: negate or () negate y x class (Num a.] [n..105 .. fromEnum y .] enumFromTo x y = map toEnum [fromEnum x . succ = toEnum .Numeric classes class (Eq a. (subtract 1) .. fromEnum y] enumFromThen x y = map toEnum [fromEnum x... signum :: a > a fromInteger :: Integer > a .. 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.Minimal complete All.Enumeration and Bounded classes class Enum a where succ. fromEnum .] enumFromThenTo x y z = map toEnum [fromEnum x.n’.m] [n. Show a) => Num a where (+). fromEnum pred = toEnum . fromEnum enumFrom x = map toEnum [fromEnum x . Ord a) => Real a where toRational :: a > Rational . (+1) .NOTE: these default methods only make sense for types that map injectively into Int using fromEnum and toEnum. (). except x . fromEnum y .n’..
106 class (Real a.r) = divMod n d = if signum r == where qr@(q. mod quotRem. acos. sinh. logBase :: a > a > a sin.a) a > Integer . tanh :: a > a asinh.Minimal complete definition: quotRem. atan asinh. STANDARD PRELUDE => Integral a where a > a > a a > a > a a > a > (a. cosh.r) = n ‘mod‘ d = r where (q. log. divMod toInteger a) :: :: :: :: CHAPTER 8. acosh. Enum quot. acosh.r) = n ‘div‘ d = q where (q. atanh x ** y = exp (log x * y) logBase x y = log y / log x sqrt x = x ** 0. atan :: a > a sinh.r) = n ‘rem‘ d = r where (q. r+d) else qr quotRem n d . sqrt :: a > a (**). rem div. tan :: a > a asin.5 tan x = sin x / cos x tanh x = sinh x / cosh x . sin.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.Minimal complete definition: pi. cosh asin. log. atanh :: a > a . cos. exp. acos. cos.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. toInteger n ‘quot‘ d = q where (q.
r) = properFraction x if r < 0 then n .r) = properFraction x m = if r < 0 then n . round :: (Integral b) => a ceiling.a) b b .0._) = properFraction x round x = let (n.1 else n where (n.5) of 1 > n 0 > if even n then n else m 1 > m if r > 0 then n + 1 else n where (n.107 class (Real a.r) = properFraction x ceiling x floor x = = . floor :: (Integral b) => a a > > > where (b.1 else n + 1 in case signum (abs r .Minimal complete definition: properFraction truncate x = m where (m. Fractional a) => RealFrac properFraction :: (Integral b) => a truncate.
108 CHAPTER 8.must be after the other double zero tests  otherwise = x + y . scaleFloat. isIEEE :: a > Bool atan2 :: a > a > a . STANDARD PRELUDE class (RealFrac a.x or y is a NaN.Int) decodeFloat :: a > (Integer. even :: (Integral a) => a > a > a = error "Prelude. significand.Minimal complete definition: All except exponent.n) = decodeFloat x significand x scaleFloat k x = = encodeFloat m (.gcd: gcd 0 0 is undefined" = gcd’ (abs x) (abs y) where gcd’ x 0 = x gcd’ x y = gcd’ y (x ‘rem‘ y) .must be after the previous test on zero y  x==0 && y==0 = y . 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 . isDenormalized.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 . return a NaN (via +) . isInfinite. Floating a) => RealFloat a where floatRadix :: a > Integer floatDigits :: a > Int floatRange :: a > (Int.Int) encodeFloat :: Integer > Int > a exponent :: a > Int significand :: a > a scaleFloat :: Int > a > a isNaN. isNegativeZero.Numeric functions subtract subtract even._) = decodeFloat x encodeFloat m (n+k) where (m.floatDigits x) where (m. atan2 exponent x = if m == 0 then 0 else n + floatDigits x where (m.
toRational .The xxxM functions take list arguments.Minimal complete definition: (>>=). but lift the function or . 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 ()) .ˆ: negative exponent" :: (Fractional 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. Num b) => a > b = fromInteger . Fractional b) => a > b = fromRational . 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. Integral b) => a > b > a = if n >= 0 then xˆn else recip (xˆ(n)) :: (Integral 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 . toInteger :: (Real a.
Enum.(useful in continuationpassing style) ($).identity function id :: a > a id x = x .) :: (b > c) > (a > b) > a > c f . STANDARD PRELUDE = () deriving (Eq.. Show.Boolean type data Bool = False  True deriving (Eq..Character type data Char = .110 . ($!) :: (a > b) > a > b f $ x = f x f $! x = x ‘seq‘ f x . Bounded) .. for illustration only . g = \ x > f (g x) . Bounded) .Not legal Haskell. Ord.Unicode values instance Eq Char c == c’ where = fromEnum c == fromEnum c’ . 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 . ’a’  ’b’ . flip :: (a > b > c) > b > a > c flip f x y = f y x seq :: a > b > b seq = . .Boolean functions (&&).constant function const :: a > b > a const x _ = x .rightassociating infix application operators .. Read.function composition (.Trivial type data () CHAPTER 8..Primitive .. Ord. Enum. .flip f takes its (first) two arguments in the reverse order of f.Function type .
fromEnum (maxBound::Char)] enumFromThen c c’ = map toEnum [fromEnum c.. .. Read. fromEnum lastChar] where lastChar :: Char lastChar  c’ < c = minBound  otherwise = maxBound instance Bounded Char where minBound = ’\0’ maxBound = primUnicodeMaxChar type String = [Char] . fail s = ioError (userError s) . fromEnum c’ .. Ord.abstract instance Functor IO where fmap f x = x >>= (return . 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 ..IO type data IO a = ...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 . Read. return = .. f) instance Monad IO where (>>=) = .Either type data Either a b = Left a  Right b deriving (Eq.. Ord. Show) either :: (a > c) > (b > c) > Either a b > c either f g (Left x) = f x either f g (Right y) = g y .Maybe type data Maybe a = Nothing  Just a deriving (Eq.
.... .be expressed directly in Haskell since the constructor lists would be .112 .. instance Integral Integer where . .. data Int instance instance instance instance instance instance instance = minBound . instance Eq Integer where ... ...... The data declarations for these types cannot . . .. .. ....Ordering type data CHAPTER 8..... 1 Eq Int where Ord Int where Num Int where Real Int where Integral Int where Enum Int where Bounded Int where  0  1 . Bounded) ....... maxBound .. instance Enum Integer where . Ord. . . .... ... ..... . Enum.. . instance Ord Integer where ..... STANDARD PRELUDE Ordering = LT  EQ  GT deriving (Eq.. .far too large... . Read....... 1  0  1 . . 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 ..... . instance Real Integer where . Show. where where where where where where where where . ....... data Integer = ..Standard numeric types.. instance Num Integer where . ....
However. truncate enumFrom = numericEnumFrom enumFromThen = numericEnumFromThen enumFromTo = numericEnumFromTo enumFromThenTo = numericEnumFromThenTo numericEnumFrom :: numericEnumFromThen :: numericEnumFromTo :: numericEnumFromThenTo :: numericEnumFrom = numericEnumFromThen n m = numericEnumFromTo n m = numericEnumFromThenTo n n’ . depending on how 0. truncate = numericEnumFrom = numericEnumFromThen = numericEnumFromTo = numericEnumFromThenTo instance Enum Float succ x pred x toEnum fromEnum enumFrom enumFromThen enumFromTo enumFromThenTo .may overflow (Fractional a) => a > [a] (Fractional a) => a > a > [a] (Fractional a. Ord a) => a > a > [a] (Fractional a. This example may have either 10 or 11 elements. Ord) . roundoff errors make these somewhat dubious. 0. The definitions of enumFrom and enumFromThen allow floats to be used in arithmetic series: [0.1 is represented.113 The Enum instances for Floats and Doubles are slightly unusual.may overflow instance Enum Double where succ x = x+1 pred x = x1 toEnum = fromIntegral fromEnum = fromInteger .95]. where = x+1 = x1 = fromIntegral = fromInteger . for illustration only instance Functor [] where fmap = map instance Monad [] m >>= k return x fail s where = concat (map k m) = [x] = [] .Lists data [a] = []  a : [a] deriving (Eq.Not legal Haskell.. 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) .1 .0. The ‘toEnum’ function truncates numbers to Int.
undefined" . and its typing forces its first argument .b. b) > c) = f (fst p) (snd p) . STANDARD PRELUDE (a.b) > a fst (x. . y) uncurry uncurry f p :: (a > b > c) > ((a.b) > b = y .asTypeOf is a typerestricted version of const. Bounded) (a. until :: (a > Bool) > (a > a) > a > a until p f x  p x = x  otherwise = until p f (f x) .b) deriving (Eq.error stops execution and displays an error message error error :: String > a = primError .Tuples data data CHAPTER 8.114 .b.Not legal Haskell. quadruples.) fst :: (a. Ord.curry converts an uncurried function to a curried function.uncurry converts a curried function to a function on pairs.component projections for pairs: .It is expected that compilers will recognize this and insert error .Misc functions . asTypeOf :: a > a > a asTypeOf = const . curry :: ((a.(which is usually overloaded) to have the same type as the second.y) = x snd snd (x. etc. Bounded) .c) deriving (Eq. for illustration only . It is usually used . undefined undefined :: a = error "Prelude. Ord.as an infix operator.(NB: not provided for triples. b) > c) > a > b > c curry f x y = f (x.y) :: (a.appears.c) = (a.until p f yields the result of applying f until p holds.b) = (a.messages that are more appropriate to the context in which undefined .
reverse. splitAt. which must be nonempty. tail. null.1. length. replicate. of a list. concatMap. rather than the beginning. last. filter. all. zipWith3. :: [a] > a = x = error "Prelude. respectively. drop. notElem. zip3. span. scanl1. dropWhile. minimum. (++).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 . scanr.1 Prelude PreludeList . foldl. concat. scanl. foldl1. sum. product. unlines. PRELUDE PRELUDELIST 115 8. maximum. break. zipWith. unzip3) where import qualified Char(isSpace) infixl 9 infixr 5 infix 4 !! ++ ‘elem‘. take. map f head and tail extract the first element and remaining elements. foldr1. last and init are the dual functions working from the end of a finite list.tail: empty list" head head (x:_) head [] tail tail (_:xs) tail [] . any. lines.Standard list functions module PreludeList ( map. iterate. lookup. init. repeat. unzip. cycle. ‘notElem‘ . or. unwords. zip. foldr.head: empty list" :: [a] > [a] = xs = error "Prelude.8. head. (!!). and. scanr1. words. elem. takeWhile.
) ‘f‘ xn foldl1 is a variant that has no starting value argument. (z ‘f‘ x1) ‘f‘ x2.. ..!!: index too large" (x:_) !! 0 = x (_:xs) !! n = xs !! (n1) foldl. again without the starting element: scanl1 f [x1. z ‘f‘ x1. STANDARD PRELUDE [a] > a x last xs error "Prelude.length returns the length of a finite list as an Int. . xn] == (. x1 ‘f‘ x2..] == [x1. . reduces the list using the binary operator..last: empty list" [a] > [a] [] x : init xs error "Prelude... length :: [a] > Int length [] = 0 length (_:l) = 1 + length l .!!: negative index" [] !! _ = error "Prelude..] Note that last (scanl f z xs) == foldl f z xs.. and thus must be applied to nonempty lists..init: empty list" :: [a] > Bool = True = False .] == [z. applied to a binary operator.List index (subscript) operator. x2. x2. scanl is similar to foldl.] 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. ... a starting value (typically the leftidentity of the operator)..116 last last [x] last (_:xs) last [] init init [x] init (x:xs) init [] null null [] null (_:_) :: = = = :: = = = CHAPTER 8. and a list. scanl1 is similar. but returns a list of successive reduced values from the left: scanl f z [x1.((z ‘f‘ x1) ‘f‘ x2) ‘f‘..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 _ [] . . from left to right: foldl f z [x1.. 0origin (!!) :: [a] > Int > a xs !! n  n < 0 = error "Prelude. x2..
or equivalently.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) .. foldr1.cycle: empty list" = xs’ where xs’ = xs ++ xs’ take n. 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. splitAt n xs is equivalent to (take n xs. with x the value of every element. and scanr1 are the righttoleft duals of the . Int > [a] > [a] [] [] x : take (n1) xs take :: take n _  n <= 0 = take _ [] = take n (x:xs) = . .the infinite repetition of the original list. It is the identity . .on infinite lists. f x. applied to a list xs.] iterate :: (a > a) > a > [a] iterate f x = x : iterate f (f x) . or [] if n > length xs. cycle cycle [] cycle xs :: [a] > [a] = error "Prelude.iterate f x returns an infinite list of repeated applications of f to x: .8.foldr. or xs itself if n > length xs.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 . PRELUDE PRELUDELIST 117 .above functions. repeat :: a > [a] repeat x = xs where xs = x:xs . returns the prefix of xs of length n.1. f (f x). scanr. drop n xs returns the suffix of xs after the first n elements.iterate f x == [x.cycle ties a finite list into a circular one.. drop n xs).repeat x is an infinite list.
dropWhile p xs returns the remaining suffix.zs) = span p xs’ break p = span (not . :: String > [String] = [] = let (l. :: (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.xs) where (ys. The resulting strings do not contain newlines.118 drop :: drop n xs  n <= 0 = drop _ [] = drop n (_:xs) = splitAt splitAt n xs  CHAPTER 8.isSpace s of "" > [] s’ > w : words s’’ where (w.zs)  otherwise = ([]. s’) = break (== ’\n’) s in l : case s’ of [] > [] (_:s’’) > lines s’’ :: String > [String] = case dropWhile Char.[]) span p xs@(x:xs’)  p x = (x:ys. break :: (a > Bool) > [a] > ([a]. which were delimited by white space. returns the longest prefix (possibly empty) of xs of elements that satisfy p. STANDARD PRELUDE Int > [a] > [a] xs [] drop (n1) xs :: Int > [a] > ([a]. applied to a predicate p and a list xs. unlines joins lines with terminating newlines. drop n xs) takeWhile. s’’) = break Char. and unwords joins words with separating spaces. words breaks a string up into a list of words.isSpace s’ lines lines "" lines s words words s . span p xs is equivalent to (takeWhile p xs. unlines and unwords are the inverse operations. dropWhile p xs). while break p uses the negation of p. p) lines breaks a string up into a list of strings at newline characters.[a]) span p [] = ([]. Similary.[a]) = (take n xs.
however.True.b)] > Maybe b lookup key [] = Nothing lookup key ((x.reverse xs returns the elements of xs in reverse order.and returns the conjunction of a Boolean list. elem.which must be nonempty. the list must be finite.8. map p all p = and .maximum: empty list" maximum xs = foldl1 max xs minimum [] minimum xs = = error "Prelude. For the result to be . any determines if any element . or :: [Bool] > Bool and = foldr (&&) True or = foldr () False . minimum :: (Ord a) => [a] > a maximum [] = error "Prelude. maximum.maximum and minimum return the maximum or minimum value from a list.g. usually written in infix form. finite.elem is the list membership predicate.disjunctive dual of and. for all. lookup :: (Eq a) => a > [(a. all :: (a > Bool) > [a] > Bool any p = or . any. False. reverse :: [a] > [a] reverse = foldl (flip (:)) [] xs must be finite.e.Applied to a predicate and a list.value at a finite index of a finite or infinite list. notElem :: (Eq a) => a > [a] > Bool elem x = any (== x) notElem x = all (/= x) . Similarly.lookup key assocs looks up a key in an association list. or is the . .of the list satisfies the predicate. x ‘elem‘ xs.minimum: empty list" foldl1 min xs .1.sum and product compute the sum or product of a finite list of numbers. sum. product :: (Num a) => [a] > a sum = foldl (+) 0 product = foldl (*) 1 . PRELUDE PRELUDELIST unlines unlines unwords unwords [] unwords ws :: [String] > String = concatMap (++ "\n") :: [String] > String = "" = foldr1 (\w s > w ++ ’ ’:s) ws 119 . map p .y):xys)  key == x = Just y  otherwise = lookup key xys . and. . . notElem is the negation. results from a False .. and of an ordered type.
b) ˜(as.[b].) zip zip zip3 zip3  The zipWith family generalises the zip family by zipping with the function given as the first argument.b.c)] = zipWith3 (.b:bs. STANDARD PRELUDE zip takes two lists and returns a list of corresponding pairs.[].[]) :: [(a.120  CHAPTER 8. instead of a tupling function.b:bs)) ([].c)] > ([a]..[c]) = foldr (\(a. 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 _ _ _ _ = [] . zipWith (+) is applied to two lists to produce the list of corresponding sums. If one input list is short.bs. unzip unzip unzip3 unzip3 :: [(a.[]) .b. Zips for larger tuples are in the List library :: [a] > [b] > [(a. excess elements of the longer list are discarded.) :: [a] > [b] > [c] > [(a.b)] > ([a].b)] = zipWith (.c:cs)) ([].cs) > (a:as.b. For example.unzip transforms a list of pairs into a pair of lists.c) ˜(as.bs) > (a:as.[b]) = foldr (\(a. zip3 takes three lists and returns a list of triples.
showInt.The instances of Read and Show for Bool.Minimal complete definition: readsPrec readList = readParen False (\r > [pr  ("[". showChar. Show(showsPrec.hs import Char(isSpace.t) [(x:xs. lexLitChar) import Numeric(showSigned. showString. readFloat.v) class Show a showsPrec show showList where :: Int > a > ShowS :: a > String :: [a] > ShowS <<<<<<<<< lex r. lex.u) readl’ s = [([].’ . readl’ t] lex s] ++ lex s.v)  (". Ordering .t) [(x:xs. lexDigits) type type ReadS a ShowS = String > [(a. Either. shows x . ShowS. readl’ u] . PRELUDE PRELUDETEXT 121 8. readParen. showl xs where showl [] = showChar ’]’ showl (x:xs) = showChar ’.s) pr where readl s = [([]. showl xs .8. readList).Mimimal complete definition: show or showsPrec showsPrec _ x s = show x ++ s show x showList [] showList (x:xs) = showsPrec 0 x "" = showString "[]" = showChar ’[’ .t)  ("]".String)] = String > String where :: Int > ReadS a :: ReadS [a] class Read a readsPrec readList . Read(readsPrec.2.". Maybe.t) (xs. readl s]) lex s] ++ reads s. read. shows. isAlphaNum. showLitChar. shows x .t) (x. reads.are done via "deriving" clauses in Prelude.t)  ("]". reads t. isAlpha.u) (xs. show. isDigit. showParen ) where . showList). readSigned.2 Prelude PreludeText module PreludeText ( ReadS. showFloat. readLitChar. readDec.u)  (x.
lex t] of [x] > x [] > error "Prelude. showChar ’)’ else p :: Bool > ReadS a > ReadS a = if b then mandatory else optional where optional r = g r ++ mandatory mandatory r = [(x. t)  (ch.lex r. (str.t) (")".This lexer is not completely faithful to the Haskell lexical syntax. <.lexString t ] lexStrItem (’\\’:’&’:s) = [("\\&".lexLitChar s.s) (x.read: ambiguous parse" :: Char > ShowS = (:) :: String > ShowS = (++) :: Bool > ShowS > ShowS = if b then showChar ’(’ .t) <. ("".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 ] . <."")] = = = lex (dropWhile isSpace s) [(’\’’:ch++"’". t)  (str.t)  ’\\’:t <[dropWhile isSpace s]] lexStrItem s = lexLitChar s .read: no parse" _ > error "Prelude. u)  (ch.s)] lexString s = [(ch++str. ch /= "’" ] [(’"’:str.t) <. STANDARD PRELUDE :: (Read a) => String > a = case [x  (x.t) <.optional s.lexString s] where lexString (’"’:s) = [("\"".’\’’:t) <.u) <. .122 reads reads shows shows read read s :: (Read a) => ReadS a = readsPrec 0 :: (Show a) => a > ShowS = showsPrec 0 CHAPTER 8."") <.lexStrItem s. p .s)] lexStrItem (’\\’:c:s)  isSpace c = [("\\&".u)  ("(".u) showChar showChar showString showString showParen showParen b p readParen readParen b g r <.reads s.
.t) lexExp s = [("".[span isIdChar s]]  (ds.Converting to Integer avoids .lexDigits s] instance Show Int where showsPrec n = showsPrec n . (ds.t) <.t) 123  otherwise = [] where isSingle c = c ‘elem‘ ".t) <.u)  (ds.()[]{}_‘" isSym c = c ‘elem‘ "!@#$%&*+.lexExp t] lexFracExp s = lexExp s lexExp (e:s)  e ‘elem‘ "eE" = [(e:c:ds.u) <.[s].bad character lexFracExp (’.possible difficulty with minInt instance Read Int where readsPrec p r = [(fromInteger i.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 "()" .t) <.’:ds++e. (e.t) <.8.[span isDigit s].2.lexDigits t] ++  (ds.t) <.t) <.readsPrec p r] . PRELUDE PRELUDETEXT lex (c:s)     isSingle c isSym c isAlpha c isDigit c = = = = [([c].s)] <.t) [(c:nam.lexFracExp s ] .s) <. c ‘elem‘ "+". t)  (i.Reading at the Integer type avoids . toInteger .u) <.u)  (c:t) [(e:ds.’:c:cs)  isDigit c = [(’.[span isSym s]]  (nam. (fe./<=>?\\ˆ:˜" isIdChar c = isAlphaNum c  c ‘elem‘ "_’"  (sym.s)] [(c:sym.t) [(c:ds++fe.lexDigits (c:cs).
lex v ] ) .s) <.y).t) <.lex r.Other tuples have similar Read and Show instances <<<<< lex r. Read b) => Read (a.v) (")".lex r.t)<.u) <.lex s ] ) instance Show Char where showsPrec p ’\’’ = showString "’\\’’" showsPrec p c = showChar ’\’’ . w)  ("(".readLitChar s."\’") <. (")". t) <. reads s.w) .b) where showsPrec p (x.u)  (c . shows y .’ .lex r. (c.124 CHAPTER 8.t)  (’\’’:s.". showChar ’. (l. showl cs where showl "" = showChar ’"’ showl (’"’:cs) = showString "\\\"" ._) <.t)  (’"’:s.t)  ("(".readLitChar s]) readList = readParen False (\r > [(l. lex t.readl t ] instance (Show a) => Show [a] where showsPrec p = showList instance (Read a) => Read [a] where readsPrec p = readList . (cs.u) (y.s)] readl (’\\’:’&’:s) = readl s readl s = [(c:cs.t) <. Show b) => Show (a. STANDARD PRELUDE instance Read () where readsPrec p = readParen False (\r > [(().y) = showChar ’(’ .b) where readsPrec p = readParen False (\r > [((x.readl s ]) where readl (’"’:s) = [("". showChar ’\’’ showList cs = showChar ’"’ . showl cs showl (c:cs) = showLitChar c . showLitChar c .Tuples instance (Show a. reads u.s) (x. showl cs instance Read Char readsPrec p where = readParen False (\r > [(c. showChar ’)’ instance (Read a. shows x .t) (".
print. interact.8. writeFile. readLn ) where import PreludeBuiltin type FilePath = String . readFile. getLine. putStrLn. :: = :: = :: = 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 <. PRELUDE PRELUDEIO 125 8.. getChar. getContents. putChar.. readIO. userError.getLine return (c:s) getContents :: IO String getContents = primGetContents . IOError.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 .getChar if c == ’\n’ then return "" else do s <. catch.. ioError.3.3 Prelude PreludeIO module PreludeIO ( FilePath.. Eq IOError where . putStr. appendFile.
("".raises an exception instead of an error readIO :: Read a => String > IO a readIO s = case [x  (x.126 CHAPTER 8.getLine r <."") <.readIO l return r .readIO: ambiguous parse") readLn :: Read a => IO a readLn = do l <. STANDARD PRELUDE interact :: (String > String) > IO () .reads s.lex t] of [x] > return x [] > ioError (userError "Prelude.The hSetBuffering ensures the expected interactive behaviour interact f = do hSetBuffering stdin NoBuffering hSetBuffering stdout NoBuffering s <.getContents putStr (f s) readFile readFile writeFile writeFile :: FilePath > IO String = primReadFile :: FilePath > String > IO () = primWriteFile appendFile :: FilePath > String > IO () appendFile = primAppendFile .t) <.readIO: no parse") _ > ioError (userError "Prelude.
or for left. . In the contextfree syntax. the nonterminals . In both the lexical and the contextfree syntax. and may have a double index: a letter . .or nonassociativity and a precedence level. A precedencelevel variable ranges from 0 to 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.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. for example actually stands for 30 productions. 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 ¢ . right. this is the “maximal munch” rule. this means that conditionals. In the lexical syntax. with 10 substitutions for and 3 for . proceeding from left to right (in shiftreduce parsing.Chapter 9 Syntax Reference 9. Thus. letexpressions. with productions having the form: There are some families of nonterminals indexed by precedence levels (written as a superscript). an associativity variable varies over . Similarly.
.{} 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. 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 ( ) .§§ § § ¦ £$ § § § © ¢ 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. / < = > ? \ ˆ  .˜ 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 ¢ ¡ . [ ] ` { } ¤ ¤© ¤ ¥ § 2 " § ! ¢ §¢ © ¥¢ ¤ ¤ © ¦ 7 ¦ 43¤ 3§ ¢ 32 ¡ © ¢ § ¦ ¨¦¤ © § ¥ £ ¤¢ ¡ ¤¥ § ¦ § ¤ § § 7 3§ ¢ ¤ 7 4¦ ¢ ¡ ¢ 7 .
.2. : :: = \  <.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. 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¢ : : . ¤ ¦ ¦ § ¦ ¦ § ¦ ¦ § ¦ ¦ § ¦ ¦ § ¦ ¦ 2 4 2 4 2 4 2 4 2 4 2 4 § ¦32 ¦ § ¦32 ¦ ¦ 32 § ¦ § ¤ ’ " \ 0o 0x e E +  . . .> 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 .. .
SYNTAX REFERENCE 9. This section deﬁnes it more precisely. provided that . then no layout tokens will be inserted until either the enclosing context ends or a new context is pushed. ¦ ¦ – If the ﬁrst lexeme of a module is not { or module. in which each element is either: – Zero. where is the indentation of the next lexeme if there is one.3 Layout Section 2. The input to is: A stream of lexemes as speciﬁed by the lexical syntax in the Haskell report. The meaning of a Haskell program may depend on its layout. because it is not the beginning of a complete lexeme. where. which is the indentation column of the enclosing layout context.) A stack of “layout contexts”. this lexeme is preceded by where is the indentation of the lexeme.. The speciﬁcation takes the form of a function that performs the translation. 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 [ \ ] ˆ _ \ \ ¢ . the token is inserted after the keyword. as a consequence of the ﬁrst two rules. (NB: a string literal it is not.e.7 gives an informal discussion of the layout rule. The effect of layout on its meaning can be completely described by adding braces and semicolons in places determined by the layout. nor before the . So in the fragment f = ("Hello \ \Bill".6. – A positive integer. do. or if the end of ﬁle has been reached. because it is not preceded only by white space. with the following additional tokens: – If a let. indicating that the enclosing context is explicit (i. The meaning of this augmented program is now layout insensitive. If the innermost context is 0. "Jake") There is no inserted before the \Bill. The effect of layout is speciﬁed in this section by describing how to add braces and semicolons to a laidout program. the programmer supplied the opening brace. preceded by may span multiple lines – Section 2. or of keyword is not followed by the lexeme {. u u – Where the start of a lexeme is preceded only by white space on the same line.130 CHAPTER 9. then it is preceded by is the indentation of the lexeme.
programmers should avoid writing programs in which the meaning of implicit layout depends on the width of nonspace characters. For the purposes of the layout rule. The deﬁnition of is as follows. To determine the column number. delivers a layoutinsensitive translation of . Unicode characters in a source program are considered to be of the same. to avoid visual confusion. LAYOUT 131 The “indentation” of a lexeme is the column number of the ﬁrst character of that lexeme. assume a ﬁxedwidth font with the following conventions: 1§3¥0 0 4 ¤ 2 © The ﬁrst column is designated column 1. the indentation of a line is the indentation of its leftmost lexeme. § § ¥ © § © © © ¨© § § ¡ ¡ § § § ¥ ¥ ¡ ¡ ¡ £ £ ¥ ¥ ¥ § ¡ ¥ ¥ ¥ ¥ ¥ ¥ ¦ ¦ ¡ . width as an ASCII character.9. However. . .3. not 0. and ¦ ¦ 7 7 . u ¤ ¨ ¥ } ¡ if !£ ¡ ¤ £ ¡ ¡ © § § ¥ © § © ¡ ¥ } ¥ ¡ ¡ if and parseerror © & § © ¥ ¤ § ¡ ¡ ¥ ¨ § © ¥ § § © © © ¥ § § ¡ ¡ ¨ © ¨ ¨ ¥ { ¥ ¡ { £ £ ¡ ¡ ¡ ¡ § © § ¡ ¥ ¥ ¤ § § © © § § ¡ ¡ ¥ ¥ } } } parseerror £ ¡ ¡ ¥ £ § © § ¡ ¥ } £ £ £ ¡ ¡ £ £ ¤ £ ¡ ¡ ¥ § & § ¡ ¥ ¥ ¥ ¦ ! ¨ ¥ § ¡ ¥ ¥ ¥ { { { ¡ if if £ ¡ © © ¦ ¥ ¥ § § © & © § ¡ ¥ © ¥ £ ¥ ¥ ¦ § ¡ § © § ¥ ¥ . Tab stops are 8 characters apart. ﬁxed. all start a new line. and “ ” for the empty stream. A tab character causes the insertion of enough spaces to align the current position with the next tab stop. where is the result of lexically analysing a module and adding columnnumber indicators to it as described above. } ¡ if if ¥ © ¨ © ¦ ¥ ¢ 2§ ¨ § § ¥ £ ¡ ¨¦¤¢ ¢ © © ¦ ¥ © ¡ ¢ The application ¢2 0 § 2§ ¡ ¦§ ¦¤ $ §£%§ ¤ ¦ § § £ ¥ § © ¥ ¦ © The characters . where we use “ ” as a stream construction operator.
By matching against 0 for the current layout context. At the end of the input. then parseerror is true. to mimic the situation if the empty braces had been explicit. The token is replaced by . ). and the tokens generated so far by followed by the token “}” represent a valid preﬁx of the Haskell grammar. If the ﬁrst token after a where (say) is not indented more than the enclosing layout context. If not. Some error conditions are not detected by the algorithm. SYNTAX REFERENCE ). A nested context must be further indented than the enclosing context ( fails. It is an error at this point to be within a nonlayout context (i. Note 2.15). because it translates to let { x = e. because doing so involves ﬁxities. including labelled construction and update (Section 3. Note 1 implements the feature that layout processing can be stopped prematurely by a parse error. Note 3. we ensure that an explicit close brace can only match an explicit open brace. the expression ¦ 4 The test brace. then the algorithm fails. and the compiler should indicate a layout error. since the close brace is missing. For example let x = e. then the block must be empty. Note 4. This clause means that all brace pairs are treated as explicit layout contexts. A parse error results if an explicit close brace matches an implicit open brace. Note 5. although they could be: for example let }.4. The parseerror rule is hard to implement in its full generality. ¤ ¥ Note 6. y = x in e’ is valid. and a nonlayout context is active. An example is: § § &§ u © u £ ¥ ¦ . For example. which is set in this case by the deﬁnition of h.e. 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. This is a difference between this formulation and Haskell 1. so empty braces are inserted. the deﬁnition of p is indented less than the indentation of the enclosing context. any pending closebraces are inserted. checks that an implicitlyadded closing brace would match an implicit open 4 £ ¦ Note 1. If none of the rules given above matches. u f x = let h y = let p z = z in p in h Here. y = x } in e’ The close brace is inserted due to the parse error rule above. It can fail for instance when the end of the input is reached.132 CHAPTER 9.
3. namely (do { a == b }) == c 133 because (==) is nonassociative. .9. Programmers are therefore advised to avoid writing code that requires the parser to insert a closing brace in such situations. LAYOUT do a == b == c has a single unambiguous (albeit probably typeincorrect) parse.
It is not necessary to insert additional blank lines before or after these delimiters. ﬁrst developed by Richard Bird and Philip Wadler for Orwell.lhs” indicating a literate Haskell ﬁle. with “.hs” indicating a usual Haskell ﬁle and “. though it may be stylistically desirable. where a line is taken as blank if it consists only of whitespace. and replacing the leading “>” with a space. The program text is recovered by taking only those lines beginning with “>”. In this convention. SYNTAX REFERENCE 9. of course).readLine > putStr "n!= " > print (fact (read l)) This is the factorial function. only those parts of the literate program that are entirely enclosed between \begin{code} \end{code} delimiters are treated as program text. The literate style encourages comments by making them the default. More precisely: Program code begins on the ﬁrst line following a line that begins \begin{code}. the style of comment is indicated by the ﬁle extension.134 CHAPTER 9. Program code ends just before a subsequent line that begins \end{code} (ignoring string literals. is an alternative style for encoding Haskell source code. > 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. By convention.4 Literate comments The “literate comment” convention. Layout and comments apply exactly as described in Chapter 9 in the resulting text. For example. 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 <. A line in which “>” is the ﬁrst character is treated as part of the program. all other lines are comment. To capture some cases where one omits an “>” by mistake. 8 8 ¥¥8 . Using this style. it is an error for a program line to appear adjacent to a nonblank comment line. all other lines are comment. and inspired in turn by Donald Knuth’s “literate programming”.
LITERATE COMMENTS \documentstyle{article} \begin{document} \section{Introduction} 135 This is a trivial program that prints the first 20 factorials.[1.20]] \end{code} \end{document} This style uses the same ﬁle extension.. . product [1. It is not advisable to mix these two styles in the same ﬁle.4.n])  n <. \begin{code} main :: IO () main = print [ (n..9.
) ¨ A§ ¤ 2 4§ 4§ ¡ §¤¤32 4 § ¡§ ¤ 2 8 8¡ ¥¥8 (.) ( (. ¨ A 5 4 ¦ ¢¥¥8 8 8 ¡ ¢ . .. } . hiding ( . . as . ..) ( module . ) ¦ ¨ A§ ¤ !¤32 ¢ S (. SYNTAX REFERENCE .. 8 8 ¥¥8 ¡ ¢ import qualified 2 4 ¨ ¦ ¦ § ¡ ¤ 4 ¢¦ 8 8 ¥¥8 ( . 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. } } © 2§ . . . ¦ ¦ 2 ¤ © 37 2 ¦ ¤ ¢ 4§ ¡ © %§ 3¥ %§ ¦ 72 ¤ ¢ ¢ ¡ ¡ ¤32 § ¤ { type data newtype class instance default ( . 4§ 8 8 ¥¥8 ¡ 7 ¥ ¦ ¡ ( . . . = => => => => . A §¤ 8 8 ¥¥8 ¡ ¤ 4 ¦ ¢ 2 4 . ¨ §¤ A A 5 4 ¦ ¢ ) 8 8 ¥¥8 ..) ( (. . .5 ContextFree Syntax 136 module where 2 ¨ ©§ ¤ 5@¤32 ¢ ¡ § 2 4 ¦ ' { { { . } = ) = 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 .) ( . . .
. %§ © S© ¤ ¢ ¡ ¤ ¡ B%§ ¦ 32 ¢ %§ ¡ ¡ 2 ¨ ¥ § ¦ § ¤ ¡ § S § 32 ¢ ¦ V © ¥ ¦ § 7 ¥ ¦ ¤ ¤ © ¥ £0 ¦ $ 8 8 ¥¥8 ¢ ¡ 7 § 7 ¥ ¦ ¤ ¤ ¢ 8 8 ¥¥8 ¤ © ¥ © ¦ § A 7 ¦ 7 ¥ ¦ © ¥ © ¥ ¤ § ¢ £¡ 7 ¦ $ £0 9.5. . . CONTEXTFREE SYNTAX { . ] ) . . ) 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 . . . } ¦ ¡ 7 ¦ $ ¥ £0 7 ¦ ¦ { . . . ¦ § ¢ ¤ ¢ %§ 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 ( . infixl infixr infix ¦ A §¤ ¦ A¢ 2 ¡ 8¥¥8 8 8 8 ¥¥8 © ¨ > function type type application ¨ ¡ %§ %§ ¢ ¨ ¡ %§ ' %§ ¡ ¡ ¤ ¡ %§ § ¢ © ¤ ( [ ( . . ) tuple type list type parenthesized constructor %§ 8 8 ¥¥8 () [] (>) (.
SYNTAX REFERENCE ) ¦ A© §S© 8 8 ¥¥8 ¡ © ¤S© © S© 7 ¥ %§ ¢ 7¥ 3 ¦ ¡ %§ ¢ ¢ 7¥ ¦ ¡ %§ ¡ %§ ¤ ¡ ( ( [ ( ) distinct distinct © S¤ ¢ %§ . { :: } :: ! deriving ( . CHAPTER 9. ¡ ¡ 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 %§ ¡ ¢ ¢ %§ ¡ { ! . ) © 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 . ] > . ! } . .
<let . . . CONTEXTFREE SYNTAX do { } do expression function application variable general constructor ¤ ¢ ¡ © @§ ¢ S ¢ 4§ © ¨ ¡ ¢ S¢0 139 ¡ ¢ S¢0 ( ( [ [ [ ( ( ( ) . ¦ ¨ ¡ ¢ S 7 ¦ § ¢ ¡ ¡ ¢¡ £ ¡ ¢ A § 8 8 !§ 4 ¤© ¥¥8 ¡ § ¡ 4 § © . ] ¦ ) ) )  ( ) right section labeled construction labeled update { ¦ § . . } ¦ { . .5. . ) ] ¢ £ . .. ¢ ¡ ¨ § . = ¢ ¡ + successor pattern ¤ ¥ § ¦ § ¤ ¢ 6 § ¢ £¡ ¤ ¢ 6 ¦ ¦§ ' 0 6 6 6 § § © @§ © © 4§ 4§ ¢ £¡ ¦ ¦ 6 § © @§ ¦§ 6 6 7 3¢ 7 3¢ ¦ ¡ ¢ ¡ § ¢ £¡ 7 3¢ $ 6 ¡ 6 ¡ ¢ S ¢ ¢ ¡ 0 .  parenthesized expression tuple list arithmetic sequence list comprehension left section left section right section ¤ ¥ £ ¢ . } ¦ <let generator local declaration guard ¢ ¡ 7 . ] . > . . ¨ © ¦ ¨5© 7 7 ¥ ¦ A§ > where where . ¡ § § § ¦ 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.
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 ) . . ¤ ¢ £¡ ¢ § £¡ ¢ . . 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. ) ) 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 § ¢ £¡ . . ) ] ¢ § 8¥¥8 8 8 8 ¥¥8 = § () [] (. .
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).
s) <. (v.t) <.146 CHAPTER 10.lex s. 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)  (u.Precedence of :ˆ: .lex r. (":ˆ:".Note: rightassociativity instance (Read a) => Read (Tree a) where readsPrec d r = readParen (d > up_prec) (\r > [(u:ˆ:v.the most tightlybinding operator Figure 10.Application has precedence one more than .t)  ("Leaf".1: Example of Derived Instances .readsPrec (up_prec+1) t]) r > up_prec) showStr u .t) <.readsPrec (up_prec+1) r. . (m. v of :ˆ: ignored ++ readParen (d > app_prec) (\r > [(Leaf m.w) <. showsPrec (app_prec+1) m showsPrec d (u :ˆ: v) = showParen (d where showStr = showsPrec (up_prec+1) showString " :ˆ: " showsPrec (up_prec+1) .readsPrec (app_prec+1) s]) r up_prec = 5 app_prec = 10 .s) <.
For example. This chapter summarizes this existing practice. 11. 11. This may be prevented by the NOINLINE pragma. Compilers will often automatically inline simple expressions. which are used to give additional instructions or hints to the compiler. An implementation is not required to respect any pragma. except that the enclosing syntax is {# #}. in 147 8 8 ¥¥8 ¡ {# SPECIALIZE . #} ¢ ¡ © S¤ ¡ {# INLINE {# NOINLINE ¢ ¡ %§ ¥ §¥ © ¤ ¢ 6 6 6 6 7¥ ¦ 7 ¥ ¦ ¡ 7 ¥ ¦ #} #} © . but which do not form part of the Haskell language proper and do not change a program’s semantics. but the pragma should be ignored if an implementation is not prepared to handle it.1 Inlining ¢ ¤ © © The INLINE pragma instructs the compiler to inline the speciﬁed variables at their use sites. pragmas appear as comments. Lexically. .2 Specialization © Specialization is used to avoid inefﬁciencies involved in dispatching overloaded functions.Chapter 11 Compiler Pragmas Some compiler implementations support compiler pragmas.
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 .
.
Rational... (%). numerator. reducing the fraction to terms with no common factor and such that the denominator is positive. Show (Ratio a) where .. In each case. and Show... for example Ratio Int may give rise to integer overﬂow even for rational numbers of small absolute size.. Enum.Integral instance (Integral a) => Ratio a = . Num. Fractional (Ratio a) where . Fractional. RealFrac (Ratio a) where . The functions numerator and denominator extract the components of a ratio... Ord. If is a bounded 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.. Real.. there is a type Ratio of rational pairs with components of type . denominator.. 12 % 8 is reduced to 3/2 and 12 % (8) is reduced to (3)/2... Num (Ratio a) where ... RealFrac. Ratio Integer (Integral a) => a > a > Ratio a (Integral a) => Ratio a > a (RealFrac a) => a > a > Rational Eq (Ratio a) where .. For each Integral type . Enum (Ratio a) where . For example.Chapter 12 Rational Numbers module Ratio ( Ratio. the results may be unpredictable. The operator (%) forms the ratio of two integral numbers. these are in reduced form with a positive denominator. Ord (Ratio a) where .. Read. the instance for Ratio simply “lifts” the corresponding operations over . Ratio is an abstract type. approxRational ) where infixl 7 % data (Integral a) => type Rational = (%) :: numerator.. a) => Read (Ratio a) where . Real (Ratio a) where . The type name Rational is a synonym for Ratio Integer.. Ratio is an instance of classes Eq. 151 ¡ ¡ ¡ ¡ ¡ ¡ .
A rational number in reduced form is said to be simpler than another if and . applied to two real fractional numbers x and epsilon. 1 ¦ ¦ 1 ¦ ¦ 1 1 ¦ ¦ ¦ ¡¦ .152 CHAPTER 12. RATIONAL NUMBERS The approxRational function. returns the simplest rational number within the open interval x epsilon x epsilon . Note that it can be proved that any real interval contains a unique simplest rational.
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. E. 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. LIBRARY RATIO 153 12. numerator. (%).1.12. approxRational ) where infixl 7 % ratPrec = 7 :: Int data type (Integral a) Rational => Ratio a = !a :% !a = Ratio Integer deriving (Eq) (%) numerator. denominator.1 Library Ratio .Standard functions on rational numbers module Ratio ( Ratio. Rational. It normalises a ratio by dividing both numerator and denominator by their greatest common divisor.g..% : 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 .
u) <. ("%".u)  (x.t) <.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 .hs but not exported from it! instance (Read a. 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 = . truncate numericEnumFrom numericEnumFromThen numericEnumFromTo numericEnumFromThenTo May overflow These numericEnumXXX functions are as defined in Prelude. RATIONAL NUMBERS instance (Integral a) => RealFrac (Ratio a) where properFraction (x:%y) = (fromIntegral q.r’) = quotRem n’ d’ (n’’:%d’’) = simplest’ d’ r’ d r .assumes 0 < n%d < n’%d’ = q :% 1 = (q+1) :% 1 = (q*n’’+d’’) :% n’’ where (q.r) = quotRem n d (q’.s) <.154 CHAPTER 12.readsPrec (ratPrec+1) r. Integral a) => Read (Ratio a) where readsPrec p = readParen (p > ratPrec) (\r > [(x%y.lex s.readsPrec (ratPrec+1) t ]) instance (Integral a) showsPrec p (x:%y) => Show (Ratio a) where = showParen (p > ratPrec) (showsPrec (ratPrec+1) x . showString " % " . (y. r:%y) where (q.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 .
cis.. . realPart. conjugate. and the phase. . This constructor is strict: if either the real part or the imaginary part of the number is . Put another way.... The function polar takes a complex number and returns a (magnitude. cis is a complex value with magnitude and phase (modulo ). 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. imagPart conjugate mkPolar cis polar magnitude. 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 constructor (:+) forms a complex number from its real and imaginary rectangular components. 155 § ¨ § ¡¤ § .. then so is the phase. (RealFloat a) realPart. the entire number is .. in the range . A complex number may also be formed from polar components of magnitude and phase by the function mkPolar.Chapter 13 Complex Numbers module Complex ( Complex((:+)).. magnitude.. phase) pair in canonical form: The magnitude is nonnegative.. if the magnitude is zero.. .. mkPolar. imagPart.. . The function cis produces a complex number from an angle . polar.a) Complex a > a a) a) a) a) a) a) where where where where where where .
a) = (magnitude z. mkPolar. phase) where infix data 6 :+ => Complex a = !a :+ !a deriving (Eq. 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.156 CHAPTER 13. cis. magnitude. conjugate. imagPart. 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 = .k phase :: (RealFloat a) => Complex a > a phase (0 :+ 0) = 0 phase (x :+ y) = atan2 y x .1 Library Complex module Complex(Complex((:+)). but oriented in the positive real direction. 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. polar. 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.Read. whereas signum has the phase of . but unit magnitude.Show) (RealFloat a) realPart. realPart. The function conjugate computes the conjugate of a complex number in the usual way. 13. abs is a number with the magnitude of .
(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 = .13.1. LIBRARY COMPLEX instance (RealFloat a) (x:+y) + (x’:+y’) (x:+y) .max (exponent x’) (exponent y’) d = x’*x’’ + y’*y’’ fromRational a = fromRational a :+ 0 .
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.158 CHAPTER 13.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 :+ (.v) = if x < 0 then (v’.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 .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 = = = = .z*z)) y’’:+(x’’) where (x’’:+y’’) = log (z + ((y’):+x’)) (x’:+y’) = sqrt (1 .
showHex. readHex. showEFloat. showSigned. showFloat. showIntAtBase. readFloat. showOct. Int) :: (RealFrac a) => ReadS a :: ReadS String 159 .Chapter 14 Numeric module Numeric(fromRat. readInt. showGFloat. readDec. showFFloat. readOct. 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]. readSigned. showInt. floatToDigits.
Int) converts a base and a value to the representation of the value in digits. is the value to show. and scientiﬁc notation otherwise. 245000. Exactly the same applies to the argument of the other two functions. showIntAtBase :: Integral a => a > (Int > Char) > a > ShowS shows a nonnegative Integral number using the base speciﬁed by the ﬁrst argument. – showEFloat uses scientiﬁc (exponential) notation (e. and is a function that can show unsigned values. plus an exponent.String)] 14. and the character representation speciﬁed by the second. NUMERIC This library contains assorted numeric functions. In the call showSigned . showOct. is the precedence of the enclosing context. 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 ([ ].0015).1 Showing functions showSigned :: (Real a) => (a > ShowS) > Int > a > ShowS converts a possiblynegative Real value of type a to a string. and 16 respectively. 2. 8. – showGFloat uses standard decimal notation for arguments whose absolute value lies between 0. the value is shown to full preciIn the call showEFloat sion.1 and 9.45e2. showInt.g. showFFloat.999. £ ¤ ¡ ¡ ¡ ¢ ¦ 7 3¢ ¦ 7 3¢ 7 3¢ © § ¦ ¤ ¥ £ 2 ¤ ¥ © ¡ © § ¦ ¡ £ ¦ 2 ¥ © © § ¦ ¡ ) . many of which are used in the standard Prelude.5e3). 0. .160 CHAPTER 14. More speciﬁcally.g. if is Nothing. floatToDigits :: (RealFloat a) => Integer > a > ([Int]. showEFloat. recall the following type deﬁnitions from the Prelude: type ShowS = String > String type ReadS = String > [(a. 1. if is Just . then at most digits after the decimal point are shown. In what follows.999. showHex :: Integral a => a > ShowS show nonnegative Integral numbers in base 10.
lexDigits :: ReadS String reads a nonempty string of decimal digits. readHex. showHex. array ) ¦ ©§ ¢© ¢ ' § ¤ ¦ § ¦ ©§ § ¤ ¦ ¢© ¢ ' . The inconsistent naming is a historical accident. isOctDigit. given a reader for an unsigned value.4 Library Numeric module Numeric(fromRat. readSigned. showSigned. readFloat :: (RealFrac a) => ReadS a reads an unsigned RealFrac value. floatToDigits. showFFloat.2 Reading functions readSigned :: (Real a) => ReadS a > ReadS a reads a signed Real value. readDec.2. expressed in decimal scientiﬁc notation. showIntAtBase. numerator. READING FUNCTIONS 161 14. ( ( isDigit. 14. showFloat. readOct. lexDigits) where import Char import Ratio import Array ( . showGFloat. § (NB: readInt is the “dual” of showIntAtBase. showInt. and hexadecimal notation respectively. isHexDigit digitToInt.) 14. readInt.3 Miscellaneous fromRat :: (RealFloat a) => Rational > a converts a Rational value into any type in class RealFloat. and converts a valid digit character to an Int. showEFloat. is a predicate distinguishing valid digits in this base. Array. denominator ) (!). readDec. showOct. readInt :: (Integral a) => a > (Char>Bool) > (Char>Int) > ReadS a reads an unsigned Integral value in an arbitrary base. both upper or lower case letters are allowed. intToDigit ) (%).14. in decimal. octal. In the hexadecimal case. is the base. readHex :: (Integral a) => ReadS a each read an unsigned number. readOct. In the call readInt . and readDec is the “dual” of showInt. readFloat.
162 CHAPTER 14. p’) = scaleRat (toRational b) minExp xMin xMax p0 (x / f) r = encodeFloat (round x’) p’ . Int) scaleRat b minExp xMin xMax p x = if p <= minExp then (x. . scaleRat :: Rational > Int > Rational > Rational > Int > Rational > (Rational.first.p) ‘max‘ minExp f = if p0 < 0 then 1 % expt b (p0) else expt b p0 % 1 (x’.a first guess of the exponent.the real minimum exponent xMin = toRational (expt b (p1)) xMax = toRational (expt b p) p0 = (integerLogBase b (numerator x) integerLogBase b (denominator x) .Exponentiation with a cache for the most common numbers. NUMERIC . or p (the exponent) <= minExp.Handle exceptional cases . fromRat’ :: (RealFloat a) => Rational > a fromRat’ x = r where b = floatRadix r p = floatDigits r (minExp0. _) = floatRange r minExp = minExp0 .Scale x until xMin <= x < xMax.Scale the rational number by the RealFloat base until .This converts a rational to a floating.Then round the rational to an Integer and encode it with the exponent .Conversion process: . .that we got from the scaling.fromRat’ (x) else fromRat’ x .it lies in the range of the mantissa (as used by decodeFloat/encodeFloat).To speed up the scaling process we compute the log2 of the number to get . fromRat :: (RealFloat a) => Rational > a fromRat x = if x == 0 then encodeFloat 0 0 else if x < 0 then . .Fractional instances of Float and Double. p) . This should be used in the . 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. 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 .p .
but that would be very slow! We are just slightly more clever. 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.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.t) read’’ r = [(n.number to show > ShowS showIntAtBase base intToDig n rest  n < 0 = error "Numeric.base > (Int > Char) .s) (x.s)  (str. read’’ s] lex r. .s) (n. showOct.2ˆn)  n <. 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 . readPos str] .4..maxExpt) [(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 ’’ .Try squaring the base first to cut down the number of divisions.showInt. integerLogBase :: Integer > Integer > Int integerLogBase b i = if i < b then 0 else ."") <<<< lex r.Compute the (floor of the) log of i in base b. .digit to char > a .14.showIntAtBase: can’t show negative numbers"  n’ == 0 = rest’  otherwise = showIntAtBase base intToDig n’ rest’ where (n’. maxExpt]] 163 . showHex are used for positive numbers only showInt. showOct.t)  ("". showPos (x))  otherwise = showPos x .Simplest way would be just divide i by b until it’s smaller then b.[minExpt .
.Leading minus signs must be handled elsewhere. data FFFormat = FFExponent  FFFixed  FFGeneric .nonnull isDig s ] .r) <. 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. r)  (ds.readInt reads a string of digits using an arbitrary base. . digToInt) ds).These are the format types.Unsigned readers for various bases readDec.164 CHAPTER 14. readInt :: (Integral a) => a > (Char > Bool) > (Char > Int) > ReadS a readInt radix isDig digToInt s = [(foldl1 (\n d > n * radix + d) (map (fromIntegral . readOct. NUMERIC .
4.Always prints a decimal point  e > 0 > take e (ds ++ repeat ’0’) .’:take dec’ (repeat ’0’) ++ "e0" _ > let (ei.0e0" [d] > d : ".’ : ds ++ ’e’:show (e1) Just dec > let dec’ = max dec 1 in case is of [] > ’0’:’. 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. e) = let ds = map intToDigit is in case fmt of FFGeneric > doFmt (if e < 0  e > 7 then FFExponent else FFFixed) (is. is’) = roundTo base (dec’+1) is d:ds = map intToDigit (if ei > 0 then init is’ else is’) in d:’.’:ds ++ "e" ++ show (e1+ei) FFFixed > case decs of Nothing .14.0e" ++ show (e1) d:ds > d : ’.
The version here uses a much slower logarithm estimator..Print decimal point iff dec > 0 let dec’ = max dec 0 in if e >= 0 then let (ei.. rs) = splitAt (e+ei) (map intToDigit is’) in mk0 ls ++ mkdot0 rs else let (ei.Print 34.and an exponent. replicate n 0) f 0 (i:_) = (if i >= b2 then 1 else 0.when the format specifies no ." ++ mk0 (replicate (e) ’0’ ++ ds) Just dec > . is) > (0. is) > (1. 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" . not . 0:ds) else (0. if floatToDigits r = ([a. e) .ab.base1]) . Int) .digits after the decimal point roundTo :: Int > Int > [Int] > (Int.Print 0.’ : s . 1 : is) where b2 = base ‘div‘ 2 f n [] = (0. in PLDI 96.’ : mk0 (drop e ds)  otherwise > "0. b. In general. .166 CHAPTER 14. . i’:ds) Based on "Printing FloatingPoint Numbers Quickly and Accurately" by R. Dybvig.This function returns a nonempty list of digits (Ints in [0.. z]. K. is) (1.z * baseˆe floatToDigits :: (RealFloat a) => Integer > a > ([Int].. It should be improved. is’) = roundTo base (dec’ + e) is (ls.34.G. . []) f d (i:is) = let (c. NUMERIC ++ ’. [Int]) roundTo base d is = case f d is of (0.then r = 0. not 34. ds) = f (d1) is i’ = c + i in if i’ == base then (1. Burger and R.34 mk0 s = s mkdot0 "" = "" mkdot0 s = ’.
p 167 . (p . e) = let n = minExp . bˆ(e)*2.e0 in if n > 0 then (f0 ‘div‘ (bˆn).the real minimum exponent . b.the fraction will make it err even more. 2*b. s. be.Haskell requires that f be adjusted so denormalized numbers . Ignoring .Haskell promises that p1 <= logBase b f < p.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 . mUp.the following will err on the low side. Adjust for this.will have an impossibly low exponent. b) else (f*be*2. 1. be*b. . e0+n) else (f0. _) = floatRange x p = floatDigits x b = floatRadix x minExp = minExp0 . e0) (r.logBase 10 2 is slightly bigger than 3/10 so . 2.4. bˆ(e+1)*2. f :: Integer e :: Int (f.14. 1) else (f*2. mDn) = if e >= 0 then let be = bˆe in if f == bˆ(p1) then (f*be*b*2. 0) floatToDigits base x = let (f0. LIBRARY NUMERIC floatToDigits _ 0 = ([]. be) else if e > minExp && f == bˆ(p1) then (f*b*2. 1) k = let k0 = if b==2 && base==10 then . e0) = decodeFloat x (minExp0.
point than the Haskell lexer. (ds’.lexFrac d ] lexFrac (’. True) > if rn’ * 2 < sN then dn : ds else dn+1 : ds (False. t)  ("NaN".d) <.readExp s] ++ [ (0/0.This floating point reader uses a less restrictive syntax for floating .t) <.lexDigits r. rn’) = (rn * base) ‘divMod‘ sN mUpN’ = mUpN * base mDnN’ = mDnN * base in case (rn’ < mDnN’.t)  (k.s) <.lex r] ++ [ (1/0.d. readFloat readFloat r :: (RealFrac a) => ReadS a = [(fromRational ((n%1)*10ˆˆ(kd)). True) > dn+1 : ds (True. rn’ + mUpN’ > sN) of (True. 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). (k.t) <.t) <. NUMERIC else fixup (n+1) in fixup k0 gen ds rn sN mUpN mDnN = let (dn.readFix r.[span p s]] .’ is optional.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.168 CHAPTER 14.t) <.s)] readExp (e:s)  e ‘elem‘ "eE" = readExp’ s readExp s = [(0. k) in .’:ds) = lexDigits ds lexFrac s = [("". False) > dn : ds (False.lex r] where readFix r = [(read (ds++ds’). t)  (ds.t)  (n.t)  (cs@(_:_).t) <. The ‘. t)  ("Infinity".t) <.s)] readExp’ (’’:s) = [(k. length ds’.
Ix b) ..b) where where where where ...a) > (a. ..u) i == i ‘elem‘ range (l..u) i == i ..when i is in range inRange (l.a) > (a. where . index. the inRange operation tells whether a particular subscript lies in the range deﬁned by a bounding pair. It is used primarily for array indexing (see Chapter 16).. to an integer. which deﬁnes the lower and upper bounds of the range.... index. instance instance instance instance (Ix a. The Ix class contains the methods range.Chapter 15 Indexing Operations module Ix ( Ix(range.. inRange. and a subscript. The index operation maps a bounding pair. . rangeSize) ) where class Ord a => range index inRange rangeSize Ix :: :: :: :: a where (a. An implementation is entitled to assume the following laws about these operations: range (l.u)) == [0.a) > [a] a > Int a > Bool Int Char Int Integer (a. .u)] 169 ..u) !! index (l. The range operation enumerates all subscripts.u) map index (range (l. and inRange.et cetera instance instance Ix Ix Ix => Ix Ix Bool Ix Ordering where .rangeSize (l.a) > (a.. The Ix class is used to map a contiguous subrange of values in a type onto integers.
using a deriving clause on a data declaration (Section 4. whose constituent types are instances of Ix.Blue) Green inRange (Yellow. For example. the nullary constructors are assumed to be numbered lefttoright with the indices being to inclusive. For an enumeration. £ ¥ ¤ == == == [Yellow. INDEXING OPERATIONS 15. This is the same numbering deﬁned by the Enum class.1 Deriving Instances of Ix It is possible to derive an instance of Ix automatically. the derived instance declarations are as shown for tuples in Figure 15.170 CHAPTER 15. Such derived instance declarations for the class Ix are only possible for enumerations (i.Blue) index (Yellow.Blue) Red For singleconstructor datatypes.3).Blue] 1 False .Green.1. A Haskell implementation must provide Ix instances for tuples up to at least size 15. datatypes having only nullary constructors) and singleconstructor datatypes. given the datatype: data Colour = Red  Orange  Yellow  Green  Blue  Indigo  Violet we would have: range (Yellow.3.e.
Instances for other tuples are obtained from this scheme: ...u’)) (i..ak) where range ((l1.. ..u’) i’ inRange ((l.l’)...uk)) (i1.uk)) = [(i1.u’)) (i.ik) = index (lk.u2.range (l1.instance (Ix a1.range (l2...(u1...range (lk. DERIVING INSTANCES OF IX 171 instance (Ix a....u1). i’ <...u) i * rangeSize (l’.lk)..u’) + index (l’.ik) = inRange (l1...(u...l2.u1))) inRange ((l1...i’) = inRange (l.u’) i’ .l2.lk).u2..i’)  i <..l’).u2).1....u’)) = [(i..i2. index (l1.i2.(u.(u....uk) ik + rangeSize (lk.(u1.(u1.l’).15. .u).range (l’.. Ix a2... ik <.... .lk). i2 <.u2) i2 && .uk)) (i1.....uk1) ik1 + rangeSize (lk1.u2..u’)] index ((l.u1) i1 && inRange (l2..i2.l2.uk1) * ( .u) i && inRange (l’.range (l.uk) * ( index (lk1..uk) ik Figure 15. Ix ak) => Ix (a1.a2.ik)  i1 <.i’) = index (l..b) where range ((l. Ix b) => Ix (a..1: Derivation of Ix instances .uk)] index ((l1. && inRange (lk.
n) i = [m.n] = = = i .n) i  inRange b i = fromInteger (i ." m <= i && i <= n instance Ix Integer where range (m. For example.index: Index out of range. INDEXING OPERATIONS 15.but the range is nevertheless empty range ((1..index: Index out of range.a) > [a] index :: (a. for all tuples Ix Bool .c’) ci  inRange b ci = fromEnum ci .fromEnum c  otherwise = error "Ix..n) i = m <= i && i <= n instance instance instance instance (Ix a.2)." inRange (c.2) <= (2.as derived Ix () .1) . b) .n) i  inRange b i  otherwise inRange (m.n] index b@(c.as derived.2 Library Ix module Ix ( Ix(range.(2.172 CHAPTER 15.h)  null (range b) = 0  otherwise = index b h + 1 .n) index b@(m..n) = [m.n] index b@(m.as derived Ix Ordering .as derived ." inRange (m.a) > a > Int inRange :: (a.m error "Ix. inRange. rangeSize) ) where class Ord a => Ix a where range :: (a.a) > Int rangeSize b@(l.a) > a > Bool rangeSize :: (a.n) = [m.fails if the bounds are tuples.1)) = [] instance Ix Char where range (m.Ix b) => Ix (a.c’) i = c <= i && i <= c’ instance Ix Int where range (m.NB: replacing "null (range b)" by "not (l <= h)" .index: Index out of range.m)  otherwise = error "Ix. (1. index.
.. elems.c)] > Array a b :: (Ix a) => Array a b > [(a..b)] > Array a b (a. a. indices.a) > [b] > Array a b Array a b > a > b Array a b > (a. 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 . assocs..c)] > Array a b :: (Ix a. accumArray. . ...Chapter 16 Arrays module Array ( module Ix. listArray. array.a) > [(a. . a..b)] > Array a b :: (Ix a) => (b > c > b) > Array a b > [(a. 173 . // => Array a b = .. accum.a) > [(a.Abstract (Ix a) array listArray (!) bounds indices elems assocs accumArray (//) accum ixmap instance instance instance instance instance (a. (Ix (Ix (Ix (Ix a. (//). :: :: :: :: :: :: :: :: (Ix (Ix (Ix (Ix (Ix (Ix (Ix (Ix a) a) a) a) a) a) a) a) => => => => => => => => .export all of Ix for convenience Array. Ix b) => (a.b)] (b > c > b) > b > (a. (!).. . . a. ixmap ) where import Ix infixl 9 data !...a) > (a > b) > Array b c > Array a c Eq b) Ord b) Show a. bounds. Show b) Read a..a) Array a b > [a] Array a b > [b] Array a b > [(a.
ARRAYS Haskell provides indexable arrays. then the array is legal. ). Thus. If any two associations in the list have the same index. Typically. arrays are treated as data. Because the indices must be checked for these errors. elems. The bounds function applied to an array returns its bounds. The ﬁrst argument of accumArray is the accumulating £ £ ¤¢ £ ¡ £ £ ¥ .10)).100) ((1. or associations. but the values associated with indices that do not appear will be undeﬁned (i. ) if any index in the list is out of bounds. respectively. the type of arrays with indices in a and elements in b is written Array a b. in index order. If. the value at that index is undeﬁned (i. this module is exported from Array so that modules need not import both Array and Ix. but nonstrict in the values. 16. array is strict in the bounds argument and in the indices of the association list. The ﬁrst argument of array is a pair of bounds. but bounds still yields the bounds with which the array was constructed. 16. Indexing an empty array always gives an arraybounds error. To ensure the possibility of such an implementation. The functions indices. For example. Figure 16. in that order..e. An array may be constructed from a pair of bounds and a list of values in index order using the function listArray. These bounds are the lowest and highest indices in the array.[2. a programmer may reasonably expect rapid access to the components. and assocs. i * a!(i1))  i <.e.1. in particular. ). x) deﬁnes the value of the array at index i to be x. elements. An array may be created by the function array. a oneorigin vector of length 10 has bounds (1. but empty.1). Since most array functions involve the class Ix.100]]) Not every index within the bounds of the array need appear in the association list.1 shows some examples that use the array constructor. which may be thought of as functions whose domains are isomorphic to contiguous subsets of the integers. each of the index type of the array. and a oneorigin 10 by 10 matrix has bounds ((1. return lists of the indices.10).1 Accumulated Arrays Another array creation function.174 CHAPTER 16. in any dimension.(10. ). using an accumulating function which combines the values of associations with the same index. the lower bound is greater than the upper bound. recurrences such as the following are possible: a = array (1.e. The (!) operator denotes array subscripting. . Functions restricted in this way can be implemented efﬁciently.1 Array Construction If a is an index type and b is any type.1) : [(i. accumArray. when applied to an array. An association (i. not as general functions. The array is undeﬁned (i. relaxes the restriction that a given index may appear at most once in the association list. this The second argument of array is a list of associations of the form ( list will be expressed as a comprehension.
inRange bnds i] If the accumulating function is strict. Num b) => (a.range b]) 0 0 .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.range b] where b = bounds a . the remaining two arguments are a bounds pair and an association list.n]] is the same matrix.2. z)  i <. accumulated arrays should not in general be recursive. (As with the array function. except with the diagonal zeroed.Scaling an array scale :: (Num a. the indices in the association list must be unique for the updated elements to be deﬁned.a) > [a] > Array a b hist bnds is = accumArray (+) 0 bnds [(i. Thus. Num b) => Array a b > Array a b > b inner v w = if b == bounds w then sum [v!i * w!i  i <. Thus accumArray can be deﬁned using accum: accumArray f z b = accum f (array b [(i.[1. if m is a 1origin. i)  i <. INCREMENTAL ARRAY UPDATES . as for the array function.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. hist produces a histogram of the number of occurrences of each index within a speciﬁed range: hist :: (Ix a. Ix scale x a = array b where b of numbers by a given number: b) => a > Array b a > Array b a [(i.range b] = bounds a 175 .The inner product of two vectors inner :: (Ix a. then m//[((i. For example. then accumArray is strict in the values. in the association list.i).16. accum takes an array and an association list and accumulates pairs from the list into the array with the accumulating function . as well as the indices. a!i * x)  i <.) For example. given a list of values of some index type.. unlike ordinary arrays.1: Array examples function.range b] else error "inconformable arrays for inner product" where b = bounds v Figure 16. the second is an initial value. 1)  i<is. 16. 0)  i <. n by n matrix.
indices.u) (\i>(i. .176 CHAPTER 16._)) = bounds x . elems.a) > Array a b > Array a b subArray bnds = ixmap bnds (\i>i) ._). respectively.A row of a matrix row :: (Ix a.a) b > Array a b diag x = ixmap (l. array.export all of Ix Array. accum.Diagonal of a matrix (assumed to be square) diag :: (Ix a) => Array (a. (!).2: Derived array examples 16.b) c > Array b c row i x = ixmap (l’. listArray. Ix b) => a > Array (a.j)) x where ((_. // data (Ix a) => Array a b = MkArray (a.(_. 16. accumArray.u’) (\j>(i.i)) x where ((l. (//). ixmap ) where import Ix import List( (\\) ) infixl 9 !.a) (a > b) deriving () .Projection of first components of an array of pairs firstArray :: (Ix a) => Array a (b. with the mapping that the original array embodies.3 Derived Arrays The two functions fmap and ixmap derive new arrays from existing ones. Figure 16.u’)) = bounds x .c) > Array a b firstArray = fmap (\(x.2 shows some examples.(u.A rectangular subarray subArray :: (Ix a) => (a.4 Library Array module Array ( module Ix.l’). ARRAYS .y)>x) Figure 16. The fmap function transforms the array values while ixmap allows for transformations on array indices. bounds. assocs. they may be thought of as providing function composition on the left and right.
a!i)  i <. a ! f i)  i <.4.a) > (a > b) > Array b c > Array a c = array b [(i.a) > [(a.b)) (range b) vs) :: (Ix a) => Array a b > a > b = f :: (Ix a) => Array a b > (a. Eq b) => Eq (Array a b) a == a’ = assocs a == assocs a’ where .c)] > Array a b = foldl (\a (i.a) > [b] > Array a b = array b (zipWith (\ a b > (a.z)  i <.a) > [(a. f) instance (Ix a.a) = b :: (Ix a) => Array a b > [a] = range . Ix b) => (a.indices a] :: (Ix a) => Array a b > [(a.f (a!i) v)]) :: (Ix a) => (b > c > b) > b > (a.ivs] then MkArray b (\j > case [v  (i.ivs.b)] > Array a b = array (bounds a) (old_ivs ++ new_ivs) where old_ivs = [(i.16. i == j] of [v] > v [] > error "Array.indices a.v) > a // [(i.b)] > Array a b array b ivs = if and [inRange b i  (i.!: \ \multiply defined array element") else error "Array.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.indices a] :: (Ix a) => Array a b > [(a.!: \ \undefined array element" _ > error "Array._) <.c)] > Array a b = accum f (array b [(i.new_ivs] :: (Ix a) => (b > c > b) > Array a b > [(a. i ‘notElem‘ new_is] new_is = [i  (i. LIBRARY ARRAY 177 array :: (Ix 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 .b)] = [(i.range b]) :: (Ix a. bounds :: (Ix a) => Array a b > [b] = [a!i  i <. a!i)  i <._) <.v) <.
Show a. showsPrec (arrPrec+1) (assocs a) ) instance (Ix a. showsPrec (arrPrec+1) (bounds a) . (b.lex r. Read b) => Read (Array a b) where readsPrec p = readParen (p > arrPrec) (\r > [ (array b as.Precedence of the ’array’ function is that of application itself arrPrec = 10 . showChar ’ ’ .178 instance (Ix a. u)  ("array".u) <. Ord b) => Ord (Array a b) a <= a’ = assocs a <= assocs a’ where CHAPTER 16.readsPrec (arrPrec+1) t ]) . ARRAYS instance (Ix a.readsPrec (arrPrec+1) s. Read a.s) <. (as.t) <. Show b) => Show (Array a b) where showsPrec p a = showParen (p > arrPrec) ( showString "array " .
179 .
find. unzip5. sortBy. minimumBy. cycle. and. inits. (!!). nub. last. foldl. insertBy. union.This is builtin syntax map. sort. unzip. unwords. elem. splitAt. transpose. []). zipWith7. words. genericTake. isSuffixOf. reverse.180 CHAPTER 17. . zipWith3. unlines. iterate. nubBy. take. zip4. intersperse. LIST UTILITIES Chapter 17 List Utilities module List ( elemIndex. . deleteBy. foldl1. scanr.[]((:). (++). genericIndex. break. elemIndices. zip3. lines. drop. init. minimum. scanr1. dropWhile. replicate. unzip4.. partition. all. tail. unzip6. span. isPrefixOf.. filter. zipWith4. lookup.and what the Prelude exports . takeWhile. sum. unfoldr. zipWith. zip7. deleteFirstsBy. (\\). head. notElem. 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] . genericReplicate. unzip7. delete. genericSplitAt. zipWith6.. scanl. intersectBy. maximumBy. zipWith5. null. or. concat. concatMap. genericLength. mapAccumL. zip6. groupBy. group. zip5. maximum. insert. findIndices. repeat. any. product. findIndex. intersect. scanl1. foldr1. length. zip. mapAccumR. tails. foldr. genericDrop. unionBy.
[b].b.b.d.g)] > ([a].c.d.e.f.c.d.f)] :: [a] > [b] > [c] > [d] > [e] > [f] > [g] > [(a. c)) > a > [b] > (a.[g]) This library deﬁnes some lesserused operations over lists.[b].d. c)) > a > [b] > (a.e)] :: [a] > [b] > [c] > [d] > [e] > [f] > [(a.[d].[c].[c].c.[c].[d]. [c]) (b > Maybe (a.[c]. .f.c.[e]) :: [(a.[b].[d]) :: [(a.[b].c.b.d.b.[e].[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.e)] > ([a].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.e.d.[b]) Integral a => [b] > a > b Integral a => a > b > [b] :: [a] > [b] > [c] > [d] > [(a.e.b.c.c.b.b.f)] > ([a].[f]) :: [(a.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.[e]. [c]) (a > b > (a.d)] :: [a] > [b] > [c] > [d] > [e] > [(a.d)] > ([a].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].[f].e.b.[d].
or Nothing. provided that their ﬁrst argument contains no duplicates.4] . (\\). Nothing is returned if not (val ‘elem‘ list).g. delete ’a’ "banana" == "bnana" (\\) is list difference (nonassociative). findIndex returns the corresponding index. union and intersect (and their By variants) preserve the invariant that their result does not contain duplicates. nub (meaning “essence”) removes duplicates elements from a list.3. of val in list as Just index.2 “Set” operations There are a number of “set” operations deﬁned over the List type.. Thus. elemIndices val list returns an inorder list of indices. e. if any. delete. For example: nub [1. "dog" ‘union‘ "cow" == "dogcw" intersect is list intersection.1. In the result of xs \\ ys. nub removes duplicate elements from a list. [1. findIndices returns a list of all such indices..3. e.4] ‘intersect‘ [2. LIST UTILITIES 17. the ﬁrst occurrence of each element of ys in turn (if any) has been removed from xs. find returns the ﬁrst element of a list that satisﬁes a predicate. union is list union.g.6.3. if there is no such element.3..3] = [1.g.8] == [2. giving the occurrences of val in list. (xs ++ ys) \\ xs == ys.1 Indexing lists elemIndex val list returns the index of the ﬁrst occurrence. e.182 CHAPTER 17.4] delete x removes the ﬁrst occurrence of x from its list argument. 17.2.4.4.
"bc"."i"."a".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. transpose [[1. intersperse ’. mapAccumR is similar to mapAccumL except that the list is processed from righttoleft rather than lefttoright."i".c. e.6]] == [[1.3 List transformations intersperse sep inserts sep between the elements of its list argument. 17. filter (not ."pp". tails "abc" == ["abc". longest ﬁrst.3].3..5]. which inserts objects into a list according to the speciﬁed ordering relation.[2.4].4 unfoldr The unfoldr function is a “dual” to foldr: while foldr reduces a list to a summary value. respectively. here speciﬁed in terms of the insertBy function.d. partition p xs == (filter p xs. insert inserts a new element into an ordered list (arranged in increasing order). group splits its list argument into a list of lists of equal.’ "abcde" == "a. LIST TRANSFORMATIONS 183 17."ss"."i"] inits returns the list of initial segments of its argument list. unfoldr builds a list from a seed value.17. For example: .g.5..[3. shortest ﬁrst..""] mapAccumL f s l applies f to an accumulating “state” parameter s and to each element of l in turn. i. adjacent elements. For example group "Mississippi" == ["M"."abc"] tails returns the list of all ﬁnal segments of its argument list."ss".e" transpose transposes the rows and columns of its argument.[4."ab".2. "c". inits "abc" == ["". p) xs) sort implement a stable sorting algorithm.g.b. e."i".e.
The “By” variants are as follows: nubBy. maximumBy. overloaded functions have a nonoverloaded counterpart whose name is sufﬁxed with “By”. sortBy. isPrefixOf. The library does not provide elemBy. the predicate is assumed to deﬁne a total ordering.y) f’ z = Nothing 17.5 Predicates isPrefixOf and isSuffixOf check whether the ﬁrst argument is a preﬁx (resp. minimumBy. sufﬁx) of the second argument. For example. unfoldr can undo a foldr operation: unfoldr f’ (foldr f z xs) == xs if the following holds: f’ (f x y) = Just (x. f x)) In some cases. intersectBy. elemIndices. when the “By” function replaces an Ord context by a binary predicate. insertBy.6 The “By” operations By convention.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. 17. LIST UTILITIES iterate f == unfoldr (\x > Just (x. because any (eq x) does the same job as elemBy eq x would. 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. isSuffixOf) were not considered important enough to have “By” variants. groupBy. the predicate is assumed to deﬁne an equivalence. A handful of overloaded functions (elemIndex. the equality method may not be appropriate in all situations. When the “By” function replaces an Eq context by a binary predicate. unionBy. . deleteFirstsBy (the By variant of \\).
:: Integral a => [b] > a 17. THE “GENERIC” OPERATIONS 185 17. genericLength is a generalised version of length. genericDrop. For example. and 7 arguments. zipWith. The List library provides these same three operations for 4.7 The “generic” operations The preﬁx “generic” indicates an overloaded function that is a generalised version of a Prelude function. and zipWith3. 5. genericReplicate. unzip3. genericIndex (the generic version of !!).7. The “generic” operations are as follows: genericLength.8 Further “zip” operations The Prelude provides zip.17. 6. . zip3. genericTake. unzip. genericSplitAt.
words. length. zipWith7. takeWhile. intersectBy.9 Library List module List ( elemIndex. drop. isSuffixOf. zip3. filter p :: (a > Bool) > [a] > Maybe Int = listToMaybe . span. last. . iterate. scanl. genericIndex. (!!). scanr1. zipWith5. tails. any. cycle. elem. unzip4.i) <. nub. mapAccumR. filter. maximum. product. zip7. foldr1. LIST UTILITIES 17. []). deleteBy. maximumBy. partition. findIndices. isPrefixOf. concat. zipWith3. dropWhile. zipWith6.and what the Prelude exports .. . findIndex. take. repeat. transpose.]. unzip7. zip. group.. minimum. union. sort.[]((:). concatMap. deleteFirstsBy. genericSplitAt. scanr. mapAccumL. all. unlines. zip5. notElem. findIndices p :: (a > Bool) > [a] > [Int] = [ i  (x. zipWith. elemIndices. sum. insert.This is builtin syntax map. 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 . unwords. foldr. init. unzip5. unionBy. head. foldl. (++). or.. tail. intersperse. sortBy. (\\). delete. lines. insertBy. intersect. reverse. scanl1. groupBy. null.186 CHAPTER 17. p x ] :: Eq a => [a] > [a] = nubBy (==) .zip xs [0. unfoldr. genericLength. replicate.. zip6. zipWith4. lookup. genericReplicate. genericTake. splitAt. inits. and. genericDrop. find. foldl1. zip4. unzip6. minimumBy. nubBy. break. unzip.
[2.elements. transpose [[1.xss]) : transpose (xs : [t  (h:t) <.Note that [h  (h:t) <."ss".2]. e."i".[5]] . ."i".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) <.4]."pp". any (eq x) ys] :: = = = a > [a] > [a] [] [x] x : sep : intersperse sep xs ."i"] group :: Eq a => [a] > [[a]] group = groupBy (==) ."i".[3.group "Mississippi" == ["M"."ss".3].For example.transpose is lazy in both rows and columns.9.17.[]] = [[1.4. and works for nonrectangular ’matrices’ .g. 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 <. adjacent ..[a]) = (filter p xs.group splits its list argument into a list of lists of equal.xss]) partition partition p xs :: (a > Bool) > [a] > ([a].5]. filter (not . p) xs) .xs.
y ) = f s x (s’’.ys) = mapAccumL f s’ xs :: (a > b > (a. c)) > a > [b] > (a. c)) > a > [b] > (a..inits xs returns the ."ab". []) = (s’’. LIST UTILITIES :: (a > a > Bool) > [a] > [[a]] = [] = (x:ys) : groupBy eq zs where (ys.e."abc"] :: [a] > [[a]] = [[]] = [[]] ++ map (x:) (inits xs) list of all final segments of xs. tails "abc" == tails tails [] tails xxs@(_:xs) CHAPTER 17. shortest first. "c".y ) = f s’ x (s’.188 groupBy groupBy eq [] groupBy eq (x:xs) . ["abc".b)) > b > [a] = case f b of Nothing > [] Just (a.g.zs) = span (eq x) xs list of initial segments of xs.y:ys) where (s’. [c]) = (s. ys) = mapAccumR f s xs :: (b > Maybe (a. []) = (s’’.tails xs returns the .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 . [c]) = (s. y:ys) where (s’’.e. longest first..""] :: [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. ["". inits "abc" == inits inits [] inits (x:xs) .g."a". "bc".
[]) = = = (x:xs’.genericDrop: negative argument" :: (Integral a) => a > [b] > ([b].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’.9. 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.genericSplitAt: negative argument" genericSplitAt (n1) xs .[b]) = ([].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.xs’’) :: (Integral a) => a > [b] > [b] = xs = [] = = genericDrop (n1) xs error "List.xs) = ([].17.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.xs’’) error "List.
b.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.b.) :: [a] > [b] > [c] > [d] > [e] > [f] > [g] > [(a.c.g)] = zipWith7 (.c.cs..genericIndex: negative argument" error "List.[].c.f.genericIndex: index too large" :: (Integral a) => a > b > [b] = genericTake n (repeat x) :: [a] > [b] > [c] > [d] > [(a.bs.d)] > ([a].....) :: [a] > [b] > [c] > [d] > [e] > [f] > [(a..b:bs.e...[b].[c].[].b.c. LIST UTILITIES :: (Integral a) => [b] > a > b = x = = = genericIndex xs (n1) error "List..e.c.c.d.b..[d]) = foldr (\(a.) :: [a] > [b] > [c] > [d] > [e] > [(a.e)] = zipWith5 (.b.d..b.d) ˜(as.) 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.d.d:ds)) ([].[]) zipWith7 zipWith6 .c:cs...d)] = zipWith4 (..f)] = zipWith6 (.ds) > (a:as.
[].[].[d].es.e:es)) ([].es) > (a:as.bs.[e].bs.[].d.ds.[]) 191 unzip6 unzip6 :: [(a.d.c:cs.es.g)] > ([a].b:bs.d.cs.c.cs.[].[]) :: [(a.[c].b.[b].d.e)] > ([a].9.e.b.[e]) = foldr (\(a.[].[f]) = foldr (\(a.[f].[b].[].[].f:fs.[c].[].e.[d].ds.e:es.[].bs.f.ds.d.c.[c].f.b:bs.[].e. LIBRARY LIST unzip5 unzip5 :: [(a.d:ds.[]) unzip7 unzip7 .c.g) ˜(as.g:gs)) ([].e:es.[].d:ds.b:bs.d.17.f:fs)) ([].[b].c:cs.c.cs.f)] > ([a].fs) > (a:as.[].c.e) ˜(as.b.[e].[g]) = foldr (\(a.e.c:cs.b.f) ˜(as.b.b.fs.d:ds.[d].gs) > (a:as.c.
LIST UTILITIES .192 CHAPTER 17.
listToMaybe. fromMaybe. catMaybes. 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.. 193 . isNothing.and what the Prelude exports Maybe(Nothing. Just). maybe ) where isJust.Chapter 18 Maybe Utilities module Maybe( isJust. fromJust... mapMaybe. . which would cause the expression to become monadic. as would happen if error were used. maybeToList. and without using IOError from the IO monad. Other operations on Maybe are provided as part of the monadic classes in the Prelude. an incorrect result is returned as Nothing. A correct result is encapsulated by wrapping it in Just.
. catMaybes. fromMaybe.ms ] :: (a > Maybe b) > [a] > [b] = catMaybes .194 CHAPTER 18. 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 . fromJust..1 Library Maybe module Maybe( isJust. map f . . isNothing.fromJust: Nothing" :: a > Maybe a > a = d = a :: Maybe a > [a] = [] = [a] :: [a] > Maybe a = Nothing = Just a :: [Maybe a] > [a] = [ m  Just m <. isJust :: Maybe a > a = a = error "Maybe. mapMaybe. maybeToList..and what the Prelude exports Maybe(Nothing. MAYBE UTILITIES 18. Just). listToMaybe.
isPrint. any 195 . with the next 128 entries comes the remainder of the Latin1 character set. For the purposes of Haskell. isLower. toUpper. isAlphaNum. isAlphaNum :: Char > Bool toUpper. readLitChar. isLatin1. isOctDigit.and what the Prelude exports Char. and other printable characters. isUpper. other alphabetic. isDigit. isPrint. This module offers only a limited view of the full Unicode character set.. isSpace. String ) where isAscii. isLatin1. isUpper. toLower. 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. intToDigit. isHexDigit. isAlpha. .Chapter 19 Character Utilities module Char ( isAscii. chr. ord.. the full set of Unicode character attributes is not accessible in this library. isControl. showLitChar.. isOctDigit. numeric digits. isSpace. isAlpha. lower case alphabetic. digitToInt. lexLitChar. The ﬁrst 128 entries of this character set are identical to the ASCII set. isDigit. Unicode characters may be divided into ﬁve general categories: nonprinting. isLower. isHexDigit. isControl.
and isHexDigit functions select only ASCII characters.. "Hello")] [(’\n’. and title). leaving any other character unchanged.. but recognises both upper and lowercase hexadecimal digits (i. For example: showLitChar ’\n’ s lexLitChar "\\nHello" readLitChar "\\nHello" = = = "\\n" ++ s [("\\n". but in addition converts the to the character that it encodes.’f’. The function readLitChar does the same. intToDigit fails unless its argument is in the range 0.’9’. 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. toLower converts a letter to the corresponding lowercase letter. The ord and chr functions are fromEnum and toEnum restricted to the type Char. The isSpace function recognizes only white characters in the Latin1 range. digitToInt operates fails unless its argument satisﬁes isHexDigit. ’0’. lower. intToDigit and digitToInt convert between a single digit Char and the corresponding Int. and generates lowercase hexadecimal digits. returning the sequence of characters that encode the character. The function showLitChar converts a character to a string using only printable characters.e. .196 CHAPTER 19. 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. using Haskell sourcelanguage escape conventions.’F’). ’a’. isOctDigit. For each sort of Unicode character. leaving any other character unchanged.. "Hello")] Function toUpper converts a letter to the corresponding uppercase letter. Similarly. ’A’. The function lexLitChar does the reverse. CHARACTER UTILITIES alphabetic character which is not lower case is treated as upper case (Unicode actually has three cases: upper.15..
fromEnum ’a’ + 10  c >= ’A’ && c <= ’F’ = fromEnum c . isLatin1. showLitChar.1 Library Char module Char ( isAscii.19. isPrint. isLatin1. LIBRARY CHAR 197 19. isControl. isUpper. chr.. isUpper. isAlpha. readHex) import UnicodePrims . digitToInt. readOct.Source of primitive Unicode functions. toLower... intToDigit..Only Latin1 spaces recognized isUpper isLower isAlpha c isDigit c isOctDigit c isHexDigit c isAlphaNum = = = = = = = primUnicodeIsUpper primUnicodeIsLower . isControl. isSpace. . isAlpha.fromEnum ’A’ + 10  otherwise = error "Char.Used for character name table. isOctDigit. isDigit.’z’ isUpper c  isLower c c >= ’0’ && c <= ’9’ c >= ’0’ && c <= ’7’ isDigit c  c >= ’A’ && c <= ’F’  c >= ’a’ && c <= ’f’ primUnicodeIsAlphaNum . toUpper. String ) where import Array .Charactertesting operations isAscii.’Z’ .’a’..and what the Prelude exports Char.1. isOctDigit. isSpace. isLower. isAlphaNum. lexDigits.’A’. 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" . isLower.fromEnum ’0’  c >= ’a’ && c <= ’f’ = fromEnum c . isPrint.digitToInt: not a digit" . isDigit. import Numeric (readDec. ord. isHexDigit. . readLitChar. isHexDigit. lexLitChar.Digit conversion operations digitToInt :: Char > Int digitToInt c  isDigit c = fromEnum c .
([].intToDigit: not a digit" .t) <.[match mne s]] of (pr:_) > [pr] [] > [] _ = [] :: (Eq a) => [a] > [a] > ([a]. s)] s@(d:_)  isDigit d = [(chr n. t)  (n.s)] (’t’:s) = [(’\t’.s’)  (c. t)  (n.s)] (’ˆ’:c:s)  c >= ’@’ && c <= ’_’ = [(chr (ord c .s)] readEsc readEsc readEsc readEsc readEsc readEsc readEsc readEsc readEsc readEsc readEsc readEsc readEsc readEsc readEsc readEsc :: ReadS Char (’a’:s) = [(’\a’.t) <.Text functions readLitChar :: ReadS Char readLitChar (’\\’:s) = readEsc s readLitChar (c:s) = [(c.readDec s] (’o’:s) = [(chr n.s)] (’n’:s) = [(’\n’.s)] (’\’’:s) = [(’\’’.s)] (’r’:s) = [(’\r’.s)] (’b’:s) = [(’\b’.table.s)] (’"’:s) = [(’"’.s’) <.ys) readEsc match match (x:xs) (y:ys)  x == y match xs ys .t) <.198 intToDigit :: Int > Char intToDigit i  i >= 0 && i <= 9 =  i >= 10 && i <= 15 =  otherwise = CHAPTER 19.s)] (’\\’:s) = [(’\\’.Casechanging operations toUpper :: Char > Char toUpper = primUnicodeToUpper toLower :: Char > Char toLower = primUnicodeToLower . mne) <.readHex s] s@(c:_)  isUpper c = let table = (’\DEL’.Character code functions ord :: Char > Int ord = fromEnum chr chr :: Int > Char = toEnum . t)  (n. CHARACTER UTILITIES toEnum (fromEnum ’0’ + i) toEnum (fromEnum ’a’ + i .s)] (’v’:s) = [(’\v’. "DEL") : assocs asciiTab in case [(c.s)] (’f’:s) = [(’\f’.[a]) = match xs ys = (xs.10) error "Char.readOct s] (’x’:s) = [(chr n.ord ’@’).
"LF".19. "SO". "BEL". "STX". "ENQ". "FF". "FS". "VT". cont where cont cont asciiTab = listArray (’\NUL’. "NAK". "DC4". "RS". "GS".c].s) = (c:t. 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 . ’ ’) ["NUL".Very crude approximation to \XYZ. "BS". lexEsc s@(c:_)  isUpper c = [span isCharName s] lexEsc _ = [] isCharName c = isUpper c  isDigit c prefix c (t. "SOH". "ETX". "SYN".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] . "DC2". "ETB".s)] [] . "SI". "CR". "US".1. "HT". "DLE". "SUB". "DC3". 199 lexLitChar :: ReadS String lexLitChar (’\\’:s) = map (prefix ’\\’) (lexEsc s) where lexEsc (c:s)  c ‘elem‘ "abfnrtv\\\"’" = [([c]. "ACK". "SP"] s@(c:_)  p c = "\\&" ++ s s = s "EOT". "DC1".s)] lexEsc (’ˆ’:c:s)  c >= ’@’ && c <= ’_’ = [([’ˆ’. "EM". "CAN". s) lexLitChar (c:s) lexLitChar "" = = [([c].s)] . LIBRARY CHAR showLitChar :: Char > ShowS showLitChar c  c > ’\DEL’ = showChar ’\\’ . "ESC".
200 CHAPTER 19. CHARACTER UTILITIES .
201 .
return.202 CHAPTER 20.. > 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) . msum.. mapM. ap. liftM5. sequence. zipWithM_. MONAD UTILITIES Chapter 20 Monad Utilities module Monad ( MonadPlus(mzero. mplus). sequence_.and what the Prelude exports Monad((>>=).c)) > [a] > m ([b]. (>>). liftM3. (=<<). foldM. mapAndUnzipM. unless. liftM2. ) 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. guard. . fail). filterM. mapM_. liftM. liftM4. when. zipWithM. join.. Functor(fmap).
20. for example: sum :: Num a => [a] > a msum :: MonadPlus m => [m a] > m a 20. Lists and the Maybe type are instances of MonadPlus.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. Thus. NAMING CONVENTIONS 203 The Monad library deﬁnes the MonadPlus class. 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.1. So. and provides some useful operations on monads.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. thus: instance MonadPlus Maybe where mzero = Nothing Nothing ‘mplus‘ ys = ys xs ‘mplus‘ ys = xs instance MonadPlus [] mzero = [] mplus = (++) where . 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 ()). 20.
The zipWithM function generalises zipWith to arbitrary monads. For example. and otherwise do nothing. the input list should be reversed. listFile :: String > IO () listFile nm = do cts <. The function arguments are scanned left to right. It is used to remove one level of monadic structure.. .. This could be an issue where (>>) and the “folded function” are not commutative.3] liftM2 (+) (Just 1) Nothing = Nothing In many situations. For example. projecting its bound argument into the outer level. For instance the following function displays a ﬁle.. putStr ": "..1. .2. putStrLn line) [1. f am xm If righttoleft evaluation is required. the liftM operations can be replaced by uses of ap. liftM2 (+) [0.] (lines cts) The foldM function is analogous to foldl. x2. Note that foldM works from lefttoright over the list arguments. xm ] == do a2 <.204 CHAPTER 20. The mapAndUnzipM function maps its ﬁrst argument over a list. preﬁxing each line with its line number. returning the result as a pair of lists.3 Functions The join function is the conventional monad join operator.f a1 x1 a3 <..2] = [0. MONAD UTILITIES 20. which promotes function application. This function is mainly used with complicated data structures or a statetransforming monad. except that its result is encapsulated in a monad. foldM f a1 [x1.1] [0.. The monadic lifting operators promote a function to a monad. The when and unless functions provide conditional execution of monadic expressions. when debug (putStr "Debugging\n") will output the string "Debugging\n" if the Boolean value debug is True.f a2 x2 .readFile nm zipWithM_ (\i line > do putStr (show i).
FUNCTIONS return f ‘ap‘ x1 ‘ap‘ ..3.. ‘ap‘ xn is equivalent to liftMn f x1 x2 .20.. xn 205 ..
filterM.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 = (++) . join. sequence. unless. when.. mplus). fail). MONAD UTILITIES 20. return.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. guard. mapM. unzip . liftM. ) where . ap. Functor(fmap). mapAndUnzipM. zipWithM. msum. liftM2. liftM3.206 CHAPTER 20. mapM_.. .c)) > [a] > m ([b]..The MonadPlus class definition class (Monad m) => MonadPlus m mzero :: m a mplus :: m a > m a > m a . zipWithM_.4 Library Monad module Monad ( MonadPlus(mzero. liftM5. liftM4. (=<<). (>>). [c]) mapAndUnzipM f xs = sequence (map f xs) >>= return . sequence_. foldM.
return (f a’) } :: (Monad m) => (a > b > c) > (m a > m b > m c) = \a b > do { a’ <. 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’ <. return (f a’ b’) } :: (Monad m) => (a > b > c > d) > (m a > m b > m c > m d) = \a b c > do { a’ <. c’ <. c’ <.p x.filterM p xs. 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 <.a. b’ <.b. 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’ <.4.c.a.c.b. b’ <. c’ <.a.d.a. b’ <. d’ <.b. return (f a’ b’ c’ d’ e’) } .20. e’ <.e.b.a. 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’ <.c. ys <.d. d’ <. b’ <.
208 CHAPTER 20. MONAD UTILITIES .
209 .
getChar. putChar. hFlush. hLookAhead. readLn ) where import Ix(Ix) data Handle = . catch.AppendMode. Ix. instance Show Handle where . Ord.. IOError. stdout. Ord. print.. readIO. hGetLine. instance Show HandlePosn where data IOMode data BufferMode = =  = ..SeekFromEnd).. BufferMode(NoBuffering. isAlreadyInUseError.WriteMode.. hPrint.RelativeSeek. hReady. try...210 CHAPTER 21. hSetPosn. instance Eq Handle where . isPermissionError. appendFile. ioeGetErrorString..and what the Prelude exports IO. Bounded. getLine. hClose. openFile. isIllegalOperation. Ord.LineBuffering. readFile. hGetChar. hIsEOF. hPutStr. hIsClosed. hPutChar. hGetPosn.implementationdependent . hIsReadable. Show) stdin. hSeek. bracket_. Show) AbsoluteSeek  RelativeSeek  SeekFromEnd deriving (Eq. Read. Show) NoBuffering  LineBuffering BlockBuffering (Maybe Int) deriving (Eq. hFileSize. isDoesNotExistError. Bounded. getContents.. interact. hWaitForInput. hGetBuffering.implementationdependent data SeekMode ReadMode  WriteMode  AppendMode  ReadWriteMode deriving (Eq. bracket. Ix. hSetBuffering. data HandlePosn = . isFullError. ioeGetHandle. userError. FilePath. Read. ioeGetFileName. isEOFError. hIsWritable. stderr..implementationdependent . Read. hIsOpen. putStrLn. INPUT/OUTPUT Chapter 21 Input/Output module IO ( Handle. isEOF. Enum. stdout..ReadWriteMode). ioError.implementationdependent . SeekMode(AbsoluteSeek. stdin. hIsSeekable. hGetContents. isAlreadyExistsError. writeFile. putStr. isUserError. IOMode(ReadMode. Enum. instance Eq HandlePosn where . HandlePosn. hPutStrLn. ..BlockBuffering). stderr :: Handle openFile hClose :: FilePath > IOMode > IO Handle :: Handle > IO () .
Some related operations on ﬁle systems .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. This library contain more advanced I/O features. Commonly used I/O functions such as print are part of the standard prelude and need not be explicitly imported.
for all other errors. In some cases. isIllegalOperation – the operation is not possible.1 I/O Errors Errors of type IOError are used by the I/O monad. This is similar to trycatchﬁnally in Java. the library provides functions to interrogate and construct values in IOError: isAlreadyExistsError – the operation failed because one of its arguments already exists. CHAPTER 21. isDoesNotExistError – the operation failed because one of its arguments does not exist. In this case it should return isIllegalOperation. and False otherwise. deallocate idiom in which the deallocation step must occur even in the case of an error during computation. compute. isEOFError – the operation failed because the end of ﬁle has been reached. and ioeGetErrorString which returns a string.212 are contained in the Directory library. which is already being used (for example. isFullError – the operation failed because the device is full. isPermissionError – the operation failed because the user does not have sufﬁcient operating system privilege to perform that operation. isAlreadyInUseError – the operation failed because one of its arguments is a singleuse resource. 4 ¦ ¢ 7 ¦ ¥ 4 ¦ ¢ 7 ¦ ¥ . INPUT/OUTPUT 21. Any computation which returns an IO result may fail with isIllegalOperation. which is True if its argument is the corresponding kind of error. All these functions return a Bool. and Nothing otherwise. Three additional functions are provided to obtain information about an error value. ioeGetFileName which returns Just if the error value refers to ﬁle . an implementation will not be able to distinguish between the possible error causes. The try function returns an error in a computation explicitly using the Either type. the string is implementationdependent. the string returned by ioeGetErrorString is the argument that was passed to fail. This is an abstract type. The bracket function captures a common allocate. Additional errors which could be raised by an implementation are listed after the corresponding operation. For “user” errors (those which are raised using fail). opening the same ﬁle twice for writing might give this error). isUserError – a programmerdeﬁned error value has been raised using fail. These are ioeGetHandle which returns Just if the error value refers to handle and Nothing otherwise.
represented by values of type Handle. any nondirectory ﬁle system object is termed a ﬁle. Haskell deﬁnes operations to read and write characters from and to ﬁles. Handles are in the Show and Eq classes. For simplicity. whether the object is seekable. a buffer (whose length may be zero). ordered ﬁles. or enabled on a line or block basis. These handles are initially open. though an implementation cannot reuse its storage while references remain to it. Once it is closed it can no longer be used for either input or output. although it could in fact be a communication channel. Files can be opened. A handle is open when ﬁrst allocated. likewise. or any other object recognised by the operating system. whether buffering is disabled.1 Standard Handles Three handles are allocated during program initialisation.2. yielding a handle which can then be used to operate on the contents of that ﬁle. 21.2 Files and Handles Haskell interfaces to the external world through an abstract ﬁle system. no attempt is made to compare the internal state of different handles for equality. whether it is open. A handle is equal according to == only to itself. Physical ﬁles are persistent. File and directory names are values of type String. . In some implementations. The ﬁrst two (stdin and stdout) manage input or output from the Haskell program’s standard input or output channel respectively. A handle has at least the following properties: whether it manages input or output or both. A handle is readable if it manages only input or both input and output. and normally reside on disk.2.21. Each value of this type is a handle: a record used by the Haskell runtime system to manage I/O with ﬁle system objects. directories may themselves be ﬁle system objects and could be entries in other directories. This ﬁle system is a collection of named ﬁle system objects. whose precise meaning is operating system dependent. closed or semiclosed. The third (stderr) manages output to the standard error channel. The string produced by showing a handle is system dependent. it should include enough information to identify the handle for debugging. Most handles will also have a current I/O position indicating where the next input or output operation will occur. FILES AND HANDLES 213 21. which may be organised in directories (see Directory). it is writable if it manages only output or both input and output.
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 ¦
¥
.
7 ¦ 7 ¦ 7 ¦ 7 ¦ ¥ 7 ¦ ¥ 7 ¦ 7 ¦ ¥ without removing it 7 ¦ § . the ﬁle or channel managed by given by the shows function to Error reporting: the hPutChar.9.21.10 Examples Here are some simple examples to illustrate Haskell I/O. 21. blocking until a character is available. ¥ Error reporting: the hLookAhead computation may fail with: isEOFError if the end of ﬁle has been reached. Error reporting: the hGetContents computation may fail with: isEOFError if the end of ﬁle has been reached.10. hPutStr and hPrint computations may fail with: isFullError if the device is full.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 .1 Summing Two Numbers This program reads and sums two Integers.10.9. 21. 21. Char 7 ¦ 7 ¦ ¥ . ¥ © © ¥ Computation hPutStr ¥ writes the string to the ﬁle or channel managed by § . which is made semiclosed.9. or isPermissionError if another system resource limit would be exceeded. 21.3 Reading Ahead ¥ Computation hLookAhead returns the next character from handle from the input buffer.5 Text Output ¥ writes the character to the ﬁle or channel managed by Computation hPutChar acters may be buffered if buffering is enabled for . Computation hPrint writes the string representation of and appends a newline. EXAMPLES 219 21.
This program will not allow a ﬁle to be copied to itself.x2 readNum = readLn 21.Providing a type signature avoids reliance on . with all lowercase characters translated to uppercase.readNum putStr ("Their sum is " ++ show (x1+x2) ++ "\n") where readNum :: IO Integer .10.readNum putStr "Enter another integer: " x2 <.hGetChar h1 hPutChar h2 (toUpper c) copyFile h1 h2 An equivalent but much shorter version.the defaulting rule to fix the type of x1.2 Copying Files A simple program to create a copy of a ﬁle.openFile f2 WriteMode copyFile h1 h2 hClose h1 hClose h2 copyFile h1 h2 = do eof <. Note that exactly two arguments must be supplied to the program.openFile f1 ReadMode h2 <. INPUT/OUTPUT main = do hSetBuffering stdout NoBuffering putStr "Enter an integer: " x1 <. import IO import System import Char( toUpper ) main = do [f1.f2] <.hIsEOF h1 if eof then return () else do c <. This version uses characterlevel I/O. using string I/O is: .220 import IO CHAPTER 21.getArgs h1 <.
readFile f1 writeFile f2 (map toUpper s) 221 21.11 Library IO module IO {.actions that IO exports.try (m x) after x case rs of Right r > return r Left e > ioError e .f2] <. LIBRARY IO import System import Char( toUpper ) main = do [f1.Just provide an implementation of the systemindependent .before rs <.21.export list omitted } where .before rs <. Left) bracket :: IO a > (a > IO b) > (a > IO c) > IO c bracket before after m = do x <.f return (Right r)) (return .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 <.try m after x case rs of Right r > return r Left e > ioError e .getArgs s <. try try f :: IO a > IO (Either IOError a) = catch (do r <.11.
222 CHAPTER 21. INPUT/OUTPUT .
223 .
setPermissions. DIRECTORY FUNCTIONS Chapter 22 Directory Functions module Directory ( Permissions( Permissions.. . setCurrentDirectory. createDirectory... searchable :: Bool } instance instance instance instance Eq Ord Read Show Permissions Permissions Permissions Permissions where where where where . renameDirectory. writable. executable. getPermissions. searchable ). > > > > > 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 .. removeFile.224 CHAPTER 22. doesDirectoryExist. writable. executable. renameFile. getDirectoryContents. removeDirectory. readable.. ... doesFileExist. getCurrentDirectory. .. getModificationTime ) where import Time ( ClockTime ) data Permissions = Permissions { readable.
. 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. or as £ ¦ ¦ ¦ 7 7 7 2 2 £ £ ¦ ¦ £ £ ¦ ¦ £ ¦ . ¦ ¦ 7 2 £ ¦ ¤§ ¦ ¤§ 7 ¦ 2 ¦ which is initially empty. removes the directory entry for an existing ﬁle . removal of the root directory). considered to form part of the directory contents. Entries in subdirectories are not. “. Some entries may be hidden. The createDirectory computation may fail with: isPermissionError if the user is not permitted to create the directory. The implementation Computation removeDirectory may specify additional constraints which must be satisﬁed before a directory can be removed (for instance. it is atomically replaced by the object. it may also be possible to have paths which are relative to the current directory. it is atomically replaced by the directory. Note that. Although there may be ﬁle system objects other than ﬁles and directories. or isDoesNotExistError if the new directory’s parent does not exist. however. Computation renameFile changes the name of an existing ﬁle system object from to . but the constraints must be documented. where is Computation removeFile not itself a directory. A conformant implementation need not support renaming directories in all situations (for instance. Computation renameDirectory changes the name of an existing directory from to . or across different physical devices). All such objects should therefore be treated as if they are ﬁles.” or “. If the object already exists. A conformant implementation need not support directory removal in all situations (for instance. this library does not distinguish between physical ﬁles and other nondirectory objects. Each ﬁle system object is referenced by a path. directory etc. There is normally at least one absolute path to each ﬁle system object.). the directory has to be empty. A directory contains a series of entries. or isDoesNotExistError if the ﬁle/directory does not exist. In some operating systems. If the directory already exists. if an implementation does not support an operation it should raise an isIllegalOperation. in particular. as described in Section 21. it is removed as if by removeDirectory. inaccessible. The implementation may specify additional constraints which must be satisﬁed before a ﬁle can be removed (for instance. isAlreadyExistsError if the directory already exists. renaming to an existing directory. It is not legal for an implementation to partially remove a directory unless the entire directory is removed. The removeDirectory and removeFile computations may fail with: isPermissionError if the user is not permitted to remove the ﬁle/directory.225 These functions operate on directories in the ﬁle system. the ﬁle may not be in use by other processes). each of which is a named reference to a ﬁle system object (ﬁle. all other permissible errors are described below. but all such entries are considered to form part of the directory contents.1. Error reporting. Any Directory operation could raise an isIllegalOperation. Error reporting. If the directory is neither the directory nor an alias of the directory. or may not be in use by other processes). or have some administrative function (for instance. removes an existing directory .” under POSIX).
getPermissions and setPermissions get and set these permissions. Error reporting. The operation doesFileExist returns True if the argument ﬁle exists and is not a directory. Error reporting. the executable ﬁeld will be False. The renameDirectory and renameFile computations may fail with: isPermissionError if the user is not permitted to rename the ﬁle/directory. A conformant implementation need not support renaming ﬁles in all situations (for instance. ¦ ¤§ ¤§ ¤§ ¤§ ¦ ¦ Computation getDirectoryContents returned list is named relative to the directory returns a list of all entries in . or isDoesNotExistError if the directory does not exist. If the operating system has a notion of current directories. but not all permissions. setCurrentDirectory the current directory of the calling process to . Error reporting. respectively. and False otherwise. For directories. The getModificationTime operation returns the clock time at which the ﬁle/directory was last modiﬁed. if permission has been given to use them as part of a path. DIRECTORY FUNCTIONS may refer to an existing directory. Each entry in the changes . and getModificationTime may fail with: isPermissionError if the user is not permitted to access the appropriate information. Note that directories may be searchable without being readable. but the constraints must be documented. or isDoesNotExistError if the ﬁle/directory ¤§ If the operating system has a notion of current directories. a construct on the following lines must be used. or isDoesNotExistError if the directory does not exist. get(set)Permissions. setCurrentDirectory may fail with: isPermissionError if the user is not permitted to change directory to that speciﬁed. not as an absolute path. and for ﬁles the searchable ﬁeld will be False. The getDirectoryContents and getCurrentDirectory computations may fail with: isPermissionError if the user is not permitted to access the directory.226 CHAPTER 22. getCurrentDirectory returns an absolute path to the current directory of the calling process. but not to examine the directory contents. ¦ ¦ . Note that to change some. doesFile(Directory)Exist. or isDoesNotExistError if the ﬁle/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 False otherwise. renaming across different physical devices). makeReadable f = do p <. The Permissions type is used to record whether certain operations are permissible on a ﬁle/directory. or if either argument to renameFile is a directory.
. 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. or isDoesNotExistError if the ﬁle/directory does not exist.227 does not exist.
228 CHAPTER 22. DIRECTORY FUNCTIONS .
getProgName. the isDoesNotExistError exception is raised. getArgs. system. Note that. Computation getArgs returns a list of the program’s command line arguments (not including the program name). exitFailure ) where data ExitCode = ExitSuccess  ExitFailure Int deriving (Eq. The exact interpretation of is operatingsystem dependent. exitWith. if an implementation does not support an operation it must raise an isIllegalOperation.1. Any System operation could raise an isIllegalOperation.ExitFailure). ExitSuccess indicates successful termination. Computation getEnv returns the value of the environment variable . in particular. 229 ¤ ¢ ¦ ¦ 2 2 ¤ ¢ ¦ 2 ¤ ¢ ¦ 2 . Computation getProgName returns the name of the program as it was invoked. 0 on a POSIXcompliant system). and ExitFailure indicates program failure with value .Chapter 23 System Functions module System ( ExitCode(ExitSuccess. If variable is undeﬁned. getEnv. 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. Read. In particular. all other permissible errors are described below. as described in Section 21. The ExitCode type deﬁnes the exit codes that a program can return. some values of may be prohibited (for instance. Ord.
Otherwise. then it is treated identically to the computation exitFailure. The caller may interpret the return code as it wishes. The value exitFailure is equal to exitWith (ExitFailure where is implementationdependent. it is treated identically to the computation ( >> exitWith ExitSuccess) ‘catch‘ \ _ > exitFailure 7 ¢ § 0 § § S ¢ ¦ 2 ¦ 2 4 Computation system the command . and ExitFailure to mean that the program encountered a problem from which it ). if any program terminates without calling exitWith explicitly. but the program should return ExitSuccess to mean normal completion.230 CHAPTER 23. any open or semiclosed handles are ﬁrst closed. If a program terminates as a result of calling error or because its value is otherwise determined to be . exitWith bypasses the error handling in the I/O monad and cannot be intercepted by catch. could not recover. ¦ returns the exit code produced when the operating system processes 4 7 ¢ § 0 § § S ¢ ¡ ¡ . SYSTEM FUNCTIONS ¦ ¦ Computation exitWith terminates the program. returning to the program’s caller. Before the program terminates.
231 .
CalendarTime(CalendarTime. Read. Read. Bool data CalendarTime = CalendarTime { ctYear ctMonth ctDay.. Bounded.Thursday. tdMin.August.Friday. Ord. toUTCTime. tdMin.May. ctHour..December). Read. Ix. diffClockTimes. ctMin. ctSec. tdMonth. Month(January. Integer.Tuesday. ctSec ctPicosec ctWDay ctYDay ctTZName ctTZ ctIsDST } deriving (Eq. .Implementationdependent data Month = January  February  March  April  May  June  July  August  September  October  November  December deriving (Eq.April. Show) . toCalendarTime. tdDay. tdDay. Show) :: :: :: :: :: :: :: :: :: Int. ctYDay. ctHour. DATES AND TIMES Chapter 24 Dates and Times module Time ( ClockTime. ctIsDST). tdPicosec :: Integer } deriving (Eq. Ord. calendarTimeToString.June.March. getClockTime. Day. instance Ord ClockTime where . addToClockTime. Enum. String.Saturday). ctTZName. ctWDay. ctYear. ctDay. Show) data Day = Sunday  Monday  Tuesday  Wednesday  Thursday  Friday  Saturday deriving (Eq. Enum.September. instance Eq ClockTime where .Monday. Ord. ctTZ.232 CHAPTER 24. Show) data TimeDiff = TimeDiff { tdYear. tdSec. TimeDiff(TimeDiff. Day(Sunday. tdYear. Read. Int. July. Ix.... ctPicosec. Bounded. Int.Wednesday. Ord.October.November. ctMonth. ctMin. tdHour.February. tdPicosec). Int.. tdSec :: Int. tdHour. formatCalendarTime ) where import Ix(Ix) data ClockTime = . tdMonth. Month. toClockTime.
The numeric ﬁelds have the following ranges. Clock times may be compared directly or converted to a calendar time CalendarTime for I/O or other manipulations. The ﬁeld is True if Daylight Savings Time would be in effect. ClockTime is an abstract type. CalendarTime is a userreadable and manipulable representation of the internal ClockTime type. The expression addToClockTime adds a time difference and a clock time to yield a new clock time. The TimeDiff type records the difference between two clock times in a userreadable way. § § © 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 ¡ § . 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.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. including timezone information. used for the system’s internal clock time. Because of this dependence on the local environment. and False otherwise. It follows RFC 1129 in its use of Coordinated Universal Time (UTC).233 . modiﬁed by the timezone and daylight savings time settings in force at the time of conversion. Function toCalendarTime converts to a local time. The returns difference may be either positive or negative. The expression diffClockTimes the difference between two clock times and as a TimeDiff. toCalendarTime is in the IO monad. Function getClockTime returns the current time in its internal representation.
April.Friday. Bounded. tdSec.Thursday. toClockTime converts into the corresponding internal ClockTime ignoring the contents of the . Enum.Wednesday.. getClockTime. Ord..May. tdMin. ctPicosec. ctDay. tdDay. tdHour. ctMonth.defaultTimeLocale) import Char ( intToDigit ) data ClockTime = . tdPicosec).234 § CHAPTER 24. t © S§ 24. Show) data Day = Sunday  Monday  Tuesday  Wednesday  Thursday  Friday  Saturday deriving (Eq.February. DATES AND TIMES Function toUTCTime converts into a CalendarTime in standard UTC format. diffClockTimes. tdYear. . ctTZ. ctHour. ctMin. instance Ord ClockTime where . and ﬁelds.. Day(Sunday. ctYear.September.March. Show) ¢ £ 4 ¢ E ¡ 7 § § ¢ G § 7 ¢ ( § .Tuesday.Implementationdependent data Month = January  February  March  April  May  June  July  August  September  October  November  December deriving (Eq. CalendarTime(CalendarTime. addToClockTime. Month(January.August. toClockTime. Ix.). Bounded. ctWDay. Read. July. calendarTimeToString.December). formatCalendarTime ) where import Ix(Ix) import Locale(TimeLocale(. ctTZName. Ord. . TimeDiff(TimeDiff.Monday.. instance Eq ClockTime where .June. ctYDay.1 Library Time module Time ( ClockTime.November. . tdMonth. toCalendarTime.October.. toUTCTime. Read.. Enum. Ix. ctIsDST). Function calendarTimeToString formats calendar times using local conventions and a formatting string. ctSec.Saturday)..
. ctMin. Ord.. Int. Int. Day. tdMin. .Implementationdependent :: CalendarTime > ClockTime = .Implementationdependent > ClockTime > TimeDiff ..24. . :: ClockTime = .. Read. Integer. tdHour.... Int. String.Implementationdependent :: TimeDiff = . LIBRARY TIME data CalendarTime = CalendarTime { ctYear ctMonth ctDay. tdDay. ctHour. Bool data TimeDiff = TimeDiff { tdYear.. tdMonth. Show) 235 :: :: :: :: :: :: :: :: :: Int.Implementationdependent > CalendarTime .Implementationdependent > IO CalendarTime . Read. Month. :: ClockTime = . tdPicosec :: Integer } deriving (Eq. Ord.Implementationdependent :: CalendarTime > String = formatCalendarTime defaultTimeLocale "%c" .1.. ctSec ctPicosec ctWDay ctYDay ctTZName ctTZ ctIsDST } deriving (Eq.. tdSec :: Int... :: ClockTime = . > ClockTime > ClockTime . Show) getClockTime getClockTime addToClockTime addToClockTime td ct diffClockTimes diffClockTimes ct1 ct2 toCalendarTime toCalendarTime ct toUTCTime toUTCTime ct toClockTime toClockTime cal calendarTimeToString calendarTimeToString :: IO ClockTime = .
1 else 6) ‘divMod‘ 7 in show2 (if days >= 4 then .if fromEnum wday > 0 then fromEnum wday .fromEnum wday) ‘div‘ 7) show (let n = fromEnum wday in if n == 0 then 7 else n) decode ’V’ = let (week. 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 .. days) = (yday + 7 ..236 CHAPTER 24. .Implementationdependent show2 ((yday + 7 .
LIBRARY TIME week+1 else if week == 0 then 53 else week) decode ’W’ = show2 ((yday + 7 .24. show3 :: Int > String show2 x = [intToDigit (x ‘quot‘ 10). show2’.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. intToDigit (x ‘rem‘ 10)] show2’ x = if x < 10 then [ ’ ’.if fromEnum wday > 0 then fromEnum wday .1. intToDigit x] else show2 x show3 x = intToDigit (x ‘quot‘ 100) : show2 (x ‘rem‘ 100) 237 .
238 CHAPTER 24. DATES AND TIMES .
String). dateFmt. it supports only time and date information as used by calendarTimeToString from the Time library. String)]. months :: [(String. At present. timeFmt..).Chapter 25 Locale module Locale(TimeLocale(. Ord. dateTimeFmt. time12Fmt :: String } deriving (Eq. 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. String)]. 239 . amPm :: (String. defaultTimeLocale) where data TimeLocale = TimeLocale { wDays :: [(String.
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
g) split :: g > (g. but very little work has been done on statistically robust implementations of split ([1. g) .1. 27.Int) next :: g > (Int. then . by starting with a speciﬁed initial random number generator. This is very useful in functional programs (for example. . The next operation returns an Int that is uniformly distributed in the range returned by genRange (including both end points).4] are the only examples we know of). and a new generator. For example.maxBound) The genRange operation yields the range of values returned by the generator. The library makes it possible to generate repeatable results. when passing a random number generator down to recursive calls). class RandomGen g where genRange :: g > (Int. The library is split into two layers: A core random number generator provides a supply of bits. – genRange – If genRange .1 The RandomGen class. 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. or to get different results on each run by using the systeminitialised generator. or by supplying a seed from some other source. It is required that: The second condition ensures that genRange cannot examine its argument. ¦ ¡ ¡ . AND THE STDGEN GENERATOR 245 The Random library deals with the common task of pseudorandom number generation.Default method genRange g = (minBound.27. without being concerned that the generator returned by (say) next might have a different range to the generator passed to next. The class RandomGen provides a common interface to such generators. That in turn allows an implementation to make a single call to genRange to establish a generator’s range. the Float instance of Random allows one to generate random values of type Float. The split operation allows one to obtain two independent random number generators. THE RANDOMGEN CLASS. The class Random provides a way to extract particular values from a random number generator.
It is required that read (show g) == g. instance Read StdGen where .. instance Show StdGen where . then g1 and g2 should be independent. distinct arguments should be likely to produce distinct generators. Implementations of the above form do not meet the speciﬁcation. split returns g itself and a new generator derived from g. In general.Abstract instance RandomGen StdGen where . The Show/Read instances of StdGen provide a primitive way to save the state of a random number generator.. Again. but in fact they are both equal to variantOf g.3]. Different argument strings are likely to result in different results.. the abstract data type StdGen: data StdGen = .246 CHAPTER 27. RANDOM NUMBERS The Random library provides one instance of RandomGen. The result of repeatedly using next should be at least as statistically robust as the “Minimal Standard Random Number Generator” described by [2.. It guarantees to consume only a ﬁnite portion of the string. mkStdGen :: Int > StdGen The StgGen instance of RandomGen has a genRange of at least 30 bits. variantOf g) Here. the read instance of StdGen has the following properties: It guarantees to succeed on any string. In addition. . split g = (g.. . Implementation warning. of course.. The function mkStdGen provides an alternative way of producing an initial generator. by mapping an Int into a generator... 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). all we require is that split deliver generators that are (a) not identical and (b) independently robust in the sense just given. Until more is known about implementations of split.. A superﬁcially attractive implementation of split is instance RandomGen MyGen where .. Programmers may. 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.
and do not return a new generator... 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 . random does the same as randomR.. but they may be.... together with a new generator. the range is normally the semiclosed interval ¦ ¨ § ¨¥ 2 7 § ¨¥ £ § ¨¥ 2 7 2 7 § ¨¥ 2 7 .. randomRs and randoms. . . . . ...27.g’) = random g randomRs = .... – For fractional types.. the Random class allows the programmer to extract random values of a variety of types: class Random a where randomR :: RandomGen g => (a. the range is normally the whole type.. – For bounded types (instances of Bounded. – For Integer. such as Char). produce an inﬁnite list of random values.a) > IO a randomIO :: IO a .2.similar.. It is unspeciﬁed what happens if . but does not take a range. the range is (arbitrarily) the range of Int. .Default methods randoms g = x : randoms g’ where (x. a) > g > [a] randoms :: RandomGen g => g > [a] randomRIO :: (a. and returns a random value uniformly distributed in the closed interval . depending on the implementation and the interval. randomR takes a range and a random number generator . a) > g > (a.2 The Random class With a source of random number supply in hand. g) random :: RandomGen g => g > (a.. The plural versions. g) randomRs :: RandomGen g => (a. For continuous types there is no requirement that the values and are ever produced. THE RANDOM CLASS 247 27.
3 The global random number generator There is a single. and updates the global generator with the new generator returned by the function. pp8788. Oct 1988. “Random number generators .ac.mat. global random number generator of type StdGen. or Linux’s kernel random number generator. . pp8289. newStdGen applies split to the current global random generator. pp11921201. “Distributed random number generation”. getStdRandom uses the supplied function to get a value from the current global random generator.3). 2(2):203212. use the global random number generator (see Section 27. To get deterministic behaviour. “Two fast implementations of the minimal standard random number generator”. July 1998. randomRIO and randomIO. for example. Journal of Functional Programming. respectively. Comm ACM 31(10). 33(1). April 1992.6)) References [1] FW Burton and RL Page. The Web site http://random. RANDOM NUMBERS The IO versions. and returns the other. It is initialised automatically in some systemdependent fashion. by using the time of day. For example. StdGen)) > IO a getStdGen and setStdGen get and set the global random number generator.at/ is a great source of information. rollDice gets a random integer between 1 and 6: rollDice :: IO Int rollDice = getStdRandom (randomR (1. updates it with one of the results. and KW Miller. [3] DG Carta. 27. implicit. ACM SIGSIM Simulation Digest 28(1). Jan 1990. “Don’t trust parallel Monte Carlo”. use setStdGen. Comm ACM. [4] P Hellekalek. [2] SK Park.good ones are hard to ﬁnd”.sbg. held in some global variable maintained by the IO monad. setStdGen getStdGen newStdGen getStdRandom :: :: :: :: StdGen > IO () IO StdGen IO StdGen (StdGen > (a.248 CHAPTER 27.
146:29–60. [7] Mark P. Fax´ n A static semantics for Haskell Journal of Functional Programming.. [6] P. Jones.B. [4] KF. December 1969. Yale University.Bibliography [1] J. Haskell Workshop. Can programming be liberated from the von Neumann style? A functional style and its algebra of programs. 5(1). Version 3. and J. The Implementation of Functional Programming Languages. The Unicode Standard. August 1978. Englewood Cliffs. Co. January 1995. [11] Unicode Consortium. January 1989. Transactions of the American Mathematical Society. CACM. In APL ’81 Conference Proceedings. PrenticeHall International.. Amsterdam. [12] P. [3] L. A system of constructor classes: overloading and implicit higherorder polymorphism. [9] P. Feys. 2000. Jones.M. N. Blott. Principal values and branch cuts in complex APL. 249 . Texas. Paris. Principal type schemes for functional programs. MA. Hindley. Milner. 2002. Curry and R. September 1981. [10] S. Peyton Jones. A gentle introduction to Haskell. pages 207–212. Journal of Functional Programming. Hudak. In Proceedings of the 9th ACM Symposium on Principles of Programming Languages. Reading. San Francisco.R. J. Addison Wesley. Penﬁeld. Backus. The principal type scheme of an object in combinatory logic. May 1996. [8] Mark P. Peterson. e [5] J. Fasel. Albuquerque. Jr. Typing Haskell in Haskell. [2] H. pages 248–256. October 1999. 1987. In Proceedings of the 16th ACM Symposium on Principles of Programming Languages. NorthHolland Pub. Damas and R. Austin. 21(8):613–641.L. How to make ad hoc polymorphism less ad hoc.0. January 1982. Combinatory Logic. 1958. Wadler and S. pages 60–76. New Jersey. Technical Report YALEU/DCS/RR901.
250 BIBLIOGRAPHY .
see operator application approxRational. 104. 80 :+. 88. 92. 126 AppendMode. 55. 55. 116 $. 20–23. 106 //. 66 abs. 55. 9. 55. 91. 55. 110 (. 62 and. 174. 110 $!. 84. 82. see also + pattern ++.. 142 <=. 104. 30 <. 84. 16. 104. 45. 91. 9. 92. 139 algebraic datatype. 109 ˆˆ. 119 ANY. 55. 173. 12 \b. 104. 175. 233. 55. 235 aexp. 174. 109 ==. 12 \n. 80 (). 12 \f. 173. 104. 177 acos.Index font. 84. 91. 142 >. 104. 104. 119 ANYseq. 44. 12 \r. 90. 151. 12 \t. 177 !!. 90. 153 &&. 55. 76 accum. 91. 55. 81. 43. Code Index entries that refer to nonterminals in the Haskell syntax are shown in an entities are shown in typewriter font. 55. see wildcard pattern . 55. 90. 81. 55. 141 all. 109 _. 106 addToClockTime. 142 >=. !. 206 apat. 104. 25. 105. Ordinary index entries are shown in a roman font. 104. 88. 115 . 109 >>=. 55. 142 =<<. 9. 153 251 § 7 3¢ §§ ¢ ¦ . 177 accumArray. see lambda abstraction \&. 84. 97. 175–177 /=. 106 +. 105. see also negation . 55. 187 \.). 105 **. 182 \a. 12 . 104. 104. 180. 19 function. 104. 139 ambiguous type. 129 any. see trivial type and unit expression *. 91. 104. 91. 17. 110 %. 80 (. 110 ˜. 55. 106 acosh. 202. 25. 55. 140 appendFile. 92. 115. see aspattern [] (nil). 81. 91. 55. 55. 155. 55. 55. 12 \\. 230 ˆ. 176. 90. 91. 67. 186. 93. 82. 92. 104. 79. 173. 104. 105 AbsoluteSeek. 156 ::. 104. 173. 119 alt. see irrefutable pattern abbreviated module. 139 alts. 151. 109 @. 88.. 31. 51. 104. 110 /. 104. 55.). 91. 97. 91. 142 >>. 214 application. 80 \\. 104. 217 abstract datatype. 79. see function application operator. 104. 129 any. 104. 55. 129 ap. 12 \v. 97. 142 :.
211. 93 comment. 80 Array (datatype). 17. 106 atan2. 11. 41. 91. 33 ascDigit. 110 Char (module). 74 cname. 114 atan. 115 conditional expression. 210 CalendarTime (datatype). 161. 12. 108 atanh. 195. 130 chr. 155. 42 class method. 110 boolean. 137 cdecls. see ASCII character set transparent. 79 literal syntax. 107 changing the directory. 177 asTypeOf. 234 char. 9 nested. 98. 235 calendarTimeToString. 91. 156 con. 49 clock time. 38. 9. 91. 129 asin. 155. 137 BufferMode (datatype). 9. 161. 41 class declaration. 177 bracket. 31. 95 binding. 91. 129 ascSymbol. 130 coercion. 130 character. 129 closing a ﬁle. 235 case expression. 104. 89. 9. 47 class. 140 concat. 9. 93. 176. 69. 173. 106 asinh. 194 cdecl. 105 derived instance. 130 ASCII character set. 10. 111 bounds. see transparent character set charesc. 198 cis. 136 Bool (datatype). 47. 48. 173. 7 ascLarge. see simple pattern binding body. 174. 12.252 arithmetic operator. 12. 140 . 38. 79. 173. 156 conop. 47. 137 ceiling. 156 class. 211. 176 array. 12 character set ASCII. 9 comment. 106 atype. 9. 115 concatMap. 174. 21 conid. 174 Array (module). 106 assocs. 125. 136 cntrl. 195. 221 break. 129 ascii. 197. 47. 93. 197 array. 79. 137 basic input/output. 92. 66. see pattern binding simple pattern. 84. 173 accumulated. 23. 232. 130 conjugate. 25 INDEX catch. 17. 38. 232. 48 class environment. 129 compare. 9 endofline. 12. 221 bracket_. 79 Bounded (class). 177 aspattern (@). 18. 230 catMaybes. 174 derived. 226 Char (datatype). 193. 39. 215 closure. 121. 67 with an empty where part. 40. 38. see function binding pattern. 173. 142 Complex (module). 137 class assertion. 37 function. 129 ascSmall. 143 instance for Char. 51. 18. 233. 234 closecom. 40. 9. 92. 90 arithmetic sequence. 174. 155. 232 ClockTime (datatype). 118 btype.
117 dashes. 97 doDiv. 186 elems. 49 declaration group. 43 datatype. see recursive datatype renaming. 180. 138 constrs. 137 context reduction. 9. 137 declaration. 235 ctMin. 130 decl. 108 default class method. 174. 37 class. 235 ctIsDST. 38. 235 current directory. 43. 43. 187 deleteFirstsBy. 232. 91. 104. 81. 47 within a let expression. 232. 27. 137 decodeFloat. 58 derived instance. 180. see newtype declaration dateFmt. 130 context. 180. 225 denominator. 112 drop. 234 dclass. 195. 145 default declaration. 233. 187 deleteBy. 186 elemIndices. see abstract datatype algebraic. 177 encodeFloat. 90. 232. 182. 40 consym. 224 doesFileExist. 184. 239. 43 data declaration. 24 within an instance declaration. 225 deleting ﬁles. 56. 240 Day (datatype). 106 divMod. 119 elemIndex. 48. 118 dropWhile. see class declaration datatype. 180. 91. 224 Double (datatype). 93. 43 abstract. 50. 182. 93 CPU time. 41 context. 9. 214 ctDay. 239. see instance declaration within a class declaration. 106 cosh. see algebraic datatype declaration. 232. 114 Curry. 92. 58 decls. 41. 92.. 91. Haskell B. 26. 224. see default declaration 253 ﬁxity. see data declaration recursive. 241 cpuTimePrecision. see import declaration instance. 10. 115. 81. 239. 55. 38. 110 constr. 224 div. 213. 240 dateTimeFmt. 167 Either (datatype). 38 constructor expression. 240 delete. 51 defaultTimeLocale. 91. 232. 55. vii cycle. 235 ctHour. see ﬁxity declaration import. 163 doesDirectoryExist. 80. 43. 180. 51. 11. 81.INDEX const. 43. 59 cos. 226 curry. 151. 92. 197 directories. 118 e. 111 elem. 129 digitToInt. 108 . see data declaration default. 235 digit. 241 createDirectory. 93. see also instance declaration deriving. 187 deleting directories. 182. 225 creating a ﬁle. 153 dependency analysis. 106 do expression. 111 either. 138 diffClockTimes. 106 cosine. 173. 89. 129 data constructor. 224 Directory (module). 184. 241 CPUTime (module). 138 decimal. 138 constructor class. 141.
202. 180. 52 expt. 17 error. see type environment environment variables. 92. 29 ﬁelddecl. see case expression conditional. 167 fail. 125 filter. 81. 91. 108 floatRange. 163 f. 97. 19. 166 ¡ ¢ ¡ . 113 instance for Float. 93. 28 selection. 113 instance for Ratio. 114. 180. 139 exp. 86.254 end of ﬁle. 105 enumFromThen. 67. 104 error. 229 exitWith. 51. 105 environment class. 158 superclass of RealFloat. 91. 229 EQ. see unit expression expression typesignature. 112 ﬂoat. 154 superclass of Integral. 229 ExitSuccess. 89. 30. 136 v INDEX expression. 99. 137 ﬁxity declaration. 81 Eq (class). 130 even. 215 ﬁle system. see type expression unit. 139 exp. 213 FilePath (type synonym). 4. 27 update. 115 filterM. 88. 215 entity. 110 Float (datatype). 182. 82. 180. 92. 51. 51. 86. see class environment type. 92. 213 ﬁle buffering. 159. 49. 110 superclass of Num. 105 enumFromThenTo. 4. 54. see simple case expression type. 66 exports. 15 case. 105 enumFromTo. 142 instance for Array. 33 floatRadix. 16. 108 exponentiation. 24–26. see label. 105 superclass of Ord. 224 execution time. 18 ﬁxity. 229 . 108 floatToDigits. 16. 12 floatDigits. 67. see let expression simple case. 164 ﬁeld label. 92. 93. 104 derived instance. 91 export. 106 enumeration. 91. 162 expts. 139 fexp. 229 exitFailure. 43. 89. 105 derived instance. 212 False. 108 ﬂoating literal pattern. 109. 207 find. 186 findIndices. 98 executable. 48. 65 Enum (class). 19. 28. 136 export list. 186 ﬁxity. 108 Floating (class). 138 ﬁle. 229 ExitFailure. 17. 106 instance for Complex. 186 findIndex. 16. 111 instance for Double. 79 fbind. 106 exponent. 86. 230 escape. 54 flip. 92. see conditional expression let. 86. 30. 21. 93. 177 instance for Char. 108 exception handling. 86. 139 FFFormat (datatype). 44 construction. 170 enumFrom. 241 ExitCode (datatype). 38. 12. 89. 94. 142 instance for Char.
181. 109. 224 getPermissions. 190 genericLength. 129 255 . 245 get the contents of a ﬁle. 193. 129 fpat. 40. 244. 23. 229 getStdGen. 94. 12. 91. 111 instance for Maybe. 87. 140 fpats. 189 genRange. 184. 91. 235 getContents. 92. 92. 91. 54. 181. 18. 117 formal semantics. 56 function type. 233. 181. 109 instance for []. 31. vii Functor (class). 153 superclass of Floating. 4 hClose. 18. 41 functional language. 189 genericTake. 176 foldl. 241 getCurrentDirectory. 244. 3 formatCalendarTime. 162 fromRational. 87 funlhs. 215 head. 105 fromIntegral. 138 gdpat. 224 getProgName. 202. 210 HandlePosn (datatype). 55. 248 getStdRandom. 31. 96. 224. 181. 189 genericReplicate. 96. 23 genericDrop. 106 fst. 106 superclass of RealFrac. 56. 165 formfeed. 125 getCPUTime. 183. 137 generalization. 189 genericIndex. 34 guard. 140 Fractional (class). 106 instance for Complex. 108 gcon. 87. 236 formatRealFloat. 107 fromEnum. 80. 9. 224. 38. 117 foldr1. 81 gtycon. 206 Handle (datatype).INDEX floor. 162 fromRat’. 96. 40. 105 fromInteger. 18 gd. 125 getModificationTime. 3 Haskell kernel. 90. 244. 187 groupBy. 114 function. 159. 219 getArgs. 193. 125 getClockTime. 115 hexadecimal. 25. 225 getEnv. 91. 49. 181. 59 generalization preorder. 56. 129 group. 140 gconsym. 25. 25. 93. 213 Haskell. 111 functor. 113 instance for Array. 217 fmap. 116 foldl1. 18. 90. 229 getLine. 181. 139 gdrhs. 138 gendecl. 130 hexit. 157 instance for Ratio. 11. 190 genericSplitAt. 181. 188 GT. 229 getChar. 177 instance for IO. 181. 42 generator. 107 ﬂushing a ﬁle buffer. 92. 109 fromJust. vii. 130 gcd. 18. 194 fromRat. 86. 233. 202. 225 getDirectoryContents. 47. 81 function binding. 116 foldM. 137 guard. 207 foldr. 89. 9. 194 fromMaybe. 210. 138 gap. 210 handles. 9. 248 graphic.
211. 181. 218 hGetContents. 98. 49. 217 hiding. 211. 125 IOMode (datatype). 219 hPutChar. 195. 92. 211. 49. 116 inits. 211. 215 isEOFError. 212 id. see conditional expression imagPart. 218 hIsWritable. 211. 212 isAlreadyInUseError. 33. 138 instance declaration. 177 init. 197 isAlreadyExistsError. 24. 195.256 hFileSize. 171. 211. 211. 197 isDoesNotExistError. 215 isAscii. 219 hGetLine. 216. 112 integer. 69 impspec. 96. 198 IO. 34. 181. 184. 156 impdecl. 183. 183. 211. 211. 211 hReady. 211. 125. 219 hPutStrLn. 195. 211. 211. 195. 183. 211. 211. 181. 221 ioeGetErrorString. 182. 211. 89. see also derived instance importing and exporting. 218 hSeek. 163 Integral (class). 210 input/output examples. 195. 211. 211. 147 INDEX input/output. 137 idecls. 184. 49. 217 hSetBuffering. 81. 136 impdecls. 211. 197 isIllegalOperation. 211. 211. 92. 214. 197 isDigit. 173. 50. 197 isControl. 211. 81. 210 IO (datatype). 212 isHexDigit. 216 hSetPosn. 126 intersect. 197 isAlphaNum. 38. 110 idecl. 69. 70 HindleyMilner type system. 189 inst. 217 hWaitForInput. 217 hGetBuffering. 172 insert. 218 hIsReadable. 211. 155. 136 index. 49 Int (datatype). 4. 187 intersperse. 218 hIsEOF. 188 inlining. 211. 71 with an empty where part. 136 import. 112 Integer (datatype). 214 irrefutable pattern. 81. 38. 111 IO (module). 219 inRange. 218 hGetPosn. 194 . 212 ioeGetFileName. 211. 12 integer literal pattern. 219 hPrint. 188 insertBy. 69. 215 hFlush. 212 ioeGetHandle. 91. 210 I/O errors. 195. 215 isEOF. 181. 218 hIsSeekable. 136 import declaration. 49. 187 intToDigit. 174. 215 hIsOpen. 211. 211. 212. 218 hLookAhead. 69. 33 integerLogBase. 57 isAlpha. 106 interact. 218 I/O. 137 identiﬁer. 193. 89. 38. 181. 169. 172 indices. 211. 187 intersectBy. 210. 211. 211. 212 ioError. 217 hGetChar. 181. 211. 58 hIsClosed. 195. 9 ifthenelse expression. 211. 212. 66. 212 IOError (datatype). 210. 169. 219 hPutStr. 211. 171. 212 isJust. 212 isFullError.
31. 13. 122 lexDigits. 31. 169. 19 large. 81 kind. 91. 202. 183. 206 mapM. 171. 106 lookahead. 180. 168 lexeme. 89. 195. 65 making directories. 174. 197 isNothing. 127 maximum. 194 isOctDigit. 50. 188 isUpper. 80 list type. 170 instance for Char. 207 liftM5. 91. 189 Maybe (datatype). 117 Ix (class). 88. 155. 172 instance for Int. 26 in list comprehensions. 197 isUserError. 129 literal pattern. 195. 239 log. 86. 105. 202. 188 mapAndUnzipM. 225 map.INDEX isLatin1. 232. 197 isPermissionError. 194 mapM_. 64 label. 176. 91. 188 isPrint. 41 listArray. 9. 81 length. 172 instance for Integer. 9. 207 liftM3. 202. 195. 183. 130. 116 layout. 181. 156 Main (module). 181. 44. 16. 104. 92 magnitude. 177 join. 234 ixmap. 211. 9. 56 linearity. 19. 202. 206 Just. 45. 115 mapAccumL. 40. 119 maximumBy. 109 Left. 186 list. 173. 134 Locale (module). 119 . 109 mapMaybe. 211. 181. 139 libraries. 193. 197 isSpace. 56 lines. 207 v 257 liftM2. 239. 40. 173. 240 locale. 212 iterate. 84. 32 literate comments. 219 lookup. 184. 9. 80 list comprehension. 24 in do expressions. 207 linear pattern. 173. 195. 172 Ix (module). 92. 202. 197 isSuffixOf. 109 match. 23. 177 listToMaybe. 21. 64 kind inference. 50. 202. 195. 45. 172. 91 logBase. see also offside rule lcm. 195. 197 isLower. 129 last. 12. 212. 106 logarithm. 188 mapAccumR. 142 maxBound. 116 let expression. 169. 27 lambda abstraction. 215 isPrefixOf. 234. 44. 143 maximal munch rule. 181. 65 main. 210. 19. 39. 118 List (module). 172 derived instance. 198 max. 194 literal. 31. 193. 176. 140 LT. 207 liftM4. 202. 81. 195. 40. 199 . 7 lexLitChar. 176. 81 magnitude. 159. 111 v § ¢ £ 7¡ ¡ ¢ ¡ 7 . 88. 74 liftM. 23 lex. 193. 129 lexical structure. 181.
121. 193. 91. 104.258 Maybe (module). 105. 119 minimumBy. 57 name qualiﬁed. 225 moving ﬁles. 110 notElem. 180. 119 Nothing. 54. 104 derived instance. 9. 195. 81. 184. 210. 168 not. 109 instance for []. see also layout op. 11. 206 instance for []. 19. 9. 9. 54. 19 ops. 142 minBound. 113 octal. 10. 197 numeric type. 206 Monad (module). 119 Ord (class). 65 module. 27. see special name namespaces. 136 module. 61 monomorphism restriction. 202. 206 mzero. 214 opening a ﬁle. 246 mod. 130. 194 maybe. 234 moving directories. 143 minimum. 81 nub. 202. 17. 46 INDEX next. 90 numericEnumFrom. 206 + pattern. 214 operating system commands. 225 mplus. 180. 108 offside rule. 116 Num (class). 89. 140 opencom. 89. 55. 106 modid. 153 superclass of Fractional. 130 octit. 230 operator. 113 instance for IO. 90. 52. 129 newStdGen. 55. 157 instance for Ratio. 61 Month (datatype). 111 instance for Ratio. 153 superclass of Real. 91. 113 numericEnumFromThen. 248 newtype declaration. 186. 84. 84. 13. 51. 33. 91. 105 ord. 32–34. 198 Ordering (datatype). 161. 129 openFile. 187 null. 16. see qualiﬁed name special. 26. 66. 106 superclass of Real. 11. 111 instance for Maybe. 10 ncomment. 81. 60. 129 negate. 89. 79. 19 operator application. 178 instance for Char. 182. 38. 206 monad. 193. 111 maybeToList. 18. 206 monomorphic type variable. 184. 159. 88. 155. 32. 66. 105 instance for Complex. 9. 151. 5. 9. 19. 156 mkStdGen. 245 nonnull. 138 newline. 11 translation of literals. 181. 34. 137 or. 104. 112 ¢ ¦ . 194 method. 153 Numeric (module). 129 odd. 206 msum. 46. 244. 89 literal syntax. 202. 20 newconstr. 105 negation. 189 mkPolar. 142 instance for Array. 105 number. 202. see class method min. 186 nubBy. 244. 202. 111 superclass of MonadPlus. 206 instance for Maybe. 90. 113 numericEnumFromTo. 113 numericEnumFromThenTo. 91. 244. 115. 232. 136 Monad (class). 95 MonadPlus (class). 18 numerator. 88.
247 Random (module). see irrefutable pattern linear. 18. 70. 75 Prelude (module). 85. 103. 104. 23 quantiﬁcation. 107 putChar. 47 defaults. 57 patternmatching. 103 PreludeBuiltin (module). 23. 140 qtycls. 151. 169. 213 pi. 247 randomRs. 229 program name. 244. 9. 125 PreludeIO (module). 18. 124 instance for Array. 247 randomRIO. 147 precedence. 247 range. 151 Read (class). 153. 3 properFraction. 110 overloaded functions. 30 overloaded constant. 103. 91. 125 putStr. 172 rangeSize. 247 randoms. 247 randomR. 140 path. 130 qop. 91. 121 principal type. see patternmatching overloading. 11. 172 Ratio (datatype). 43. 125 qcon. 171. 130 qual. 53 print. 11. 140 pat. 11. 187 . 121 derived instance. 115 PreludeText (module). 244. 244. 244.INDEX otherwise. see + pattern refutable. 245 randomIO. see also ﬁxity pred. 103. 4 pragmas. 171. 125 product. 151 Ratio (module). 18. 119 program. 11. 41 quot. 96. 42. 30 @. 18. 11. 218 polymorphic recursion. 217 RandomGen. 106 polar. 91. 31. 96. 140 qconsym. 90. 75. see ﬂoating literal pattern integer. 151. 130 qvarop. 156 physical ﬁle. 244. see integer literal pattern irrefutable. 19. 31. 38 overloaded pattern. 183. 140 qvarid. 125 PreludeList (module). 169. 156 polling a handle for input. 11. 155. 244 random. 54 polymorphism. 153 rational numbers. 96. 181. 140 qconid. 130 qconop. 106 qvar. 229 program structure. 93. 11. 105 Prelude implicit import of. 92. 79. 224 phase. 130 qtycon. 225 pattern. 103. 139 qualiﬁed name. 244. 130 Random (class). 178 ¢ ¦ ¢ ¦ § ¢ £¡ . 125 putStrLn. 161 Rational (type synonym). 106 quotRem. 51 partition. 96. see refutable pattern pattern binding. 25. 18. 140 qvarsym. 55. see constructed pattern ﬂoating. 247 random access ﬁles. 34 Permissions (datatype). see wildcard pattern constructed. see aspattern _. 72 qualiﬁer. 143 instance for [a]. 51. 155. 103. 129 v 259 program arguments. see linear pattern + .
123 instance for Float. 33 RelativeSeek. 85. 109 recip. 123 instance for Int. 159. 117 replicate. 92. 138 Right. 224 readDec. 123 instance for Integer. 109 sequence_. 225 repeat. 124 v v § ¡ ¢ £¡ ¢ ¡ ¤ ¤ . 126 ReadMode. 143 ReadWriteMode. 56. 225 renaming directories. 85. 85. 248 setting the directory. 96. 155. 109 reverse. 10. 94. 86. 88. 214 readOct. 137 searchable. 224. 154 read. 218 readInt. 106 superclass of RealFrac. 217 SeekMode (datatype). 51. 198 readLn. 224 setStdGen. 92. 10. 139 rhs. 16. 225 removing directories. 166 . 10. 210. 124 instance for Double. 88. 154 superclass of RealFloat. 46 refutable pattern. 143 readLitChar. 104. 109 setCurrentDirectory. 164 readIO. 92. 226 Show (class). 159. 159. 93. 168 readHex.260 instance for Char. 162 scanl. 110 sequence. 214 separate compilation. 244. 224. 121 reads. 85. 119 . 96. 225 removing ﬁles. 225 renameFile. 88. 117 scontext. 106 removeDirectory. 164 reading a directory. 195. 126 readList. 164 readEsc. 130 return. 85. 93. 156 realToFrac. 159. 122 ReadS (type synonym). 81. 90. 122 readable. 121. see also operator application SeekFromEnd. 31. 76 seq. 91. 116 scanr. 225 renaming ﬁles. 108 scaleRat. 153 superclass of Integral. 214 Real (class). 108 realPart. 217 rem. 105 instance for Ratio. 55. 85. 107 instance for Ratio. 226 reading from a ﬁle. 198 readFile. 117 scanr1. 106 recursive datatype. 92. 92. 140 INDEX scaleFloat. 224. 91. 104. 224 section. 224. 108 RealFrac (class). 121 derived instance. 81 round. 117 reservedid. 214 readFloat. 121. 159. 217 semantics formal. 126. 225 removeFile. 89. 225 setPermissions. 130 reservedop. 116 scanl1. 217 seeking a ﬁle. 20. 159. 225 renameDirectory. 107 RealFloat (class). 143 instance for [a]. 86. 164 readParen. 163 readsPrec. 123 instance for Ratio. see formal semantics semiclosed handles. 97. 91. 122 readSigned. 224. 107 roundTo.
91.INDEX instance for Array. 195. 159. 232. 92. 43. 85. 129. 82 String (type synonym). 105 sum. 91. 106 tdDay. 12. 85. 237 show3. 159. 188 take. 93 tanh. 106 size of ﬁle. 123 instance for HandlePosn. 121 shows. 124 instance for Double. 163 showList. 105 simple pattern binding. 178 instance for Char. see also Prelude stderr. 181. 164 showFloat. 164 showFFloat. 235 tdHour. 210. 119 superclass. 111 string. 129 tail. 106 sine. 129 snd. 9. 245 splitAt. 188 sortBy. 57. 235 tdMonth. 235 tdMin. 237 showChar. 184. 85. 9. 232. 213 stmt. 106 standard handles. 92 signature. 159. 143 showLitChar. 183. 235 261 . 80. 138 sin. 117 takeWhile. 12 transparent. 86. 129 span. 108 signum. 53 significand. 48. 164 showHex. 181. 137 simpletype. 244. 139 strictness ﬂag. 232. 91. 91. 139 stmts. 154 superclass of Num. 122 ShowS (type synonym). 62 simpleclass. 159. 164 showGFloat. 45 strictness ﬂags. 41. 159. 163 showIntAtBase. 213 StdGen (datatype). 80. 232. see transparent string string. 108 succ. 92. 91. 232. 9. 122 showEFloat. 163 showsPrec. 9. 121. 129 split. 159. 159. 130 synonym. 183. 121 show2. see type signature signdecl. 213 standard prelude. 159. 237 show2’. 210. 49 symbol. 121. 123 instance for Ratio. 115 tails. 85. 130 subtract. 215 small. 106 tangent. 210. 118 special. 74. 143 showString. 246 stdin. 159. 9. 163 showInt. 181. 79 literal syntax. 123 instance for Float. 118 sqrt. 46. 122 sign. 118 tan. 85. 93 sinh. 210 instance for Integer. 235 tdPicosec. 26. 26. 127 System (module). 105 show. 114 sort. 163 showParen. 122 showSigned. 94. 188 space. 244. 199 showOct. 213 stdout. 229 system. see type synonym syntax. 86. 123 instance for Int. 91. 45. 229 tab.
49 topdecl (newtype). see also datatype recursive. 136 toRational. 233. 191 unzip7. 46 tyvar. 184. 9. 40. 22. 233. 93. 49 value. 136 topdecls. 235 transpose. see function type list. 47 topdecl (data). 206 unlines. 4 var. 187 trigonometric function. 42 type expression. 232 time12Fmt. 4. 233. 240 TimeDiff (datatype). 42 ambiguous. 183. 129 unless. see trivial type unit expression. 114 unwords. see constructed type function. 232. 107 try. 114 undefined. 40. 80. 195.262 tdYear. 67. 181. 119 unzip. 9. 181. 9. 51 topdecl (instance). 81. 234 time. 180. 224 Time (module). 235 toEnum. 129 uniLarge. 17. 7. see list type monomorphic. 80 tuple type. 9. 239. see principal type INDEX trivial. 41. 40. 119 until. 53 for an expression. 120 unzip3. 240 TimeLocale (datatype). 18. 232. 11. 224. 49. 105 toUpper. 92. 185. 125 valdefs. 181. see trivial type tuple. see class type constructor. 105 toInteger. 45. 188 Unicode character set. 11. 11. 129 uniSymbol. 235 timeFmt. see newtype declaration type signature. 197 uniDigit. 11. see tuple type type. 17. 130 varop. 93. 41. 43 type environment. 239. 41 tycls. 140 . 130 uncurry. 211. 49. 93 trivial type. 230 the ﬁle system. 114 unfoldr. 191 unzip6. see numeric type principal. 22. 187 unionBy. 180. 81 True. 137 type class. 221 tuple. 190 unzip5. 22 uniWhite. 202. 18. 103. 236 toCalendarTime. 129 unit datatype. 129 union. 4. 38. 79 truncate. 140 varid. 232 time of day. 187 uniSmall. 198 toUTCTime. 40 type renaming. 17. see expression typesignature type synonym. 66. 181. 46 topdecl (type). 86. 181. 239. 42. 198 topdecl (class). 106 toLower. 45 topdecl. 12 UnicodePrims (module). 39. 130 tycon. 98. 10. see monomorphic type numeric. 240 to12. 191 userError. see ambiguous type constructed. 91. 235 toClockTime. 9. 130 type. 195. 43 topdecl (default). 120 unzip4. 232. 38. 182. 38. 181. 235 terminating a program.
129 whitestuff.INDEX vars. 214 zip. 202. 190 zipWith7. 181. 224 writeFile. 190 zipWith5. 214 WriteMode. 190 zip7. 190 zip6. 206 whitechar. 190 zip5. 9. 97. 118 writable. 207 263 . 207 zipWithM_. 190 zipWith. 9. 53. 31 words. 130 vertab. 181. 181. 137 varsym. 120 zipWith4. 129 whitespace. 120 zip3. 10. 190 zipWithM. 185. 181. 181. 120 zip4. 38. 126. 190 zipWith6. 181. 9. 185. 129 when. 80. 181. 129 wildcard pattern (_). 202. 120 zipWith3. 202. 181. 9.
This action might not be possible to undo. Are you sure you want to continue?
We've moved you to where you read on your other device.
Get the full title to continue listening from where you left off, or restart the preview.