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

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