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