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

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