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