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

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