Haskell 98 Language and Libraries The Revised Report

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. Modified versions of this Report may also be copied and distributed for any purpose, provided that the modified version is clearly presented as such, and that it does not claim to be a definition 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 Identifiers 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 Type-Signatures . . . . . . . . . . 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 User-Defined 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 Qualified 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 Qualified 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

Predefined 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 Number-Theoretic 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

. . 159 160 161 161 161 . . . . . . . . . . . . . . .3 Derived instances of Bounded . . . . . . . . . . . . . . . . 172 16 Arrays 16. . . . . .4 Literate comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9. . . . . 147 II The Haskell 98 Libraries 149 12 Rational Numbers 151 12. . . . . . . . . 10. . . 156 14 Numeric 14. 147 11. . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Showing functions 14. . . . . . . . . . . . . . . .1 Notational Conventions 9. . . . . .1 Accumulated Arrays 16. . . . . . . . 15 Indexing Operations 169 15. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3 Miscellaneous . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Array Construction . . . . . . . . 16. .3 Layout . . . . . . . . . . . . . . . . . . 16. . . . . . . . . . .2 Lexical Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 Reading functions . . . . . . . . . . . . . . . 14. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 Specification of Derived Instances 10. . .1. . . . . . . . . . . . . . . . . . . . . . . .2 Derived instances of Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Library Complex . . . . . . . . . . . . . . . .4 Library Array . . . . . . . . . . . . . 9. . . . . . . . .iv 9 Syntax Reference 9. . . . . . . . . . . . . . . . . . . . 170 15. . . . . . . . . . . . . . . . . . . . .1 Inlining . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Deriving Instances of Ix . . . . . . . . . . . . . . . . . . . . . .1 Library Ratio . . . . . . . . . . . . . . . . . . . . . . . . . . . CONTENTS 127 127 128 130 134 136 141 142 142 143 143 145 . . . . . 16. .5 Context-Free Syntax . . . . . 153 13 Complex Numbers 155 13. . . . . . .3 Derived Arrays . . . . . . . . . . . . . . . . .4 Library Numeric . . . . . . . . . . . . . . . . . . . . .1 Derived instances of Eq and Ord . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4 Derived instances of Read and Show 10. . . . . . . . . . . . . . . . . . . . . . . . 10. . . . .2 Specialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14. . . . . . . . . . . . . . . . . . . . 10. .5 An Example . . . . . . . . . . . . 9. . .2 Library Ix . . . . . . . 173 174 174 175 176 176 . . . . . . . . . . . . .2 Incremental Array Updates . 11 Compiler Pragmas 147 11. . . . . .

. . . . . . . . . . . . . . 17. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3. . . . . .9 Library List . . .1 Indexing lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5 Predicates . . . . 21. . . . . . . . .9. . . . . . . . 21. . .2 Closing Files . .8 Handle Properties . . . . 17. . . . . . . . . . . 21. . . 17. . . . . . . . . . . 21. . . . . . . . . . . . . . . . . . . . . . . . . . 21. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21. . . . .9. . . . . . . . . . . . . . . . . . .2 Reading Input . . . . .2 Semi-Closed Handles . . . . . . 21. . . . . . . . . . 21. . .7 Repositioning Handles . . . . . . . . . . . .1 Opening Files . . . .9. . . . . . . . . . . . .5 Text Output .2 “Set” operations . . . . . . . . . . . .3 Functions .3. . . . . . . . 21. . . . . . . . . . . . . . .9. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8 Further “zip” operations . . . . . . . . . . . . . . . .4 Determining the Size of a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21. .7. . . . 20. . 21. . . . . . . .3 File locking . . . . . .5 Detecting the End of Input . 197 20 Monad Utilities 20. . 17. 20. . . . . . . . . . . . . . . . . . . . . . .1 Naming conventions 20. . . . . . . . . . . . . . . . . . . .9. . . . . . . . . . . . . . . . . . . .1 Revisiting an I/O Position 21. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 Maybe Utilities 193 18. . . . . . . . . . . . . .3 Opening and Closing Files . . . . . . . . . . . . . . 17. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21. . . . . . . . . . . . . .9 Text Input and Output . . . . . . . . . . . . . . . . . . . . 194 19 Character Utilities 195 19. . . . . . . .4 Library Monad . . . . . . . . . . . . . . . . . . . . . . . . . .7 The “generic” operations 17. . . . . . . . . . . . .1 Checking for Input . . . . 21. . . . .2 Class MonadPlus . . . . . . . . . . . . . . . . . . . . . .1 Library Maybe . . . . . . . . . . . . . 21. . . . . . . . . . . . . . . . . . .2. . . . . . . . .6 The “By” operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21. . . . . . . . . . . . . . . . . . .1 Flushing Buffers . . . . . . . . . . . . . .1 Library Char . . . . . . . . . . . . . . . . 21 Input/Output 21. . . . 21. . . . . . . . . . . . . . . . . . . . . . . v 179 182 182 183 183 184 184 185 185 186 . . . . . . . . . . . . . . . . . . . . . . . . . .6 Buffering Operations . . .6. . . . . . .2. . . . . . . . . . . . . . . . . 17. . .CONTENTS 17 List Utilities 17. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3 Reading Ahead . . . . . . 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 . . . . . . . . . . . . . . . . . .7. . . . . . . . . . . . . . . 21. . . . . . . . . . . . . . . . . . . .2 Seeking to a new Position 21. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21. . . . . . . . . . . . .3 List transformations .1 Standard Handles . . . . .4 Reading The Entire Input . .2 Files and Handles . . . . . . . .2. . . . . 17. . . . . . . . . . . . . . . . . . .4 unfoldr . . . . .1 I/O Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . .2 The Random class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Index . . . and the StdGen generator 27. . . . . . . . . . . . . . . . . . . . . .2 Copying Files . . . .10. . . . . . . . . . . . . . . . . . . . . .1 Library Locale . . . . . . . . . . . . . . . . . . . . . . . . . . .11Library IO . . . . . . . . . . . . . . . . . . . . . . . 241 243 245 247 248 249 251 . . . . . . . . . . . . . . . . . . . . . . .10Examples . . . . . . . . . . . . . 27. 22 Directory Functions 23 System Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240 26 CPU Time 27 Random Numbers 27. . . . . . . . . . . . . . . CONTENTS . . . . . . . . 234 25 Locale 239 25. 21. . . . . . . . . . .1 The RandomGen class. . . . . . . . . . . . . References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3 The global random number generator . . .vi 21. 219 219 220 221 223 229 24 Dates and Times 231 24. . . . . . . . . . . . . . . . . . . . . . . .10. . . . . . . .1 Library Time .1 Summing Two Numbers 21. . . . . . . . . .

Anyone should be permitted to implement the language and distribute it to whomever they please. 3. Oregon. Curry and Robert Feys in the Preface to Combinatory Logic [2]. providing faster communication of new ideas. to discuss an unfortunate situation in the functional programming community: there had come into being more than a dozen non-strict.” Haskell B. and a vehicle through which others would be encouraged to use functional languages. and most of these. all similar in expressive power and semantic underpinnings. 4. and excessive condensation would be false economy here. There was a strong consensus at this meeting that more widespread use of this class of functional languages was being hampered by the lack of a common language. It should reduce unnecessary diversity in functional programming languages. 5. Thus fullness of exposition is necessary for accuracy. 2. It was decided that a committee should be formed to design such a language. This document describes the result of that committee’s efforts: a purely functional programming language called Haskell. It should be completely described via the publication of a formal syntax and semantics. even more than it is ordinarily. have published something erroneous. Goals The committee’s primary goal was to design a language that satisfied these constraints: 1. including ourselves. research. 1956 In September of 1987 a meeting was held at the conference on Functional Programming Languages and Computer Architecture (FPCA ’87) in Portland. purely functional programming languages.PREFACE vii Preface “Some half dozen persons have written technically on combinatory logic. Curry whose work provides the logical basis for much of ours. a stable foundation for real applications development. It should be based on ideas that enjoy a wide consensus. and applications. . named after the logician Haskell B. including building large systems. It should be suitable for teaching. It should be freely available. we regard this as evidence that the subject is refractory. Since some of our fellow sinners are among the most careful and competent logicians on the contemporary scene. May 31.

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. It is intended to be a “stable” language in sense the implementors are committed to supporting Haskell 98 exactly as specified. The Haskell 98 Language and Library Reports were published in February 1999. If these program were to be portable.         Clarify obscure passages.viii PREFACE Haskell 98: language and libraries The committee intended that Haskell would serve as a basis for future research in language design. making some simplifications. much larger than I had anticipated. for the foreseeable future. Haskell 98 was conceived as a relatively minor tidy-up of Haskell 1. This task turned out to be much. By the time Haskell 98 was stabilised. It is not a . and is called “Haskell 98”. Revising the Haskell 98 Reports After a year or two. incorporating experimental features. many typographical errors and infelicities had been spotted. and I have adopted hundreds of (mostly small) changes as a result of their feedback. and hoped that extensions or variants of the language would appear. make small changes to make the overall language more consistent. a set of libraries would have to be standardised too. this stable language is the subject of this Report. As Haskell becomes more widely used. By the middle of 1997. The original committees ceased to exist when the original Haskell 98 Reports were published. The original Haskell Report covered only the language. and constitutes the official specification of both. with the following goals: Correct typographical errors. together with a standard library called the Prelude. Haskell has indeed evolved continuously since its original publication. It includes both the Haskell 98 Language Report and the Libraries Report. With reluctance.4. it was decided that a stable variant of Haskell was needed. it had become clear that many programs need access to a larger set of library functions (notably concerning input/output and simple interaction with the operating system). This document is the outcome of this process of refinement. and removing some pitfalls for the unwary. Resolve ambiguities. A separate effort was therefore begun by a distinct (but overlapping) committee to fix the Haskell 98 Libraries. the Report has been scrutinised by more and more people. so every change was instead proposed to the entire Haskell mailing list. At the 1997 Haskell Workshop in Amsterdam.4).

PREFACE ix tutorial on programming in Haskell such as the ‘Gentle Introduction’ [6]. functional dependencies. so that those who wish to write text books. can do so in the knowledge that Haskell 98 will continue to exist. including: multi-parameter type classes. concurrency. Haskell 98 does not impede these developments. exceptions.org gives access to many useful resources. local universal polymorphism and arbitrary rank-types. and some familiarity with functional languages is assumed. Control extensions. There is more besides. existential types.                       recursive do-notation. going well beyond Haskell 98. it provides a stable point of reference. at the time of writing there are Haskell implementations that support: Syntactic sugar. Extensions to Haskell 98 Haskell continues to evolve. For example. The entire text of both Reports is available online (see “Haskell resources” below). meta-programming facilities. including: monadic state. Haskell Resources The Haskell web site http://haskell. including: pattern guards. including: . or use Haskell for teaching. lexically scoped type variables. Type system innovations. Instead.

Contributed Haskell tools and libraries. with their affiliation(s) for the relevant period: Arvind (MIT) Lennart Augustsson (Chalmers University) Dave Barton (Mitre Corp) Brian Boutel (Victoria University of Wellington) Warren Burton (Simon Fraser University) Jon Fairbairn (University of Cambridge) Joseph Fasel (Los Alamos National Laboratory) Andy Gordon (University of Cambridge) Maria Guzman (Yale University) Kevin Hammond (Uniiversity of Glasgow) Ralf Hinze (University of Bonn) Paul Hudak [editor] (Yale University) John Hughes [editor] (University of Glasgow. Tutorial material on Haskell. devoted a huge amount of time and energy to the language. University of Nottingham. Oregon Graduate Institute) Dick Kieburtz (Oregon Graduate Institute) John Launchbury (University of Glasgow. and criticise the language or its presentation in the report. Chalmers University) Thomas Johnsson (Chalmers University) Mark Jones (Yale University. Implementations of Haskell. Microsoft Research Ltd) . in particular. including a complete list of all the differences between Haskell 98 as published in February 1999 and this revised version. Those who served on the Language and Library committees. by an active community of researchers and application programmers. Building the language Haskell was created. Oregon Graduate Institute) Erik Meijer (Utrecht University) Rishiyur Nikhil (MIT) John Peterson (Yale University) Simon Peyton Jones [editor] (University of Glasgow. suggest improvements to.x   PREFACE Online versions of the language and library definitions.           Details of the Haskell mailing list. via the Haskell mailing list. and continues to be sustained. Here they are. You are welcome to comment on. Applications of Haskell.

Chris Okasaki. Randy Michelsen. Jan Kort. Stefan Kahrs. Ian Lynagh. Duke Briscoe. Jose Labra. Clean. ML and Standard ML. Simon B. In addition. Paul Callaghan. Satish Thatte. Patrick Sansom. Nic Holt. Felix Schroeter. Jan Skibinski. Ralf Hinze. Ross Paterson. Id. Raman Sundaresh. Laura Dutton. Mark Carroll. Klemens Hemm. the following languages were particularly influential: Lisp (and its modern-day incarnations Common Lisp and Scheme). Mike Joy. Bjarte M.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 co-ordinating editor for one or more revisions of the language. it is right to acknowledge the influence of many noteworthy programming languages developed over the years. Jerzy Karczmarczuk. They are as follows: Kris Aerts. Marcin Kowalczyk. Henrik Nilsson. Cordy Hall. Chris Fasel. Nick North. Michael Webber. Tom Thomson. Bob Hiromoto. Carl Witty. Sandra Loosemore. Pablo Lopez. Stuart Wray. Craig Dickson. Ketil Malde. Tony Warnock. Ian Holyer.   . Josef Svenningsson. Guy Cousineau. Tony Davie. Bjorn Lisper. Landin’s ISWIM. Gary Memovich. Keith Wansbrough. Simon Thompson. Libor Skarvada. Although it is difficult to pinpoint the origin of many ideas. Richard Kelsey. Sisal. Robert Jeschofnik. Arthur Norman. Michael Fryers. Jones. Andreas Rossberg. Olaf Chitil. John Meacham. Dean Herington. Mike Gunter. Ian Poole. Dylan Thurston. Tom Blenko. Chris Clack. Graeme Moss. Curry. Andy Moran. Alexander Jacobson. Rick Mohr. Nimish Shah. Christian Maeder. Patrik Jansson. Rinus Plasmeijer. Lauren Smith. Sigbjorn Finne. Tommy Thorn. Jeff Lewis. George Russell. Larne Pekowsky. Hope and Hope . Fergus Henderson. Mark Tullsen. Christian Sievers. Without these forerunners Haskell would not have been possible. Jim Mattson. Sergey Mechveliani. Michael Marte. Gofer. Chris Dornan. Stephen Price. Dave Parrott. and Bonnie Yantis. Kent Karlsson. Mark Lillibridge. dozens of other people made helpful contributions. Manuel Chakravarty. Stef Joosten. aside from the important foundational work laid by Church. Simon Marlow. Orjan Johansen. and Turner’s series of languages culminating in Miranda 1 . some small but many substantial. Antti-Juhani Kaijanaho. Olaf Lubeck. Hans Aberg. Feliks Kluzniak. Paul Otto. Siau-Cheng Khoo. Ken Takusagawa. Amir Kishon. Wolfram Kahl. John Robson. and others on the lambda calculus. APL. Pat Fasel. Finally. Østvold. Matt Harden. David Tweed. Michael Schneider. Mike Thyer. Thomas Hallgren. Sven Panne. Franklin Chen. 1 Miranda is a trademark of Research Software Ltd. Magnus Carlsson. Andy Gill. Rosser. Sten Anderson. Malcolm Wallace. Julian Seward. Randy Hudson. Mark Hall. Richard Bird. Pradeep Varma. Backus’s FP [1]. Stephen Blott.

September 2002 PREFACE .xii Simon Peyton Jones Cambridge.

Part I The Haskell 98 Language 1 .

.

  1. static polymorphic typing. and fixity information. Declarations define things such as ordinary values. At the next lower level are expressions.e. This includes such issues as the nature of programming environments and the error messages returned for undefined programs (i. etc. 3 . datatypes. Modules provide a way to control namespaces and to re-use software in large programs. purely functional programming language incorporating many recent innovations in programming language design. programs that formally evaluate to ). all described in Chapter 4. expressions are at the heart of Haskell programming “in the small. defined in Chapter 2. of which there are several kinds. Haskell is both the culmination and solidification of many years of research on non-strict functional languages. The lexical structure captures the concrete representation of Haskell programs in text files. 2. pattern-matching. non-strict semantics. user-defined algebraic datatypes. The top level of a module consists of a collection of declarations. type classes. We leave as implementation dependent the ways in which Haskell programs are to be manipulated. compiled. including lists. arbitrary and fixed precision integers. 3.” 4.1 Program Structure In this section. and floating-point numbers. arrays. At the topmost level a Haskell program is a set of modules. a monadic I/O system. interpreted. a module system. 1. and a rich set of primitive datatypes. This report defines the syntax for Haskell programs and an informal abstract semantics for the meaning of such programs. we describe the abstract syntactic and semantic structure of Haskell. described in Chapter 5. list comprehensions. Haskell provides higher-order functions.Chapter 1 Introduction Haskell is a general purpose. described in Chapter 3. At the bottom level is Haskell’s lexical structure. as well as how it relates to the organization of the rest of the report. An expression denotes a value and has a static type.

such as for expresin if sions. If these translations are applied exhaustively. and pragmas supported by most Haskell compilers. the specification of derived instances. The translation of each syntactic structure into the kernel is given as the syntax is introduced.1. there are several chapters describing the Prelude. Errors in Haskell are semantically equivalent to .4 CHAPTER 1. it is essentially a slightly sugared variant of the lambda calculus with a straightforward denotational semantics. so the language includes no mechanism for detecting or acting upon errors. The chapters not mentioned above are Chapter 6. and permits not only parametric polymorphism (using a traditional Hindley-Milner type structure) but also ad hoc polymorphism. and Chapter 7. 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. how Haskell programs communicate with the outside world). Also.e. the concrete syntax. INTRODUCTION This report proceeds bottom-up with respect to Haskell’s syntactic structure. they are not distinguishable from nontermination. for types. implementations will probably try to provide useful information about errors. Although the kernel is not formally specified.2 The Haskell Kernel Haskell has adopted many of the convenient syntactic structures that have become popular in functional programming. Technically.3 Values and Types An expression evaluates to a value and has a static type. which discusses the I/O facility in Haskell (i. or overloading (using type classes). the type system allows user-defined datatypes of various sorts. Values and types are not mixed in Haskell. which describes the standard built-in datatypes and classes in Haskell. Generally the italicized names are mnemonic. However. This modular design facilitates reasoning about Haskell programs and provides useful guidelines for implementors of the language. However. as then else . etc. See Section 3. the result is a program written in a small subset of Haskell that we call the Haskell kernel. 1. In this Report. for declarations.   ¥ ¢  § £ ¤  ¡ ¢  ¦ 1.   . literate programming. the meaning of such syntactic sugar is given by translation into simpler constructs.

. and constructor within a single scope. and type classes refer to entities related to the type system.1. those for type variables. An identifier must not be used as the name of a type constructor and a class in the same scope. These are the only constraints. and module names refer to modules. NAMESPACES 5 1. 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. type constructors. There are two constraints on naming: 1.4. 2. the other four kinds of names are identifiers beginning with uppercase letters. Names for variables and type variables are identifiers beginning with lowercase letters or underscore. for example. class.

INTRODUCTION .6 CHAPTER 1.

Haskell compilers are expected to make use of new versions of Unicode as they are made available.]. all whitespace is expressed explicitly. This syntax depends on properties of the Unicode characters as defined by the Unicode consortium. there is no implicit space between juxtaposed symbols. Most of the details may be skipped in a first reading of the report. source programs are currently biased toward the ASCII character set used in earlier versions of Haskell. 2.. Haskell uses the Unicode [11] character set.Chapter 2 Lexical Structure In this chapter. 7 § ¢ £¡ ¨ ¥¥8 8 8   1 &§ ¢ £¡  A !§ 7 3¢  8 8 8 @¥¥9 £ § )'% $ " 0(&§#!§ £§  ¢§ ¡ £¡ ¢ ¢  ¦ £¤ ¡ §¥  § § £¡ §¥  § § £ ¦¤ ¢ ¡ ¨ ¦¤ ¢ ¡ ©§¥  § § £ ¢ £  ¡ 7 3¢  ¡§ 7 3¢ 6 4¤ ¦ 2 5  § 3©¦ . although usually the context makes the distinction clear.. we describe the low-level lexical structure of Haskell. 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. BNF-like syntax is used throughout. with productions having the form: Care must be taken in distinguishing metalogical syntax such as and from concrete terminal syntax (given in typewriter font) such as | and [.

˜ any Unicode symbol or punctuation y B         2 4 3 t  ¢ h h h h A v f 4 x"$ wg " 5 7 2 ' 4 3 t § ¦ £$  § 7 2 ' 4 3 t  © ¢ A B Z any uppercase or titlecase Unicode letter _ : " ’    %¤   ¢ u  8 8 8 @¥¥9 ¦ £$    2¤   ¢ u  ¢ © 2 3© 4  7 ' § £$   2¤   ¦ ¢u ©   %¤   ¢ ¢ u ¢7   %¤    S¢RQFP§   4 32 ¦    © G E C ¦ 4  _ a b z any Unicode lowercase letter  77 !3¢ 4 t §  8 8 8 @¥¥9  ¦ £$  4 © 77 03¢  ¢ t 4 § £$ ¦ 703¢ 7 4 t © 77 !3¢  §¢© t 4 77 !3¢  § #¥ ¡3 §¢ ¦  ¤   G E QFC    © G E S¢RQFC ¢   © G E C 4 ¡  IHFD32   ©   ¥ ©  ¢ ¦ § ¦¥  4 32 ¦ 4 4 2   B2  © 4 2  ¥  ¥2 ¦ 7  ¡ ©   ¥ © ¦ ¦ ¥  4 4 ¢ 2 §    § ¨)§ § ¥ (   ¦ £$ ' ¨¢ § © ¤ ¥   § ¨¦£ § ¥ ¢  & $ § © § ¥ %¤  § ¨¦£  ¢ ¤£¡ © § ¥   § ¨¦£ §  ¤¢ ¡     1§3¥0 0 4 ¤ 2 ¦ § ¥   ¤ ' #¢   ¢2  ¦ §   0 ¦ ¦¤ $§ §£%¢  ¤7 ¦§ £   ¦ 7   6  6 6 6 7 ¤ 3¢ ¥  § ¡ § 7 3¢ 7   ©   ¥  ¡  4 ¢ 4 ¤ ¡&¤ 7   2 ¢ ¡ .{-} a carriage return a line feed a vertical tab a form feed a space a horizontal tab any Unicode character defined as whitespace CHAPTER 2. / < = > ? \ ˆ | .2 Lexical Program Structure 8 ( ) .§§  § € § ¦ £$  § §      § €  © ¢ 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. LEXICAL STRUCTURE : " ’  7 ¥    4 §©   §   ©  § §   §  2 43©    2¤  ¦ 7 ' 7 3¢  ¡ ¢ 7 § !3¢ ¤   77 §    ©  ¨¥ '¨  ¡ ¤ ¢ ¥   § ¨¢£¡ ¤  ¨¥ §¢ ¤   § ¥ ¨¦£ § ¢  ¡T ) cRasY`WXrpq7"9 g 24"9 A g hi7¡9 gA " 3¦db`XV   GH§¢ C U f f 9 e c a Y W U E ¦   2 ¡ ! # $ % & * + . [ ] ` { }       ¤ ¤©  ¤ ¥  § 2 " § ! ¢  §¢   ©    ¥¢  ¤   ¤   © ¦ 7 ¦ 43¤   3§ ¢ 32 ¡    ©     ¢   § ¦ ¨¦¤   © § ¥ £  ¤¢ ¡   ¤¥      § ¦ § ¤   § § 7 3§ ¢ ¤ 7  4¦ ¢   ¡  ¢ 7  -. .

COMMENTS 9 Lexical analysis should use the “maximal munch” rule: at each point. “-->” or “|--” do not begin a comment.2. however “--foo” does start a comment. --) and extends to the following newline. and. In an ordinary comment. a sequence of dashes has no special significance. the longest possible lexeme satisfying the production is read. the first unmatched occurrence of the string “-}” terminates the nested comment. No legal lexeme starts with “{-”.g. cases is not. == and ˜= are not. the character sequences “{-” and “-}” have no special significance. are not valid in Haskell programs and should result in a lexing G E HTC Characters not in the category error.   © § ¥   § ¨¦£ Any kind of is also a proper delimiter for lexemes. then any occurrence of {. because both of these are legal lexemes. although case is a reserved word. Nested comments are also used for compiler pragmas. An ordinary comment begins with a sequence of two or more consecutive dashes (e. although = is reserved. The sequence of dashes must not form part of a legal lexeme. Similarly.4 Identifiers 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. If some code is commented out using a nested comment. 2. Nested comments may be nested to any depth: any occurrence of the string “{-” within the nested comment starts a new nested comment. Instead. So. 2. each “{-” is matched by a corresponding occurrence of “-}”. as explained in Chapter 11. “{---” starts a nested comment despite the trailing dashes. For example.3 Comments Comments are valid whitespace. in a nested comment. The comment itself is not lexically analysed. A nested comment begins with “{-” and ends with “-}”. for example.or -} within a string or within an end-of-line comment in that code will interfere with the nested comments. terminated by “-}”. Within a nested comment.3.

: :: = \ | <. Underscore. Other than the special syntax for prefix 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 identifier consists of a letter followed by zero or more letters. “:”. is reserved solely for use as the Haskell list constructor. this makes its treatment uniform with other parts of list syntax. Identifiers are lexically distinguished into two namespaces (Section 1. “_”. is treated as a lower-case letter. such as “[]” and “[a. although each infix operator can be used in a section to yield partially applied operators (see Section 3.5).   Notice that a colon by itself.   An operator symbol starting with any other character is an ordinary identifier. underscores. as defined above. : : : . However. naMe.b]”.10 CHAPTER 2. “_” all by itself is a reserved identifier. digits.4): An operator symbol starting with a colon is a constructor. the last is a constructor identifier).-> @ ˜ => Operator symbols are formed from one or more symbol characters. In the remainder of the report six different kinds of names will be used:  variables constructors type variables type constructors type classes modules                 )  4 f ¡$ 4   ¡  ¥  h  " 9 f £   f 4 f S¥ X¤¢%w5       §§        ) " 9¡¦fX¤  f24w5¡§   2 3© ¥ £ f  4  4 ©7 ' 2 4  ©     7 '   §   @ ¦      %¤   7 2   ¢7 '   77 !3¢ 4 §©    ¦ ¤ § ¦32 ¦ ¦32 ¦ 32 ¦ ¦   2¤    § § § ¢ ¢7       6 6 6 6 6 6 6 6 6 2   ¥¢  ¤  ¤   © ¡ ¦ 43¦ 2  © 4 S¤   © ¢ ¦ ¦ §   ¥¢   ¤   © ¦ ¦ ¦ ¦ ¤ § ¦ 72  3¥ %§ ¦ © § § § ¢¦ 2 ¤ ¦ 2  2 4  %§  ¢  %§    ¤ . Compilers that offer warnings for unused identifiers are encouraged to suppress such warnings for identifiers beginning with underscore. This allows programmers to use “_foo” for a parameter that they expect to be unused.4): those that begin with a lower-case letter (variable identifiers) and those that begin with an upper-case letter (constructor identifiers).. and single quotes. all operators are infix. used as wild card in patterns. and can occur wherever a lower-case letter can. and Name are three distinct identifiers (the first two are variable identifiers. All of the standard infix operators are just predefined symbols and may be rebound. Identifiers are case sensitive: name. and are lexically distinguished into two namespaces (Section 1.

(two tokens) F.. . F. no spaces are allowed between the qualifier and the name.5. Namespaces are also discussed in Section 1. .g f. but not type variables or module names.4. ¦ ¢ ¦  ¢ § 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  ¥  %§    ¢ ¡       ¦ ! . .2.+ is an infix operator with the same fixity as the definition of + in the Prelude (Section 4. the other four do not. variables and constructors have infix forms.g (qualified ‘g’) f ..5 Numeric Literals  §§ § § 2  § § § 2  §§ §   §   § §   §  ¦  ¦ 6 7 ¢ ¦ ¢ § 2 73§ ¢    4  4§   ¨  e E + - ¨ §   32 ¦ ¦ ¢ ¡  . Prelude. (two tokens) The qualifier does not change the syntactic treatment of a name. constructor. 2.. F. This f. . Sample lexical analyses are shown below. also.4. 4§   ¢ ¡  ¥ 0X 7 ¢  ¦ ¢ ¡ 7 3¢   3¢ 7 § ¦  32 ¡  ¦ ¢ 4§   ¦ 7 4 §   ¡ 3¢ 4 §     ¦ 7 3¢  ¦   § 7 ¢2 ¦ 4§     ¢ ¡  ¥ 0o 0x 0O 7 3¢ 43332 ¨  © ¦ 4 ©  3¤ `¨  ¦ 72  3¥ %§ ¨ © § ¦ 32 ¨ ¢ %§ ¨   § § S  ¢  . for example. . type constructor and type class names. NUMERIC LITERALS 11 Variables and type variables are represented by identifiers beginning with small letters. Qualified names are discussed in detail in Chapter 5.’) F . Lexes as this f . and the other four by identifiers beginning with capitals.g F. ¦ ¤ §  `¨  Since a qualified name is a lexeme.2). (qualified ‘. g (three tokens) F. This applies to variable. A name may optionally be qualified in certain circumstances by prepending them with a module identifier..

similarly. octal (prefixed by 0o or 0O) or hexadecimal notation (prefixed by 0x or 0X). Escape codes may be used in characters and strings to represent special characters. “horizontal tab” (\t). but must be escaped in a string. Note that a single quote ’ may be used in a string. are also provided. Floating literals are always decimal. The typing of numeric literals is discussed in Section 6. as in "Hello".  ©    7 3¢ 4§  ¤ ¥     ¢                           4§      ¢¡  ¥  § 2  ¦ ¢ 7 3¢  ¦ 7 ¢        ©      © ¡5¢ ¡ 5¢   ¢ ¨£¡ )   ©      © ¡ 5¢   ¢ ¨£¡ § §#¥¦£ ¤ ¥   § ¨¦£ § ¥   ©    y  ¢    2¤ ¢ u   ¢          ¤§ ¦  ©       ©   § ¨¥  § ¨¥ ¤ ¢ ¦  ¤   ¡§¢  ¤   ¡ §¢  7 ¥     6 6 6 6 6 6 6 § @§ ©  ¢ ©  ¤ ¥  ¢     © ¡ §¢    #¦ § ¤ § © 7 ¤ ¤ ¡ ¤ § 5¢¦ ¢ ¢ ¥ ¥      . A string may include a “gap”—two backslants enclosing white characters—which is ignored. “carriage return” (\r). Similarly. 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. \o137) and hexadecimal (e. "\SOH".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. \x37) representations are also allowed. Further equivalences of characters are defined in Section 6.1. as in ’a’. is parsed as a string of length 1. Thus "\&" is equivalent to "" and the character ’\&’ is disallowed. numeric escape characters in strings consist of all consecutive digits and may be of arbitrary length. LEXICAL STRUCTURE There are two distinct kinds of numeric literals: integer and floating. Escape characters for the Unicode character set.4. Numeric escapes such as \137 are used to designate the character with decimal representation 137. “backspace” (\b). “new line” (\n).g. a double quote " may be used in a character. For example. the one ambiguous ASCII escape code. The category also includes portable representations for the characters “alert” (\a). and “vertical tab” (\v).2. Consistent with the “maximal munch” rule.4. and strings between double quotes. octal (e. A floating literal must contain digits both before and after the decimal point.1. Integer literals may be given in decimal (the default). 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).12 CHAPTER 2. “form feed” (\f). including control characters such as \ˆX. but must be escaped in a character. Negative numeric literals are discussed in Section 3. 2. \ must always be escaped. this ensures that a decimal point cannot be mistaken for another use of the dot character.g.

pop.1 shows a (somewhat contrived) module and Figure 2. When this happens. a close brace is inserted.7). an explicit open brace must be matched by an explicit close brace. As an example.2.2 shows the result of applying the layout rule to it. The effect of layout on the meaning of a Haskell program can be completely specified by adding braces and semicolons in places determined by the layout. This allows both layout-sensitive and layoutinsensitive styles of coding. a single newline may actually terminate several layout lists. Also. and \ˆX. an empty list “{}” is inserted. b = 2 g y = exp2 in exp1 making a. a control character. Within these explicit open braces. The layout rule matches only those open braces that it has inserted." String literals are actually abbreviations for lists of characters (see Section 3. Given these rules. no layout processing is performed for constructs outside the braces. then the layout list ends (a close brace is inserted). \ \a numeric escape character. even if a line is indented to the left of an earlier implicit open brace. these rules permit: f x = let a = 1. Haskell programs can be straightforwardly produced by other programs. which can be freely mixed within one program.3 gives a more precise definition of the layout rules. Because layout is not required. and layout processing occurs for the current level (i. For each subsequent line. 2. where the . Informally stated.e. A close brace is also inserted whenever the syntactic category containing the layout list ends. LAYOUT 13 "Here is a backslant \\ as well as \137. If the indentation of the non-brace lexeme immediately following a where. then a new item begins (a semicolon is inserted). b and g all part of the same layout list. let. do or of is less than or equal to the current indentation level. Figure 2. Section 9. then instead of starting a layout. if it is indented the same amount. if an illegal lexeme is encountered at a point where a close brace would be legal. that is. 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).7. insert a semicolon or close brace). The meaning of this augmented program is now layout insensitive. the braces and semicolons are inserted as follows. or of. if it contains only whitespace or is indented more. by using layout to convey the same information. do.7 Layout Haskell permits the omission of the braces and semicolons used in several grammar productions. Note in particular: (a) the line beginning }}. let. and if it is indented less. The layout (or “off-side”) rule takes effect whenever the open brace is omitted after the keyword where. then the previous item is continued (nothing is inserted).

stkToLst (MkStack x s) = x:xs where {xs = stkToLst s }}.push :: a -> Stack a -> Stack a .top :: Stack a -> a . size ) where data Stack a = Empty | MkStack a (Stack a) push :: a -> Stack a -> Stack a push x s = MkStack x s size :: Stack a -> Int size s = length (stkToLst s) where stkToLst Empty = [] stkToLst (MkStack x s) = x:xs where xs = stkToLst s pop :: Stack a -> (a. size ) where {data Stack a = Empty | MkStack a (Stack a) . Stack a) . case s of {r -> i r where {i x = x}}) -. push.2: Sample program with layout expanded termination of the previous line invokes three applications of the layout rule. LEXICAL STRUCTURE module AStack( Stack. pop. top. push.push x s = MkStack x s . (b) the close braces in the where clause nested within the tuple and case expression.top (MkStack x s) = x } -.(pop Empty) is an error top :: Stack a -> a top (MkStack x s) = x -.(top Empty) is an error Figure 2. inserted because the end of the tuple was detected.(top Empty) is an error Figure 2. top.14 CHAPTER 2.size :: Stack a -> Int . corresponding to the depth (3) of the nested where clauses. inserted because of the column 0 indentation of the end-of-file token. and (c) the close brace at the very end. Stack a) pop (MkStack x s) = (x.1: A sample program module AStack( Stack.pop :: Stack a -> (a.pop (MkStack x s) = (x.(pop Empty) is an error . case s of r -> i r where i x = x) -.size s = length (stkToLst s) where {stkToLst Empty = [] . . pop.

For example. “concatMap” used in the translation of list comprehensions (Section 3. there are some families of nonterminals indexed by precedence levels .11) means the concatMap defined by the Prelude. or for left-. and (if it is in scope) what it is bound to. and may have a double (written as a superscript).or non-associativity and a precedence level. For example actually stands for 30 productions. with 10 substitutions for and 3 for . the nonterminals . where appropriate. Free variables and constructors used in these translations always refer to entities defined by the Prelude. right. we describe the syntax and informal semantics of Haskell expressions. including their translations into the Haskell kernel. A precedencelevel variable ranges from 0 to 9. Except in the case of let expressions. an associativity variable varies over . . regardless of whether or not the identifier “concatMap” is in scope where the list comprehension is used. these translations preserve both the static and dynamic semantics. Similarly.Chapter 3 Expressions In this chapter. index: a letter . In the syntax that follows. ::  - 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 .

} ¦ §    {  ( )  - right section labeled construction labeled update  )  )   )  ¦  . }   ¦     ... Expressions that involve the interaction of fixities with the let/lambda metarule may be hard to parse.. . it has the same precedence as the infix .. } in (x + y) z + (let { . For example. ¦ 2 ' . the expression  p  ¢  8 @e §  2   ¡ ¦ p v £!e ¢ $ ¡ 2   ¢ %e p 8  Q¢ ¡ 2    p v £!e ¢ $ A ¦ ¡ § { . ]     ¢ £    . ]       . } in (x + y)) (f x y) :: Int \ x -> ((a+b) :: Int) + g y x + y { . The grammar is ambiguous regarding the extent of lambda abstractions. . .2.2).(f x)) + y let { .operator defined in the Prelude (see Section 4.16 © @§ CHAPTER 3.. .. This f x .1). .4. ) ]  ¤ ¥ £  ¢    Q¢     ( ( [ [ [ ( ( ( ) . and conditionals.4. parentheses must be added around either “ ” or “ ” when unless or .. Figure 4. } in x + y let { . The ambiguity is resolved by the meta-rule that each of these constructs extends as far to the right as possible.. } in x + y y :: Int -> a+b :: Int A note about parsing. EXPRESSIONS Expressions involving infix operators are disambiguated by the operator’s fixity (see Section 4. Given an unparenthesized expression “ ”. Sample parses are shown below.f let z + f x \ x Parses as (f x) + (g y) (. | parenthesized expression tuple list arithmetic sequence list comprehension left section left section right section  variable general constructor  function application       0 ¡ ¦§ 0 ) A 9 g © ¡  ¨ ¢ 8 8 ¥¥8 ¦ ¦¡ 2 ¢ A ¦ § 0 8¥¥8 ' ¡ ¦ § 0 8 ¦ ¦  ' ' ¢ S  ¤ ) 2  v ¡ p v ¢ ¡e ¡   ¢ S  ) 2  ¡ v ¡ p v ¢ $0e ¡ 2  ¢ S  v p v ¢ 5e A 2 ¡  ¡ v ¡ ¡ 7 ¢ p v £!e ¡ ¢ $ ¡ ¡  $ $ ¢ A  ¥8¥8 8 ¡  7 3¢ ¨ ¥ ¢¡  ¢ ¡¢ ¨ £ 7 ¡  ¢ ¡ ¡  ¡   ¢ S  ¢ 8¡ ¥¥8   ¡ ¡ ¡  8   ¡¡ ¢S  ¥8¥8 ¡¢ ¡ ¡  8   ¡¡ ¡ ¡  ¢ ¡   § § ¤ 7 3¢ ¦ 2 7   ¡ ¢ S  4§ ¢ © do { }  do expression  ¨ ¤ ¡ ¡ ¢   S¢0 ¢  ¢   S¢0    '    ¢                6 6   ' ¡ ¡ ¢ S   ¢ ¡  0 ¢ ¢ .. Negation is the only prefix operator in Haskell. let expressions. Consecutive unparenthesized operators with the same precedence must both be either left or right associative to avoid a syntax error.

For the sake of clarity. Operators. the error message is created by the compiler. Programmers are advised to avoid constructs whose parsing involves an interaction of (lack of) associativity with the let/lambda meta-rule. That is. denoted by . results in an error.2 Variables.     3. Constructors. so the expression must parse thus: (let x = True in (x == x)) == True 17 However. a value of any type may be bound to a computation that. Translations of Haskell expressions use error and undefined to explicitly indicate where execution time errors may occur.3. implementations may well use a post-parsing pass to deal with fixities. so they may well incorrectly deliver the former parse. 3. errors cause immediate program termination and cannot be caught by the user. are indistinguishable by a Haskell program from non-termination. The actual program behavior when an error occurs is up to the implementation. It should also display the string in some system-dependent manner. When undefined is used. all Haskell types include . When evaluated. The messages passed to the error function in these translations are only suggestions. Since Haskell is a non-strict language. when demanded.1.1 Errors Errors during expression evaluation. The Prelude provides two functions to directly cause such errors: error :: String -> a undefined :: a A call to error terminates execution of the program and returns an appropriate error indication to the operating system. implementations may choose to display more or less information when an error occurs. the rest of this section shows the syntax of expressions without their precedences. and Literals    ¤ ¢     ¤   § § 7 3¢ ¦ 2 7     6 ¡ ¢ S  ¢ variable general constructor . ERRORS let x = True in x == x == True cannot possibly mean let x = True in (x == x == True) because (==) is a non-associative operator.

If no fixity declaration is given for `op ` ` then it defaults to highest precedence and left associativity (see Section 4.% ).4). . Ratio Integer). or is an ordinary identifier enclosed in grave accents (backquotes). EXPRESSIONS () [] (. An operator is either an operator symbol. Special syntax is used to name some constructors for some of the built-in types. such as + or $$.2). (+) x y is equivalent to x + y. An operator is a function that can be applied using infix syntax (Section 3.18 CHAPTER 3. production for An integer literal represents the application of the function fromInteger to the appropriate value of type Integer. as found in the and . an operator symbol can be converted to an ordinary identifier by enclosing it in parentheses. where fromInteger is a method in class Num (see Section 6. one can write the infix application x `op y.4. a floating point literal stands for an application of fromRational to a value of type Rational (that is. as defined in the Ratio library. For example. ¦ ¦    ¦ § ¦   `   `   `   `   )   )   )   ( ( ( ( ` ` ` ` )  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 qualified variable constructor qualified constructor variable operator qualified variable operator constructor operator qualified constructor operator operator qualified operator .1). The floating point literal is equivalent to fromRational ( Ratio. Translation: The integer literal is equivalent to fromInteger .5). such as ` `. where fromRational is a method in class Fractional and Ratio. or partially applied using a section (Section 3.4.1. Dually. The integers and are chosen so that . instead of writing the prefix application op op x y.% constructs a rational from two integers. Similarly. These are described in Section 6. For example. and foldr (*) 1 xs is equivalent to foldr (\x y -> x*y) 1 xs. ) : Haskell provides special syntax to support infix notation.

will always refer to the negate function defined in the Prelude.3. if the pattern fails to match.1.17. page 55). prefix negation qualified operator . (-) is syntax for (\ x y -> x-y). partial applications of data construc- ) of ( . and is syntax for negate . as with any infix operator. . one must write e1(-e2) for the alternative parsing.defined in the Prelude (see Table 4. Prefix negation has the same precedence as the infix operator . Similarly. so the parentheses may be could be a data constructor.   3. ¡   A ¡ 8 8 ¥¥8 ¡ ¡   £   ¡   Function application is written omitted in (f x) y.operator and unary negation. . Because e1-e2 parses as an infix application of the binary operator -.operator does not necessarily refer to the definition of . where the are patterns. v Translation: The following identity holds: Given this translation combined with the semantics of case expressions and pattern matching described in Section 3. it may legally be written as \(x:xs)->x. However. Because tors are allowed. it may be rebound by the module system. CURRIED APPLICATIONS AND LAMBDA ABSTRACTIONS 19 3.4 Operator Applications  £ The special form .in the Prelude. An expression such Lambda abstractions are written \ as \x:xs->x is syntactically incorrect. The binary .   £ ¤  ¡   2  £ ¤  2   3  ¡ ¢  The form is the infix application of binary operator to expressions and    ¡ ¡ - 2 ¦ ©32 ¡ ¢ ¡      2 ¤  ¡ ¡¢   ¢ 2  ¡ ¡ ¡  ¢ ¡ ¡ ¡  6 6  where the are new identifiers. The set of patterns must be linear—no variable may appear more than once in the set. and does not denote (\ x -> -x)—one must use negate for that. the only prefix operator in Haskell. .  ¨   ££ ¥¦£ ¡   ¨  ££ ¥¦£ ¡  ¨  £££ ¡ ¦¥   ¨   £££ ¡ ©§¦¥¤¢  \ -> \ -> case ( .3 Curried Applications and Lambda Abstractions   -> . unary . ) ->  ¦ ¢ ¡  A !§ ¡ 8 8 ¥¥8 ¡ § \ ->      ¡ ¢ ¡ £5¢ ¡ ¢ S  ¢ ¢ ¡ ¢¢   ¨ £§S¢0 ¡   6 6  ¡ ¡ ¡ function application lambda abstraction ¡ ¡  ¢ 2 ¢ ¡  ¢ ¡   0 . then the result is . There is no link between the local meaning of the .denotes prefix negation.3. Application associates to the left.3.

For example. However. where is a binary operator and Sections are a convenient syntax for partial application of binary operators. but an application of prefix negation.5 Sections   ¢ S  ¤ v ¡ ¢ S  ¡ v ¡ p v ¢ A5e ¡ 2  - Syntactic precedence rules apply to sections as follows. there is a subtract function defined in the Prelude such that (subtract ) is equivalent to the disallowed section. As another example. but (+a*b) and (*(a+b)) are valid. by the let/lambda meta-rule (Section 3).    - £ ¡ ¤  ¢   ( ) negate ¡ 2  £ ¤  ¡ 2 ¢  ¡ p v £!e ¢ $ ¡ ¡ 2   ) 2  p v ¢ ¡e ¡   ) 2  p v ¢ 0e ¡ $ 2  v S  ¢ ¡ ¡ 7 ¢ ¡ ¡ ¡ 2   v    6 ¡ ¢ ¡  ¡ ¢ S  ¢ . The expression (+ ()) can serve the same purpose. (a+b+) is syntactically correct. and similarly for ( ). ( ) is legal if and only if (x ) ( )).20 Translation: The following identities hold: CHAPTER 3. but (+a+b) is not. Because (+) is left associative.  ( )  - right section  )   ¡  2   ¡ 2 ¡ 2 ¡ ¡ ¡ 2   ¢ ¡      ( ( ( ) )     left section left section right section is an expression. (*a+b) is synparses in the same way as (x tactically invalid. the expression (let n = 10 in n + x) parses as (let n = 10 in (n + x)) rather than ((let n = 10 in n) + x)   Because . the latter may legally be written as (+(a+b)).is treated specially in the grammar. () is not a section. ¢ S  ¡ 2   Sections are written as ( ) or ( ). EXPRESSIONS 3. the expression (let n = 10 in n +) is invalid because. as described in the preceding section.

and must have the same type. is an expression. 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 ¢        . denoted []. and the empty list is Lists are written [ . where . CONDITIONALS Translation: The following identities hold:   21 3.1).6 Conditionals ¥ ¢ ¡  Translation: ¡ ¢  The following identity holds: ¥ ¢  £ ¢  ¡ ¤  where True and False are the two nullary constructors from the type Bool. ¥   £   ¡   3. ].      ¢ ¢ S  8 8 ¥¥8   4 © 3¦ 2 2 ©¦ 2 4 © ¦ 3¡ 32   8 8 ¥¥8 ¡ ¦ 2 ¦ 2 ¢ ¡  [    . and otherwise. £     ¡   £ ¢ S  ¡ ¤  ¡ ¢ ¡  if then else ¢ ¡ ¡   ¡ ¥ ¢  ¡ ¡   ¢ ¡    6 6 6 6 6 6 6 6 ¡   2 where . which is also the Prelude.3.1.3.7 Lists   [] (        ) : . Standard operations on lists are given in the Prelude (see Section 6.   is a binary operator. if is False. The list constructor is :. as defined in the must be Bool. ] ¢   ¡¡  £ ¥ ¢  ¡ ¢ ¡  ¡ 2  ¡¡ £ ¤  if then else case of { True -> . The type of type of the entire conditional expression.6. and Chapter 8 notably Section 8. False -> } £   ¥   A conditional expression has the form if then else value of is True. .

22 Translation: The following identity holds:   CHAPTER 3.1.3). The types of through must all be the same (call it ). . It is the only member of that type apart from ..2).         ¢ ¡  ( () ) ¦     ¤  ¢ ¡   ¢    ¡¦   § §   8 8 ¥¥8 ¤  ¢ ¡§ ¡§   8 8 ¥¥8       8 8 ¥¥8 8 8 ¥¥8  ¡ ¦ 2 ¢ ¡  (   . EXPRESSIONS where : and [] are constructors for lists. ) ¤  ¢ 8 8 ¥¥8 £   ¡ ¢    ¡¡    8 8 ¥¥8   ¡ ¡ ¤    [ .2).5).1. respectively.) a b c tuple is denoted by (. it is considered part of the language syntax. . It is a right-associative operator. Translation: ( ) is equivalent to . ) (see Section 4. ) Tuples are written ( . and the type of the overall expression is [ ] (see Section 4. where there are denote the same value.c) and (. as defined in the Prelude (see Section 6. Standard operations on tuples are given in the Prelude (see Section 6. If through are the types of through . The unit expression () has type () (see Section 4. and may be of arbitrary length . and cannot be hidden or redefined. Thus (a.1.1. . with precedence level 5 (Section 4.2).8 Tuples  ¢ S  (.1. ) for is an instance of a -tuple as defined in the Prelude. Translation: ( . The constructor for an commas.4.).4 and Chapter 8). ] : ( : ( (     : []))) ¡   ¡ ¢    6 6 6 6 ¡     ¦ 32 ¦ 32 ¡ ¡ § ¢ S  ¢ S     ¢ ¢   . .b.9 Unit Expressions and Parenthesized Expressions ¡¦ 2    The form ( ) is simply a parenthesized expression. and requires no translation.1. . .. like []. . § 3. 3. and is equivalent to . and can be thought of as the “nullary tuple” (see Section 6. . . then the type of the resulting tuple is ( .2). The constructor “:” is reserved solely for list construction. ).

.4 for more details of which Prelude types are in Enum and their semantics.. ¡   ¡   ¡ ¡ ¢ £¡ ¢ ¡    6 6 6 7 ¢ 3¢ S  ¡ ¢ ¡ ¢ S  $  ¢ ] .. § ¥ ¢  £ ¤  ¡   § § ¨ £ ¢ ¡  ¡ ¡ ¢ ¡  [ . where each of the has type .3.. See Section 6. which are arbitrary expressions of type Bool     local bindings that provide new definitions for use in the generated expression or subsequent guards and generators. ARITHMETIC SEQUENCES 23 3.10 Arithmetic Sequences ¨ ¥ ¡ $  ¢ ¡  Translation: Arithmetic sequences satisfy these identities: ¡   where enumFrom. ] where the qualifiers are either and is an            ¡ ¡  $ © ¢ ¡  7    ¦ ¢ ¡  [ | <let § . . ] . The semantics of arithmetic sequences therefore depends entirely on the instance declaration for the type .3. ] .10. . enumFromThen. and is an instance of class Enum. .1.11 List Comprehensions  ¦  A 8 8 ¥¥8 ¡ guards.. and enumFromThenTo are class methods in the class Enum as defined in the Prelude (see Figure 6. ] enumFrom enumFromThen enumFromTo enumFromThenTo v   The arithmetic sequence [ . ] denotes a list of values of type . § 3.   §   generators of the form expression of type [ ] §   <. ] list comprehension generator local declaration guard     ¥¤  £   ¡   ¥ ¢  ¡   £   ¡    7 3¢     ¥ ¢  7 ¢ ¥ ¢  £ ¤  £ ¤  ¡¢  ¡¢  ¡¢  ¡ ¢  [ [ [ [ . depth-first evaluation of the generators in the qualifier list.. .     Such a list comprehension returns the list of elements produced by evaluating in the successive environments created by the nested... page 83). ] . .17) of type v  ¦ A ¥ 8 8 ¥¥8 ¡    A list comprehension has the form [ | . enumFromTo. where is a pattern (see Section 3.

} in . ] | <. (3. an implicit ˜ makes these patterns irrefutable.4)..[ [(1.2]. = = = = [ ] [ | . . [(5.x. If a qualifier is a guard.x) <.(3. over boolean over declaration lists.2). As indicated by the translation of list comprehensions.y] ] else [] ] ]   6 ¡ ¢ ¡  .x. and introduce a nested.12 Let Expressions ¢ ¡  © Let expressions have the general form let { .24 CHAPTER 3.4). z <. bindings in list comprehensions can shadow those in outer scopes. for example: Translation: List comprehensions satisfy these identities. and if a match fails then that element of the list is simply skipped over. The function concatMap. True ] if then [ | let ok = [ | ok _ = [] in concatMap ok let in [ |  [ x | x <. Pattern bindings are matched lazily. variables bound by let have fully polymorphic types while those defined by <. Declarations are described in Chapter 4. The scope of the declarations is the expression and the right hand side of the declarations.y) = undefined in does not cause an execution-time error until x or y is evaluated. mutually-recursive list of declarations (let is often called letrec in other languages).are lambda bound and are thus monomorphic (see Section 4.17).4)]. over list-valued expressions. Thus: [ x | xs <. it must evaluate to True for the previous pattern match to succeed.xs ] yields the list [4. over patterns. which may be used as a translation into the kernel:  where ranges over expressions.   A ¦ 8 8 ¥¥8   ¡ ¦   let in '   ©   7  ¡ ¡ ©   7  ¦ © 7 ¥ ¦   [   | let . and over sequences of qualifiers. lexically-scoped.   let (x.(3. x <.   3. and boolean value True. ] =   7   ]       ¡ 7 ¥ ¦ '         7 ¥ ¦ 7   '  ¡         [ [ [ [ | True ] | ] | .5. over qualifiers. are defined in the Prelude.2)] ]. expressions. For example. EXPRESSIONS Binding of variables occurs according to the normal pattern matching rules (see Section 3. ok is a fresh variable.x ] [ z | y <. As usual.

.4. 3. .3. ¥ §  ¢ ¡  ¢ ¡ ¢ ¡  | ¨ §   ¢ ¡  -> ¤ }  3  § § ¢ ¦¤ 5  § 7 3¢   %§ ¡ 4   ¦   ¨ ©   ¨ 5© 7    ¦ 7 ¥ ¦ © @§ ¢ £¡ ¦   ¡ A§ 7 3¢   £¡ ¦ ¢ ¢ £¡ ¢ ¡  §   ¡ ¥8¥8 ¢ £¡ ¡§ 8 7 3¢ § ¢ S  case .4. 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 { .13.3. Each match in turn consists of a sequence of pairs of guards and bodies (expressions). the “|” is a terminal symbol. . } in are captured by this translation: After removing all type signatures. where where ¡ £ ¡       7 3¢ ¡ ¡ ¢ ¡ ¦   ¡ ¢   6 6 6 6 6   let = in =  ¨ ¡ ¡ ¥ ¡ ¢   ¨ ©    ¡   ¡ ¡  ¨ ¨ ©  ¡ ¢ ¡   ¡ ¡ ¥ ¢  let { = let = .) Each alternative consists of a pattern and its matches.3.˜ ) = ( ... ... CASE EXPRESSIONS Translation: The dynamic semantics of the expression let { 25 . . these identities hold. which may be used as a translation into the kernel: ¡ where fix is the least fixpoint operator. not the syntactic metasymbol for alternation. using the translation in Section 4. ->   ¦§ of { } . Note the use of the irrefutable patterns ˜ . followed by optional bindings ( ) that scope over all of the guards and expressions of the alternative. . each declaration is translated into an equation of the form = .. . This translation does not preserve the static semantics because the use of case precludes a fully polymorphic typing of the bound variables. in = } in = = let (˜ . . Once done. The static semantics of the bindings in a let expression are described in Section 4.13 Case Expressions   A case expression has the general form (Notice that in the syntax rule for . . where and are patterns and expressions respectively. . ) in case of ˜ -> where no variable in appears free in let = fix ( \ ˜ -> ) in ¡ ¢ ¨   ££ ¦¥£   ¡         § ¢ £¡ ¦ © @§ ¡ § 7 3¢ 7¡ 3 ¢ ¢ ¦     .

It has a single unambiguous parse. If all the guards evaluate to False.17. the guards for that alternative are tried sequentially from top to bottom. from top to bottom.getLine return (words l)  §     § § ¦ 4 ¢ ©  %§ ¡ 4 ¥   © . in the environment of the case expression extended first by the bindings created during the matching of the in the where clause associated with that alternative. 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 <. The alternatives are tried sequentially. Programmers are advised. with the formal semantics of case expressions in Section 3. matching continues with the next alternative. to avoid guards that end with a type signature — indeed that is why a contains an not an . ¦ §    ¡ 7  ¦ ¢ ¡  § ¡ ¢¡ £  ¡ ¢ ¡ ¢S  A § 4 §¤© 8¥8¥8 ¡ § 4 § © 4§ © © @§ do { } do expression        v © 7 ¥ ¦   ¡ ¢ S     6 6 6 ¤ ¥¡ © @§ ¢ ¡  § ¡ 4§ 4§ © © ¢ ¡  . and then by the guards evaluates to True. Each body must have the same type. A case expression is evaluated by pattern matching the expression against the individual alternatives. namely case x of { (a.17. and parsers with limited lookahead may incorrectly commit to this choice. ¦   3. The expression case x of { (a. and the type of the whole expression is that type.26 CHAPTER 3. A note about parsing.  ¦ ¨ . and hence reject the program._) | (let b = not a in b :: Bool) -> a } However. the corresponding right-hand side is evaluated in the same environment as the guard. therefore.   . If matches the pattern in the alternative. If no match succeeds.3. EXPRESSIONS A case expression must have at least one alternative and each alternative must have at least one body. Pattern matching is described in Section 3. the phrase Bool -> a is syntactically valid as a type. If one of the pattern. the result is . .14 Do Expressions  A do expression provides a more conventional syntax for monadic programming._) | let b = not a in b :: Bool -> a } is tricky to parse correctly. <let .

" stands for a compiler-generated error message. and fail are operations in the class Monad. select from..2) and update (Section 3.3.1 Field Selection ¤ ¢   Field labels are used as selector functions.15. When used as a variable. do { <- © @§ 4 ¤© § = = =  ¦ 4 ¤© §     } = do { } _ = fail ". and ok is a fresh identifier.. however. preferably giving some indication of the location of the pattern-match failure." >>= ok in do { } { ¡ 6 ¡ ¢ S  ¢ .. a field label serves as a function that extracts the field from an object. 3. which may be used as a translation into the kernel. To illustrate the last point.2. in record construction (Section 3. as defined in the Prelude.3).1)..BAD Here S is legal but T is not. 3. This shadowing only affects selector functions.15. passed to fail. As indicated by the translation of do. variables bound by let have fully polymorphic types while those defined by <.15. Within a datatype.15 Datatypes with Field Labels A datatype declaration may optionally define field labels (see Section 4. because y is given inconsistent typings in the latter. and update fields in a manner that is independent of the overall structure of the datatype. field labels cannot be confused with ordinary variables. a field label can be used in more than one constructor provided the field has the same typing in all constructors. A field label can be used at most once in a constructor. DATATYPES WITH FIELD LABELS 27 Translation: Do expressions satisfy these identities. } = © @§ 4 ¤© § } © @§ 4 ¤© ¡ § >> do let ok ok in let 7 ¥   ¦     © @§ 4§ 7 © @§   do { } do { . Different datatypes cannot share common field labels in the same scope.15. >>=. after eliminating empty : } .are lambda bound and are thus monomorphic. the functions >>.OK -. consider: data S = S1 { x :: Int } | S2 { x :: Int } data T = T1 { y :: Int } | T2 { y :: Bool } -. © The ellipsis ". These field labels can be used to construct. © @§ 4§ © ©   © @§ 4§ © ©   do {let . Selectors are top level bindings and so they may be shadowed by local variables but cannot conflict with other top level bindings of the same name.

undefined A   8 8 ¥¥8 ¡   8 8 ¥¥8 ¡ ¡  ¦ ¡§ ¢ ¡  0 { = .15. 0 v   v P ¡ A      8 8 ¥¥8 ¡ ¢  ¦ ¡ '   8 8 ¥¥8 ¡ ¡ ¡   = case x of { -> . EXPRESSIONS A field label 0 ' introduces a selector function defined as: 3. it denotes F .28 Translation: x 0 CHAPTER 3. ¦ § v ¦ v   where are all the constructors of the datatype containing a field labeled with . the field labels .   A field label may not be mentioned more than once.) Construction using field labels is subject to the following constraints: Only field labels declared with the specified constructor may be mentioned. and is y when some field in has a label of or undefined otherwise. where F is a data constructor.     Fields not mentioned are initialized to     A compile-time error occurs when any strict fields (fields whose declared types are prefixed by !) are omitted during construction.1. A ¥¥8 ¡ A   A 8 8   ¡ ¡   ¡ ¡ -> } ¦ '  ¤ ¦ ¢2     A 8 8   ¥¥8 ¡   0 ¦ 6 6 0   ¢ ¦ ¦ ¡ ¦§ ¢ S  ' ¢ 0 .2.   0 ¦ © ' ¡ ¢ v  0 § ¡   ¦ If the th component of a constructor in the binding list . . The expression F {}. then value . is legal whether or not F was declared with record syntax (provided F has no strict fields — see the third bullet above). and if appears is .2 Construction Using Field Labels  ¦ A ¦§ 0 A constructor with labeled fields may be used to construct a value in which the components are specified by name rather than by position. is y when labels the th component of or _ otherwise. Unlike the braces used in declaration lists. (This is also true of field updates and field patterns. the { and } characters must be explicit. these are not subject to layout. Strict fields are discussed in Section 4. © ' ¡ ¢ v  § ¡ ¦ © ¡ ¢ v ©  ' §  ¡ where is the arity of The auxiliary function § . where is the arity of F. is the default  © § 8 8 ¥¥8  © ¡ §   © { } = undefined ' ¡  £¢  ¡   0 ' ¡ ¢¢   0 Translation: ' In the binding = . is defined as follows: has the field label . . Otherwise. } labeled construction .

f3 = ’x’}.   An execution error occurs when the value being updated does not contain all of the specified labels. This creates a new value in which the specified field values replace those in the existing value.   At least one constructor must define all of the labels mentioned in the update. This example translates expressions using constructors in field-label notation into equivalent expressions using the same constructors without field labels.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. .15. and is the arity of   £ F© £ ¢ § 8 8 ¥¥8  ¡ -> _ -> error "Update error"  T©   ' £ ¡  ¢  ¡  ' ' £ ¡ ¢ .  T© § 8 8 ¥¥8  ¡  T© ¡ ¡ §  § ¡       ->   ¢  '     ¢  ¡ ¢  ¡  '   ¡ ¢ {   }  ¡    ¡  = case of  ¢ £  ¡   8 8 ¥¥8 8 8 ¥¥8 ¡ 8 8 ¥¥8 ¡ ¡   ¡    ¦§   0 { .f2 :: Int} | C2 {f1 :: Int. v ©     ¥¥8 ¡   8 8 where . Translation: © Using the prior definition of   Here are some examples using labeled fields: data T = C1 {f1. f3. f3 = ’B’} x {f1 = 1} The field f1 is common to both constructors in T. f4 = ’A’.3 Updates Using Field Labels   ¦ A ¦§ ¡ 0  § Values belonging to a datatype with field labels may be non-destructively updated. A compile-time error will result if no single constructor defines the set of field labels used in an update. DATATYPES WITH FIELD LABELS 29 3. } labeled update .   No label may be mentioned more than once.      ¦ ' ¦ ' ) A9g© ¨ ¡ ¢ ¡  ¢     6 '    ¡ ¢ S    ¢ .15.3. v is the set of constructors containing all labels in . Updates are restricted in the following ways: All labels must be taken from the same datatype.. such as x {f2 = 1..

the principal type. The value of the expression is just that of .30 CHAPTER 3.17. 3. Translation:  3. so defining the semantics of pattern matching for case expressions is sufficient.1.1). As with normal type signatures (see Section 4. and case expressions. where is an expression and is a type (Section 4. list comprehensions. EXPRESSIONS 3. function definitions. do expressions. . but it is an error to give a type that is more general than. they are used to type an expression explicitly and may be used to resolve ambiguous typings due to overloading (see Section 4.3.2).4. or not principal type derivable from comparable to.17 Pattern Matching Patterns appear in lambda abstractions. the declared type may be more specific than the . } ¦§ ¢  ¦   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 { :: . pattern bindings. = } 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 § ¢ ¡ £§¢ § § ¡ ¢ £¡ ¢ £¡ ¢ ¡  . However.4).1 Patterns Patterns have this syntax:  § 8 8 ¥¥8 ¡§ 0 { . the first five of these ultimately translate into case expressions.16 Expression Type-Signatures    %§ 0 Expression type-signatures have the form :: .

according to the following rules:  ¤   ¤  1.e. value being matched by § § ¢ ¢ § = as a name for the to .      ¢     § . or it may diverge (i.17. It is as if an identifier not used elsewhere were put in its place. PATTERN MATCHING 31 The arity of a constructor must match the number of sub-patterns associated with it. this definition is illegal: f (x. For example. 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 right-hand-side. it may succeed._.y.ILLEGAL. Pattern matching proceeds from left to right.3. . one cannot match against a partially-applied constructor. and allow one to use . Matching the pattern against a value always succeeds and binds ¤ ¢  Patterns of the form @ are called as-patterns. and outside to inside. case e of { [x. returning a binding for each variable in the pattern. .17. For example. ) ]  ¤  ¢      £¡ ¢ §   £¡ ¢ 8¥¥8 8 8 8 ¥¥8 ) ._] is equivalent to: case e of { [x. return ).z] -> if x==0 then True else False } -> if x==0 then True else False } 3. All patterns must be linear —no variable may appear more than once.2 Informal Semantics of Pattern Matching Patterns are matched against values.   ¢ ¡ ¢ £¡ ¢ £¡ ¤ § ¢£§¢ ¡ ¡§ ¢£¡ ¡§ ¢£¡ ¢ £¡ § _ ( ( [ ˜    wildcard parenthesized pattern tuple pattern list pattern irrefutable pattern ¢ ¤  ¢      6   § ¢ £¡ 0 . For example.x) = x -. Attempting to match a pattern can have one of three results: it may fail.

Matching the pattern by data. If the value is of the form . is the same as in numeric literal patterns. depends on the value: against a value. 8. the functions >= and .  §  ¦ Q32 If the value is of the form . then is matched against . § § § That is. The interpretation of numeric literals is exactly as described in Section 3. the first to fail or diverge causes the overall match to fail or diverge. (Binding does not imply evaluation. except that only   ¢ ¢ ¢ ¦ ¢ ¢ ¦ ¢ ¢ ¢   If the value is   . depending on the type of the pattern. the overloaded function fromInteger or fromRational is applied to an Integer or Rational literal (resp) to convert it to the appropriate type. where == is overloaded based on the type of the pattern. At that point the entire pattern is matched against the value. Fields not named by the pattern are ignored (matched against _). Matching against a constructor using labeled fields is the same as matching ordinary constructor patterns except that the fields are matched in the order they are named in the field list.) Operationally. respectively. constructors associated with newtype serve only to change the type of a value. that is. where newtype.. All fields listed must be declared by the constructor. EXPRESSIONS 2.32  CHAPTER 3. and fails otherwise. Matching the wildcard pattern _ against any value always succeeds.   . the match diverges. if all matches succeed. and no binding is done. sub-patterns are matched left-to-right against the components of the data value. ¦ 32 4. the overall match succeeds. fields may not be named more than once. The match diverges if the comparison diverges. this means that no matching is done on a ˜ pattern until one of the variables in is used. and if the match fails or diverges. 1 ¦ 2 ¦ 32 7   ¦ 8 8 ¥¥8 ¡ r1 32 If the value is of the form the match fails. The match diverges if this test diverges. . where is a different constructor to  ¦ 32  A  8 8 ¥¥8 ¡ A !§  8 8 ¥¥8 ¡ § 5. 3. 7. The interpretation of the literal integer literals are allowed. depends on the value: is a constructor defined by is a constructor defined ¢ ¡ £5¢ ¢ ¡ £§¢   § ¢ ¡ £§¢ ¢ £¡  § ¢ £¡ ¢ ¡  § ¦ 2 ¢ ¡ £5¢  § ¢ ¡ £§¢ ¢ ¦ ¢ ¡ £§¢        .are overloaded. Again. so does the overall computation. or string literal pattern against a value succeeds if == . and to if matching against fails or diverges. where    ¢ £¡ ¦ 32   § ¢ £¡ ¦ 32    If the value is   . The free variables in are bound to the appropriate values if matching against would otherwise succeed. character. 6. Matching the pattern against a value.2. Matching a numeric. resulting in the binding of to . Matching an + pattern (where is a variable and is a positive integer literal) against a value succeeds if >= . then is matched against . Matching the pattern ˜ against a value always succeeds.

then   Aside from the obvious static type constraints (for example. If the match of against fails or diverges.˜(a. attempting to match ’a’ against causes the match to 2.3). An + pattern can only be matched against a value in the class Integral. the following static class constraints hold: An integer literal pattern can only be matched against a value in the class Num. to . Consider the following declarations: newtype N = N Bool data D = D !Bool           (\ (x:xs) -> x:x:xs) (\ ˜(x:xs) -> x:x:xs)     (\ ˜[x.’x’].’b’] is matched against [’x’. it is a static error to match a character against a boolean). then ’a’ to match against ’x’. ] (\ ˜[x. ]         (0. But if [’a’. where is a constructor defined by newtype and is irrefutable @ where is irrefutable. and the result is a failed match. These patterns may be removed or changed in future versions of Haskell.1) § ¢ ¡ £5¢ § ¢ ¡ £§¢ © § 7 ¢ 0 § ¢ ¡ £§¢   %¥   §   ¤ § ¢ §¢ ¡   ¦          §   ¤   ¢ ¡ £§¢ § ¢  @ 9. Here are some examples: 1. (a.   A floating literal pattern can only be matched against a value in the class Fractional. or of the form ˜ (whether or not (see Section 4. Matching a refutable pattern is strict: if the value to be matched is the match diverges.b)] -> x) [(0.b)] -> x) [(0. If the pattern [’a’.y) -> 0) (\ ˜[x] -> 0) [] (\ ˜[x] -> x) [] 0 0     : : 3.2. then . PATTERN MATCHING §  33 against a value is the result of matching against . It is sometimes helpful to distinguish two kinds of patterns. ¢ ¡ £§¢ ¢ ¡ £§¢ E     ¤ ¢  § ¢§ ¡ £§¢ ¢ ¡ £§¢ ¢ ¦ ¤ ¢E  ¢ ¦     . Matching an irrefutable pattern is nonstrict: the pattern matches even if the value to be matched is . ]. The irrefutable patterns are as follows: a variable. irrefutable matching:         (\ ˜(x.1).’b’] is matched against [ . a wildcard.y) -> 0) (\ (x.3. These examples demonstrate refutable vs.17. Many people feel that + patterns should not be used. All other patterns are refutable.1). is irrefutable). Matching an as-pattern augmented with the binding of so does the overall match.

EXPRESSIONS These examples illustrate the difference in pattern matching between types defined by data and newtype:       Additional examples may be found in Section 4. (e).2. Subsequent identities manipulate the resulting case expression into simpler and simpler forms. and is a newtype constructor. A guard is a boolean expression that is evaluated only after all of the arguments have been successfully matched. or pattern binding to which it is attached.3. it is this rule that defines the meaning of pattern matching against overloaded constants. in Figures 3.Int.2 involves the overloaded operator ==.y.2. (q).1. For example. function definition.3 Formal Semantics of Pattern Matching The semantics of all pattern matching constructs other than case expressions are defined by giving identities that relate those constructs to case expressions. in f :: (Int. These identities all preserve the static semantics. Any implementation should behave so that these identities hold. and are boolean-valued expressions. since that would generate rather inefficient code. then True is substituted for the guards in the forms. The semantics of case expressions themselves are in turn given as a series of identities. it is not expected that it will use them directly.1–3. In particular. (j).z) [a] | (a == y) = 1 both a and y will be evaluated by == in the guard. and (s) use a lambda rather than a let.Int) -> [Int] -> Int f ˜(x.1–3. The guard semantics have an obvious influence on the strictness characteristics of a function or case expression. Rule (h) in Figure 3. In Figures 3. regardless of whether it actually includes guards—if no guards are written. this indicates that variables bound by case are monomorphically typed (Section 4.4). . 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.34 CHAPTER 3. v ¥ §  Rule (b) matches a general source-language case expression. an otherwise irrefutable pattern may be evaluated because of a guard. . and it must be true for the overall pattern match to succeed. and are algebraic datatype (data) constructors (including tuple constructors). and are variables.17. ¢ ¡ 4 v  ¢ 3  v ¤  1           (\ (N True) -> True) (\ (D True) -> True) (\ ˜(D True) -> True) True       E v   v ¤¢ 1     ¢  v ¡ . and are patterns. Rules (d). and are expressions.2: . 3. The environment of the guard is the same as the right-hand-side of the caseexpression alternative.

. _ -> }  $C ¨ § ££ ¦¥£ © DC ¨ ¨ @   §     ¨ $C¦E£¥¥¦FC ££E © ££ © ¥¦£ C  C $3 § (d) case (\ where of { ˜ -> . -> error "No match" }  ¡ !  ¨ ££ ¥¦£ ©   £ ¡  © ¨ © ¡  © ¨ #   $£ § § (b) .3. _ -> } -> ) (case of { -> are all the variables in }) (case of { -> A     % ££ ¦¥£ case of { -> (where is a new variable) case of { -> let { } in if then _ -> }} ©   ¥ ¢ 2   10 © % A B ¨ @   § A @ 6  _ else if ¥ ¢ 98   70 ££ ¥¦£  6  © 4  © 1%  5% ¨ § (c) case of { | | -> -> -> . _ -> } case of { -> ( \ -> ) . Part 1   G  @     § (f) case of { _ -> .17. | } else ££ ¥¦£ _    £ ¡ ! §  ¨ ££ ¥¥£ -> case of { . Figure 3. }  } . }) ¡   "£ § §   £  ¡   (a) case of { } where is a new variable case of { case of { _ § (\ -> case of { ¥ £ ¦¤¢ ¥ £ ¦¤¢ })     . _ -> } @   §   @   C   ¨ ¨ C § § (e) case of { @ -> . where { } } then   10   -> where { # ¥ ¢ 32 ( & )' ¤# ( & )' ¤# % ££ ¦¥£ © & ¤#   ¡ ! where each | -> © & ¤# % has the form: .1: Semantics of Case Expressions. . PATTERN MATCHING 35 .

_ -> is a newtype constructor @   @       ¨ ¨ ¢ § § ¢ (k) case of { -> . . _ otherwise case of { {} -> . _ -> } where is if labels the th component of . is a new variable © 7¤ A   ¨ £  @     ¨ ¢ £ (l) ¢ case where of { -> . EXPRESSIONS Figure 3. _ -> } case of { -> .) else where is a numeric literal ¡ £  @   ©    C ££ ¥¦£ © C     £ (r) case where of { -> .  ¦" C E £££ ¥¦¥E © C  28 ¨ E £££ ¥¦¥E @   © ¨ _ -> at least one of } is not a variable. _ -> } . _ -> } case of { _ _ -> .36 CHAPTER 3. _ -> is a data constructor of arity } @      C ££ ¥¦£ © © C      ££ ¥¦£ ©        ££ ¥¦£  C ©   ££ ¦¥£   (q) case ( ) of { (\ -> ) where is a data constructor of arity © C -> . _ -> } where is a newtype constructor ¢ } case §   C    C § (j) case of { -> } ( \ -> ) of {   C §  @     C § (i) case of { -> . _ -> } case of { -> } -> @ F    ¡ §  @ F    ¡ § (h) ¡ case where of { -> . character. _ -> } case ( ) of { -> . = . _ -> } if >= then (\ -> ) ( . are new variables else } } }. } -> .2: Semantics of Case Expressions. ££ ¥¦£ @      ¨  C ££ ¦¥£ @   © C -> case © ¨ of { -> case _ -> } @      ¨ ££ ¥¦£ © ¨  ¦ C   ££ ¦¥£ © C §           ¨ § (g) case of { case of { -> . are fields of constructor . _ -> } @    @    ©    $C ££ ¥¦£ © C     ££ ¦¥£ @ © 4    @   (p) @   @       '   ££ ¥¥£ § § (o) -> . _ -> }        of { -> . _ -> case of { -> case of { { = } -> case of { { = . _ -> } A @       ££ ¥¥£ ££ ¦¥£ ¥ ¥ §¨ ¨ A ¥ ¤ ¥ ¦¤     © ¨ © ¤ A § © ¨   © 5¤ ££ ¥¥£ ¥ ¤ § @     § (m) case of { { = . respectively   @   @     ¨ ¨   ¤     ¨ ¤ ££ ¥¦£ § ¨ © ¨ § (n) case of { case of { # { = } -> . or string literal. _ -> } if ( == ) then is a numeric. } -> . _ -> _ -> }} where . Part 2 @   ¡ § @     C   ¡ C ¡ § § (s) case of { + -> . _ -> } where and are distinct data constructors of arity and .

.¦ §  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      ¦     ¦ { .  ¦ { . }  ¦ A   8 8 ¥¥8 ¡  ¦ $ ¥ £0 7      ¦    ¦   { . }  = = where where empty   A   § ¦ 37  6 6 © ¥   § ¦ § © 7   ¦ 7   6 6   ©   7¥   ¦ 7 ¥ ¦   6 6 © 7¥   ¦ 7 ¥ ¦      6 6 ©    2§ 7 ¥   ¦ ¡ 2 § 7 ¥ ¦ ¡    6 6  2 ¦ ' 2   $ 7 ¦ 2 4 . type data newtype class instance default ( . . module where  2 ¨ ©§ ¤ 5@¤32 ¢ ¡  § 2 4 ¦ ' { { { . . = => => => => . . we describe the syntax and informal semantics of Haskell declarations. } } ©   2§ .

but most “built-in” datatypes are defined with normal Haskell code. and nested declarations. consisting of class. . For exposition. Haskell has several primitive datatypes that are “hard-wired” (such as integers and floating-point numbers). DECLARATIONS AND BINDINGS The declarations in the syntactic category are only allowed at the top level of a Haskell module (see Chapter 5). 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 fixity declaration empty declaration  %§ § ¢ ¦ ¥  ¢ 2 ¡      .3.38    %§ CHAPTER 4. we divide the declarations into three groups: user-defined datatypes. . and fixity declarations (Section 4.(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.3). A class declaration (Section 4.3.4). using normal type and data declarations.2) declares that a type is an instance of a class and includes the definitions of the overloaded operations—called class methods—instantiated on the named type. and default declarations (Section 4. defined on it.” We may then declare Int and Float to be instances of this class:     . 5].1) introduces a new type class and the overloaded operations that must be supported by any type that is an instance of that class.2). suppose we wish to overload the operations (+) and negate on types Int and Float. of the given types. © 4.1 Overview of Types and Classes Haskell uses a traditional Hindley-Milner polymorphic type system to provide a static type semantics [3.e. consisting of value bindings. whereas may be used either at the top level or in nested scopes (i. those within a let or where construct). and data declarations (Section 4. These “built-in” datatypes are described in detail in Section 6. instance. For example. An instance declaration (Section 4. type classes and overloading. consisting of type. type signatures.1.simplified class declaration for Num -. but the type system has been extended with type classes (or just classes) that provide a structured way to introduce overloaded functions. We introduce a new type class called Num: class Num a where (+) :: a -> a -> a negate :: a -> a -. . newtype.

However. The first declaration above may be read “Int is an instance of the class Num as witnessed by these definitions (i.1 Kinds To ensure that they are valid.simplified instance of Num Float x + y = addFloat x y negate x = negateFloat x where addInt. negateInt.2 Syntax of Types  ¨    %§ ->  %§ function type         %§ 8 8 ¥¥8 ¡ ¤      ¡ ¡ %§   %§  %§ ( [ ( . ) tuple type list type parenthesised constructor ¤  type application ¢ ©¡  ¢      ¤ ¡ ¨§6 ¦¡ ¢   ¡ If and are kinds.1. ¡   ¡ ¢   ¨   ¤ ¡ B%§   ¦  32 ¢ %§     ¡ ¤ ¡  ¡  %§  %§ ' '     The symbol represents the kind of all nullary type constructors. ] ) . addFloat. type expressions are classified into different kinds.1. unlike types.4. kinds are entirely implicit and are not a visible part of the language. ‘constructor class’ was used to describe an extension to the original type classes.simplified instance of Num Int x + y = addInt x y negate x = negateInt x instance Num Float where -. Kind inference is discussed in Section 4. OVERVIEW OF TYPES AND CLASSES 39 instance Num Int where -. is the kind of types that take a type of kind and return ¤ ¥¡     6 6 6 ¢ £¡           ¡ ¡  %§  %§ ¡  %§ ' ¢ .6.0 type system.1. but in general could be any user-defined function. then a type of kind .e. class methods) for (+) and negate. 4. and negateFloat are assumed in this case to be primitive functions. There is no longer any reason to use two different terms: in this report. 4.” More examples of type classes can be found in the papers by Jones [7] or Wadler and Blott [12]. 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. 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.

Double and Bool are type constants with kind . or newtype T . Since the IO type constructor has kind . Int. The tuple types are written as (. Most type constructors are written as an identifier beginning with an uppercase letter. The list type is written as [] and has kind . The declarations data T . For example: Char. Type variables. The main forms of type expression are as follows: 1. Special syntax is provided to allow certain type expressions to be written in a more traditional style: § § ¤ ¢ ¡ ¡ ¢ ¡ ¤   ¡ 6   ¤ ¡   6 ¢ ¡ 3. The function type is written as (->) and has kind . Integer. also written () (see Sections 3. A parenthesized type. to the variable a. IO. type synonyms. If is a type of kind type expression of kind .. As with data constructors. the names of type constructors start with uppercase letters. Use of the (->) and [] constants is described in more detail below. it follows that both the variable a and the whole expression. For example. a process of kind inference (see Section 4.9 and 6. must have kind .1. Type constructors. Maybe and IO are unary type constructors. then is a     6       6   6       6      6   () [] (->) (. Type application. © S¤ Special syntax is provided for certain built-in type constructors: The trivial type is written as () and has kind . and is a type of kind . Float.).5).6) is needed to determine appropriate kinds for user-defined datatypes.). having form ( ). The kind of T is determined by kind inference. (.40 CHAPTER 4. It denotes the “nullary tuple” type. written as identifiers beginning with a lowercase letter. add the type constructor T to the type vocabulary.. Just as data values are built using data constructors. and so on. the type expression IO a can be understood as the application of a constant. 4. Their kinds are . IO a. is identical to the type ... )      6   2§  $ § © ¦ ¤ ¤32    ¡  %§ ¤ ¡ ¢   ¡  ¦ 32 6      %§  6       6   6               ¦ 32   %§   unit type list constructor function constructor tupling constructors . DECLARATIONS AND BINDINGS The syntax for Haskell type expressions is given above. . infix type constructors are not allowed (other than (->)).. and treated as types with kind . 2. The kind of a variable is determined implicitly by the context in which it appears. type values are built from . . and so on. and has exactly one value. and classes. In general. Unlike data constructors.

the type expression a -> a . ¡§ £§ ¡§ v §   4. For clarity. then the expressions (\ -> ). and has the general form A $ A   8 8 ¥¥8 ¡ $ ¡   ( ) ¤ ¢  %§   ¦ ( )    ¦      A © © ( . For example. A tuple type has the form ( . and lists. []. A list type has the form [ ]. A function type has the form Function arrows associate to the right. however. 1.8 and 6. and ( ) have the types ( -> ). . A class assertion has form . A class identifier begins with an uppercase letter. the second component of type . ().).1.) Although the list and tuple types have special syntax.7 and 6. nor mentioned in import or export lists (Chapter 5). ) where . always denote the built-in type constructors. 2.) where there are commas between the parenthesis. It denotes the type of lists with elements of type (see Sections 3. )  £§ ¢ 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    %§   . A context consists of zero or more class assertions. . . for example. For example. above. “gtycon”. regardless of what is in scope. which is equivalent to the type [] . there is no explicit syntax for universal quantification [3]. These special syntactic forms always denote the built-in type constructors for functions. ( With one exception (that of the distinguished type variable in a class declaration (Section 4. and so on (see Sections 3.1. (. which is equivalent to the type (. means . tuples. we often write quantification explicitly when denotes the type discussing the types of Haskell programs. the type variables in a Haskell type expression are all assumed to be universally quantified.1)).4).. If is the type of expression or pattern .3. It denotes the type of -tuples with the first component of type . the scope of the extends as far to the right as possible.1. (Hence the special production. and so on. and indicates the membership of the type in the class . Notice that expressions and types have a consistent syntax. OVERVIEW OF TYPES AND CLASSES £§ ¡§ 41 £§ ¡§ -> .3 Syntax of Class Assertions and Contexts . the prefix type constructors (->). which is equivalent to the type (->) . . they cannot be qualified. [ ]. When we write an explicitly quantified type. In a similar way. Int -> Int -> Float means Int -> (Int -> Float). respectively. . their semantics is the same as the equivalent user-defined algebraic data types.1.4. 3. [ ].3). and ).

we provide informal details of the type system. £ ¢ 8 £ ¥ $  ¡§ t   $ ¡ ¢ 8 t $ The type substitution ¥ is more general than the type whose domain is such that: if and only if there is a § A $ A ¢    $ 8 8 ¥¥8   8 8 ¥¥8    ¡ $   ¢ ¡ $  ¢  ¢ v r$  $ § ¢    ¢  § ¢    A   ¢  8    $ 8 8 ¥¥8 ¢ ¥    ¡   £§     ¦   .4. For example. Haskell’s extended Hindley-Milner type system can infer the principal type of all expressions. respectively. although in this case the concrete syntax contains no =>.) The Haskell type system attributes a type to each expression in the program. we write => even if the context is empty. a type is of the form . Show a. and each of the is either a type variable. the universally-quantified type variables the context must be of the form given above in Section 4. Therefore. In general. here are some valid types: Eq a => a -> a (Eq a. up to the equivalence induced by the generalization preorder. as described in Section 4.42 CHAPTER 4. explicit typings (called type signatures) are usually optional (see Sections 3. also holds. the most general type. Functor f) => (a -> b) -> f a -> f b -> Bool In the third type. For example.16 and 4. including the proper use of overloaded class methods (although certain ambiguous overloadings could arise.3.1. consider the function double: §   if and only if the context     ¡ ¢ ¢  8 £ ¢ Whenever ¥   holds in the class environment. Types are related by a generalization preorder (specified below). in more detail. DECLARATIONS AND BINDINGS where are class identifiers. Eq b) => [a] -> [b] -> String (Eq (f a). that can be assigned to a particular expression (in a given environment) is called its principal type.  " t  ¡§ is identical to  . The type of an expression depends on a type environment that gives types for the free variables in . where is a set of type variables . In general. the constraint Eq (f a) cannot be made simpler because f is universally quantified. may be instantiated at types holds. £§   ¨ $   © ¢ © A value of type . (Wadler and Blott [12] and Jones [7] discuss type and constructor classes. we use to denote a context and we write => to indicate the type restricted by the context . 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). For convenience. Furthermore. The context must only contain type variables referenced in .1. The outer parentheses may be omitted when . In any such type. § § § 4. or the application of type variable to one or more types.1).3. any of that are free in must also be free in .4).4 Semantics of Types and Classes In this section.

The types of the data constructors are given by:    A § ¥¥8 ¡ !§ A A 8 8   $ 8 8 ¥¥8 ¡ $      6 ¡ ¡ ¢¢¡ ¤ v§   6 ¢¢¡ ¡ ¡ ¡§ 8 8 ¥¥8 ¡ ¡ § ¡ 6 ¡ @§ v   A       v ¢ $ 8 8 ¥¥8 8 8 ¥¥8 ¡  8     ¡ $   $ 8 8 ¥¥8 ¡   $ Q¥ §¦v ¥¥ ¢ data ¢  => = | | £ ¤   A © S©   ¡  8 8 ¥¥8 © ¡ S©    © S© deriving © ( . we describe algebraic datatypes (data declarations). USER-DEFINED DATATYPES double x = x + x 43 The most general type of double is Num . 4. in which case double may indeed be applied to a Char.2.4. because Char is not normally an instance of class Num. In this Report. . double may be applied to values of type Int (instantiating to Int).2 User-Defined Datatypes In this section. since Num Int holds.1 Algebraic Datatype Declarations ¨ #¦ §   § The precedence for is the same as that for expressions—normal constructor application has higher precedence than infix constructor application (thus a : Foo a parses as a : (Foo a)). double may not normally be applied to values of type Char. The user may choose to declare such an instance. }  3   %§ ¢ ¥ ¦  7   ! !  ¡ ¢ 7     ¦ ¦ 7 %§  ¡       %§ ¡  ¡   7  ¥ %§ ¦ ¦ 7 ¡ ¢ ¡ ¢   %§ ! ! arity infix ¦§ £  ¢ ¢   ¡ 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§   ¦ ©   . and type synonyms (type declarations). This declaration introduces a new type constructor with one or more constituent data constructors . ) ¦ § ¦   ¢ ¥ ¦ 7 A     ¢ ¥ ¦ 7   { ::   .2. renamed datatypes (newtype declarations). However. 4. These declarations may only appear at the top level of a module. An algebraic datatype declaration has the form: where is a context. because Int is an instance of the class Num. the unqualified term “constructor” always means “data constructor”. ! .

The context in the data declaration has no other effect whatsoever. the declaration data Eq a => Set a = NilSet | ConsSet a (Set a) In the example given. The visibility of a datatype’s constructors (i..3. }).6.8. 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. The optional deriving part of a data declaration has to do with derived instances. the overloaded type for ConsSet ensures that ConsSet can only be applied to values whose type is an instance of the class Eq.f2 :: Int. Constructors using field labels may be freely mixed with constructors without them.. For example. The arguments to the positional constructor occur in the same order as the labeled fields. and is described in Section 4.e. features using labels are simply a shorthand for operations using an underlying positional constructor. the “abstractness” of the datatype) outside of the module in which the datatype is defined is controlled by the form of the datatype’s name in the export list as described in Section 5.3. DECLARATIONS AND BINDINGS   is the largest subset of that constrains only those type variables free in the types . A constructor with associated field labels may still be used as an ordinary constructor. using the record syntax (C { . f3 :: Bool } defines 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 . This means that may be used in type expressions with anywhere between and arguments. These components are normally accessed positionally as arguments to the constructor in expressions or patterns. A constructor definition in a data declaration may assign labels to the fields of the constructor. the declaration data C = F { f1. This allows For large datatypes it is useful to assign a specific field to be referenced independently of its location within the constructor. to the components of a data object. 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 .44 ¢ v ¢ CHAPTER 4. Pattern matching against ConsSet also gives rise to an Eq a constraint. For example. Labelled Fields A data constructor of arity creates an object with components. The type variables through must be distinct and may appear in and the . For example: f (ConsSet a s) = a the function f has inferred type Eq a => Set a -> a. it is a static error for any other type variable to appear in or on the right-hand-side.

Lexically. whether or not F was declared with record syntax. replaces every occurrence of 8 8 ¥¥8 A 8 8 §© ¥¥8 ¡ ©   8 8 ¥¥8 $ 8 8 ¥¥8 ¡ $   ¢ data => = | | in an expression is the strict apply is not affected by 2       ¤  ¤ © ¡ ¦    6   6 8 8 ¥¥8   %¢  § 4§ © 7  ©¡ 2 § 7 ¥ ¦ ¡ ¡ 2 ¡   $ ¡ #  ¡ § § §   . . The pattern F {} matches any value built with constructor F.2 Type Synonym Declarations A type synonym declaration introduces a new type that is equivalent to an old type. v 2§ v © v © v ¢ £ 2  ¡ ¢ ¡ 2   ¤  %§ ¥¥8 ¡ ¤  %§ 32  8 8  ¦   ¢%§   %¢  ¢ 4 § ©   § ¡ ¡ ©¡ 7 A 8 8 3¢ ¥¥8 ¡ ¡ 6   ¡ ¢ (\ ->   2 v %§ ¡  3¢ A 2  ¥¥8  £ A 8 8 ¡ ¡ ¡ v @§  &  v 2§ 6 ¥¥8 8 8 ¨   $ #  § 6 ¢ ¡   v © where each by is either of the form ! or . Field names share the top level namespace with ordinary variables and class methods and must not conflict with other top level names in scope. A label cannot be shared by more than one type in scope. A data declaration may use the same field label in multiple constructors as long as the typing of the field is the same in all cases after type synonym expansion. Strictness Flags Whenever a data constructor is applied.4. USER-DEFINED DATATYPES data C = F Int Int Bool 45 Operations using field labels are described in Section 3.15. denoted by an exclamation point. Pattern matching on strictness flags. each argument to the constructor is evaluated if and only if the corresponding type in the algebraic datatype declaration has a strictness flag. For example. The type variables through must be distinct and are scoped only over . and function $! (see Section 6. “!”.2.2. the following definition 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 non-strict apply function $ if is of the form . The type is equivalent to the type .2) if is of the form ! . it has special significance only in the context of the argument types of a data declaration. Translation: A declaration of the form 4. 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. it is a static error for any other type variable to appear in .6. “!” is an ordinary varsym not a . It has the form § $ which introduces a new type constructor.

so that is the same as . the newtype constructor is unlifted. The constructor in an expression coerces a value from type to type ( ).17). type Rec a = [Rec a] is not allowed. A synonym and its definition are completely interchangeable. These coercions may be implemented without execution time overhead.2).3. DECLARATIONS AND BINDINGS Type constructor symbols introduced by type synonym declarations cannot be partially applied. type Rec a data Circ a is allowed.2.invalid = = [Circ a] Tag [Rec a]     is not. this is not so for type synonyms. whereas type Rec a type Circ a = = [Circ a] [Rec a] -. Also. Using in a pattern coerces a value from type ( ) to type . E       $ 8 8 ¥¥8 ¡ § § $     $ 8 8 ¥¥8 ¡ $   § E $ 8 8 ¥¥8 ¡ $   E ¢ newtype =>    A declaration of the form =  ¦ § ¢  ¤   ¢  %§    8 8 ¥¥8 ¡ ¤  %§ ¢¤  %§   { :: } ¤   ¤ § 332 © ¦ £   ¦    § %¢  4 § x¨ © § ¡  § ¢ ¡ ¦ 32 newtype   => = ¦    ¡ 7 ©¡  V  ¢ ¡  %§ E ¢ ¦ 32 §  ¦32 ¦ 32  %§   E    6 6 6 $ 8 8 ¥¥8 ¡   ¤ ¤32 § © ¦ ¡  § %¢  7 ¥ ¦ ¡ 7 ©¡ $    £   4§   © 2§ ¦ . A type created by newtype differs from an algebraic datatype in that the representation of an algebraic datatype has an extra level of indirection. newtype may be used to define recursive types. newtype does not change the underlying representation of an object. This difference may make access to the representation less efficient. The type ( ) renames the datatype . 4.invalid -. mechanism to make type signatures more readable. Type synonyms are a convenient. unlike type synonyms. Unlike algebraic datatypes. The difference is reflected in different rules for pattern matching (see Section 3. Similarly. unless an algebraic datatype intervenes. For example. but strictly syntactic. it is a static error to use without the full number of arguments.3 Datatype Renamings ¨   ¦§ § introduces a new type whose representation is the same as an existing type. except in the instance type of an instance declaration (Section 4.3. It differs from a type synonym in that it creates a distinct type that must be explicitly coerced to or from the original type. Although recursive and mutually recursive datatypes are allowed. New instances (see Section 4.2) can be defined for a type defined by newtype but may not be defined for a type synonym.46 type List = [] CHAPTER 4.

3 Type Classes and Overloading 4. In particular. though of course there may only be one field.4.3. . TYPE CLASSES AND OVERLOADING 47 The following examples clarify the differences between data (algebraic datatypes). ( n ( N ) ). A newtype declaration may use field-naming syntax. ) ¦ §  ¢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§ © © .1 Class Declarations ¨ 5©     A class declaration introduces a new class and the operations (class methods) on it. type (type synonyms). and newtype (renaming types. © ¥ } ¦ § ¦  A© §S©   4§ © 7   8 8 ¥¥8 ¦  ( . see Section 4.3.3. ( d2 ) and (d2 (D2 ) ) are all equivalent to .3. ( N ) is equivalent to while ( D1 ) is not equivalent to . Thus: newtype Age = Age { unAge :: Int } brings into scope both a constructor and a de-constructor: Age :: Int -> Age unAge :: Age -> Int                         4. A class declaration has the general form: ©   $   ¢ class => where ¦ 7 ¥ ¦  A   { . ( d1 ( D1 ) ) and ( s ) are all equivalent to 42. .) Given the declarations data D1 = D1 Int data D2 = D2 !Int type S = Int newtype N = N Int d1 (D1 i) = 42 d2 (D2 i) = 42 s i = 42 n (N i) = 42 the expressions ( d1 ). The optional deriving part of a newtype declaration is treated in the same way as the deriving component of a data declaration. whereas ( n ).

For example: class Foo a where op :: Num b => a -> b -> a v #¢  £ $ £ v ¨¢  £ $ $ $ v§ v  The may also contain a fixity declaration for any of the class methods (but for no other values). in which case the type of is polymorphic in both and . That is. i.3.2). the type variable is scoped only over the class method signatures in the class body. or another class method. because the left hand side of the default declaration is a pattern. they must not conflict with other top level bindings in scope. except that the left hand side may only be a variable or function definition. it must form a directed acyclic graph. the may not constrain . v B v # v  v @§ v ¢  v  © The type of the top-level class method The must mention . The default class method for is used if no binding for it is given in a particular instance declaration (see Section 4. However. The class methods of a class declaration are precisely the for which there is an explicit type signature :: => in . © 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. outside the class declaration. it may mention type variables other than . the fixity declaration for a class method may alternatively appear at top level. since class methods declare top-level values.. the may contain a default class method for any of the . The default method declaration is a normal value definition. The may constrain only . Lastly.e. The context specifies the superclasses of .48 CHAPTER 4. DECLARATIONS AND BINDINGS $ This introduces a new class name . whose scope extends outside the class declaration. op2) = . is not permitted. a field name. no other declarations are permitted in . Show a) => Textual a   Other than these cases.. a class method can not have the same name as a top level definition. as described below. For example: class Foo a where op1. in particular. the only type variable that may be referred to in is . op2 :: a -> a (op1. The superclass relation must not be cyclic. Class methods share the top level namespace with variable bindings and field names. For example: class (Read a. 6 7 ¥ ¦ 6   Foo Num   8 ¥ Here the type of op is © ¢ ' ¡ ¡   ¡ £ £ ¥ ¡ ¤¥ §¥ ¢  8  ¨ ©  § ¥   ¦ ¢ '   ¢  '   ¢ 7 ¥ ¦   v   7 ¥ ¦ 7 ¥ ¦         The   part of a class declaration contains three kinds of declarations: is:   $ ¢  ¢    7  ¦  . © The class declaration introduces new class methods .     .

and the must all be  $ 8 8 ¥¥8 ¡ $     1 ¢ instance => where { ¦ 2      ¢ class => where { }   £%§  ¡ 4   ¦ .. must take the form of a type constructor applied to simple . The type type variables distinct. this is legal.) For example.3. . it is not automatically an instance of the subclass. instance C [[a]] where .Ix T where range = . }  . in particular.a) where .3. since these have already v x$      $ 8 8 ¥¥8 ¡ $     $ where . TYPE CLASSES AND OVERLOADING 49 In such a case. Let  be a class declaration.2 Instance Declarations ¨ © }   § ¦ § © ©  %§  $ An instance declaration introduces an instance of a class. even though the subclass has no immediate class methods. 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§    §  ¦   § ¦ . if a type is an instance of all superclasses.4.range. module A where import qualified Ix instance Ix.2. The general form of the corresponding instance declaration is: This prohibits instance declarations such as: instance C (a.a) where . The declarations may contain bindings only for the class methods of . The declarations may not contain any type signatures or fixity declarations. furthermore.. (This rule is identical to that used for subordinate names in export lists — Section 5.. ] -> . even though range is in scope only with the qualified name Ix.. 4.. must not be a type synonym. it may be a qualified name... The instance declaration must be given explicitly with no where part. but the name under which it is in scope is immaterial.. It is illegal to give a binding for a class method that is not in scope.

The constraints expressed by the superclass context be satisfied. then the program would be invalid.. The following example illustrates the restrictions imposed by superclass instances: class Foo a => Bar a where .. A type may not be declared as an instance of a particular class more than once in the program. but it is nevertheless mandatory to write an explicit instance context.50 CHAPTER 4. In other words. instance (Eq a. must be an instance of each of . if such a default does not exist then the class method of this instance is bound to undefined and no compile-time error results.. The first instance declaration does indeed say that [a] is an instance of Foo under this assumption. DECLARATIONS AND BINDINGS been given in the class declaration.. Any constraints on the type variables in the instance type that are required for the class method declarations in to be well-typed must also be satisfied. the following two conditions must also be satisfied: 2. Since Foo is a superclass of Bar. In fact. Show a) => Bar [a] where . the second instance declaration is only valid if [a] is an instance of Foo under the assumption Num 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 C-T     $   1 ¢   8 8 ¥¥8 ¡  ¢  $      1 ¢ ¦ 1 ¢      . Assume that the type variables in the instance type satisfy the constraints in the instance context . If no binding is given for some class method then the corresponding default class method in the class declaration is used (if present). instance (Eq a. this can be determined using kind inference as described in Section 4..   The class and type must have the same kind.. This example is valid Haskell. the method declarations must take the form of a variable or function definition. instance Num a => Bar [a] where .. because Eq and Show are superclasses of Num.. The second instance declaration is valid only if [a] is an    ¨ $ #   $ 8 8 ¥¥8   1. As in the case of default class methods (Section 4. except in pathological cases it is possible to infer from the instance declaration the most general instance context satisfying the above two constraints. Show a) => Foo [a] where .3. If the two instance declarations instead read like this: instance Num a => Foo [a] where .6.1). Under this assumption...

Bounded. If the form is included. TYPE CLASSES AND OVERLOADING 51 instance of Foo under the assumptions (Eq a. For example.4. and Read. When deriving a class for a type . Ord. since [a] is only an instance of Foo under the stronger assumption Num a. It is also a static error to give an explicit instance declaration for a class that is also derived.4 Ambiguous Types. all mentioned in Figure 6. Classes defined by the standard libraries may also be derivable. then the expression let x = read ". The only classes in the Prelude for which derived instances are allowed are Eq. 4. For example. 4. instances for all superclasses of must exist for . because the types for show and read. not all datatypes can properly support class methods in Enum. If the deriving form is omitted from a data or newtype declaration. )   ¦ §    ¡   ¡   6 7 ¥ ¦ ¡   2§ ." in show x -. then derived instance declarations are automatically generated for the datatype in each of the named classes. Derived instances provide convenient commonly-used operations for user-defined datatypes. These instances are subject to the same restrictions as user-defined instances. Further examples of instance declarations may be found in Chapter 8. Enum. The precise details of how the derived instances are generated for each of these classes are provided in Chapter 10.3 Derived Instances As mentioned in Section 4. and Defaults for Overloaded Numeric Operations  ¦ A    %§ A problem inherent with Haskell-style overloading is the possibility of an ambiguous type. using the read and show functions defined in Chapter 10. data and newtype declarations contain an optional deriving form. omitting a deriving form is equivalent to including an empty deriving form: deriving (). that is. page 83. freeing the programmer from the need to define them. For example. Show a). including a specification of when such derived instances are possible. ¢ 6 6   ¢ 8 ¢ 8 ¥ §¥ ¥ ¥ §¥ ¥ show read Show Read String String ¢   ¢ 8 8 ¥¥8 ¢ ¡ ¢   %§ default ( . Show.2..1. But this does not hold. then no instance declarations are derived for that datatype. and supposing that just Int and Bool are members of Read and Show.3. derived instances for datatypes in the class Eq define the operations == and /=.invalid is ambiguous. A static error results if it is not possible to derive an instance declaration over a class named in a deriving form.3.3. either via an explicit instance declaration or by including the superclass in the deriving clause. ..1.

Such expressions are considered ill-typed. page 83. § ¢   . (that is. approxSqrt x = encodeFloat 1 (exponent x ‘div‘ 2) ‘asTypeOf‘ x (See Section 6. Num or a subclass of Num). It is a static error if no such type is found.1. an ambiguous type variable. shows the classes defined in the Prelude. In situations where an ambiguous type is discovered. ) where . For example. turns off all defaults in a module. rather than being given a fixed type with an expression type-signature. This is the purpose of the function asTypeOf (Chapter 8): ‘asTypeOf‘ has the value of . Double) The empty default declaration. is defaultable if:  ¢  ¢   at least one of these classes is a numeric class. the earlier expression involving show and read has an ambiguous type since its type Show Read String. but and are forced to have the same type.4. Such types are invalid. is Ambiguous types can only be circumvented by input from the user. Only one default declaration is permitted per module. default (). and its effect is limited to that module. for the ambiguous expression given earlier. § ¢ ¢   For example. For example. where is a class.6 for a description of encodeFloat and exponent. an otherwise ambiguous expression needs to be made the same type as some variable.16.      appears only in constraints of the form  . and Figure 6. and   all of these classes are defined in the Prelude or a standard library (Figures 6. 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 ( .2–6. in its type variable in that occurs in but not in . and 8 $ ¥ We say that an expression e has an ambiguous type if.)   Each defaultable variable is replaced by the first type in the default list that is an instance of all the ambiguous variable’s classes. pages 91– 92 show the numeric classes.. DECLARATIONS AND BINDINGS could be satisfied by instantiating a as either Int in both cases. or Bool. If no default declaration is given in a module then it assumed to be: default (Integer. one could write: let x = read "..52 CHAPTER 4. and each must be a type for which Num holds.) Ambiguities in the class Num are most common. a static error." in show (x::Bool) which disambiguates the type. One way is through the use of expression type-signatures as described in Section 3. Occasionally.3.

these declarations contain a static error. . such as  ¦ ¦ § ¢ § 6 ¢ ¢    A ¢  §   8 8 ¥¥8   ¢ 8  ¡  ¢ ¥ §¥ ¥ A §¤ v  ¢  . However.5. this is explained in Section 4.1. ¡ => ¡  V  © ¤ ¤ ¢ ¢   6 6 7 ¥ ¦   © S¤ ¦ ¥ ¢    .4.4. then each use of is treated as having the declared type. and hence the scope of a type variable is limited to the type signature that contains it. it is invalid to give a type signature for a variable bound in an outer scope. Indeed. then each use of outside its own declaration group (see Section 4. if we define sqr x = x*x 0 0 0 0 0 0 then the principal type is sqr Num . it is invalid to give more than one type signature for one variable. there is currently since x does not have type no way in Haskell to specify a signature for a variable with a dependent type.4 Nested Declarations The following declarations may be used in any declaration list.) If a given program includes a signature for a variable . It is a static error if the same type cannot also be inferred for the defining occurrence of . If a variable is defined without providing a corresponding type signature declaration.4. Moreover. or principal type .e.invalid    A type signature specifies types for variables.    %§ ¨ § S  § ¢ ¢ 8 ¦ 32 ¢ 8 8 ¥¥8 ¥ :: .2. as described in Section 4. every type variable appearing in a signature is universally quantified over that signature. possibly with respect to a context. A type signature has the form: :: => which is equivalent to asserting :: => for each from to . even if the signatures are identical. which allows applications such as sqr 5 or sqr 0.1.5. It is also valid to declare a more specific type. in the following declarations f :: a -> a f x = x :: a v B the a’s in the two type signatures are quite distinct. 4. including the top level of a module. For example. NESTED DECLARATIONS 53 4. to ensure that type inference is still possible. the defining occurrence. and all uses of within its declaration group must have the same monomorphic type (from which the principal type is obtained by generalization. For example.5) is treated as having the corresponding inferred. i. As mentioned in Section 4.1 Type Signatures  -. (The type of x is dependent on the type of f.2). Each must have a value binding in the same declaration list that contains the type signature.4.

54 sqr :: Int -> Int CHAPTER 4. The in a fixity declaration must be in the range to .and right-associativity (infix. If the is omitted. Any operator lacking a fixity declaration is assumed to be infixl 9 (See Section 3 for more on the use of fixities). infixl. fixity is not a property of that entity’s name.4. ¦  ¡ 2 ©¦ 2  &¤  2 A 2 ¡ ¥¥8 ¡ ¡ ¢ 2 8 8 ¡ ¡  2 ¨ ¥      § ¦ § %§ § ¢ ¤      6 6 6 6 7 ¥ ¦   ©  %§ § ¢ ¦ ¥  ¡ ¡2 2     . left. declares a property of a particular operator. Type signatures can also be used to support polymorphic recursion. Table 4. respectively). Type signatures such as sqr :: (Num a. just like its type. level 9 is assumed. and level 9 binds most tightly). (Class methods are a minor exception. DECLARATIONS AND BINDINGS but now applications such as sqr 0. 4. 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. For example: §§  § ¦ ¤       § ¦ §    ¦    infixl infixr infix . the type of f will be inferred as T Int -> Int due to the first recursive call for which the argument to f is T Int. T a -> a. non-. Polymorphic recursion allows the user to supply the more general type signature.1 are invalid.invalid -. and at most one fixity declaration may be given for any operator. . A fixity declaration may appear anywhere that a type signature appears and. Also like a type signature.) There are three kinds of fixity. and ten precedence levels. Num b) => a -> b sqr :: a -> a -.1 lists the fixities and precedences of the operators defined in the Prelude. as they are more general than the principal type of sqr. their fixity declarations can occur either in the class declaration itself or at top level. The following definition is pathological.invalid are invalid. Fixity is a property of a particular entity (constructor or variable). and infixr.2 Fixity Declarations © A fixity declaration gives the fixity and binding precedence of one or more operators. 0 to 9 inclusive (level 0 binds least tightly. like a type signature. a fixity declaration can only occur in the same sequence of declarations as the declaration of the operator itself.

op‘ b) + 1 f x = let p ‘op‘ q = (p ‘Foo..4. Here. module Foo where import qualified Bar infix 3 ‘op‘ a ‘op‘ b = (a ‘Bar. NESTED DECLARATIONS 55 Precedence 9 8 7 6 5 4 3 2 1 0 Left associative operators !! *. >>= $. ‘quot‘ +. ‘notElem‘ && || >>. ˆˆ. (It would also be possible to give a fixity to the nested definition of ‘op‘ with a nested fixity declaration. ++ ==. ‘Bar. - Non-associative operators Right associative operators . ‘mod‘.4.1: Precedences and fixities of prelude operators module Bar( op ) where infixr 7 ‘op‘ op = . <. /. ‘div‘..4.3 Function and Pattern Bindings © ¥     § ¤ 2 v  ¢£¡ § p v ¢ §e ¡ ¡ v © ¢ £¡ p v ¢ §e 2 § ¡ v £¡ p v ¢ 0e $ ¢  § ¡ ¢ ¡ £5¢ ¤  § ¤ ¢ £¡ ¤   ¡ v ¢ 2¢ &¤  v § £¡ ¢ ¤ ¡  ¢ ¡ v § £ 7¡ ¢ ¢ ¤ £ ¡ ¢ §      ¢ ¡ £5¢ © ¥ 7 ¦ $ £0 §     6 6 © ¥ 7 ¦ 7 ¥ ¦   $ 0 . ˆ.op‘ is infixr 7. and the nested definition of op in f’s right-hand side has the default fixity of infixl 9. ‘seq‘ Table 4.op‘ is infix 3.. /=. ‘elem‘.op‘ q) * 2 in . <=.. $!. ** :.) 4. ‘Foo. ‘rem‘. >. >=.

The set of patterns corresponding to each match must be linear—no variable is allowed to appear more than once in the entire set. these three function definitions 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 . For example. Alternative syntax is provided for binding functional values to infix operators. 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. .56 CHAPTER 4. the binding is called a function binding. DECLARATIONS AND BINDINGS We distinguish two cases within this syntax: a pattern binding occurs when the left hand side is a . and the number of patterns in each clause must be the same. ¤ 4. the latter.1 Function bindings A function binding binds a variable to a function value. The general form of a function binding for variable is: ¡ ¥ § ¥ §   or ¡   v ¡v   | | = Note that all clauses defining a function must be contiguous.3. otherwise.4. and where each is of the general form: } } A ¢ ¢ 4 4 v ¥ § 4  ¢ A ¥¥8 ¡ A 8 8   ¡ ¡   ¡ ¡ 8 8 ¥¥8 ¡ ¡ ¡ 8 8 ¥¥8 ¢ ¢ ¢ ¡  | ¨ © ¥ ¤   ¢ ¡  =     ¦ ¦   ¡   ¤ © ¥ ¡ ¢ ¡  = ¦   where where  9§ ¨© ¨ 7 © ¥ 7 ¥ ¦ § © ¥   ¡ ¦ $ £0 ¤ ( ) ¢ §¢  ¡ ¢ ¡ £5¢ 7 ¦     6 6 ¡ ¦ ¢ 6 © ¥ ¤ § © ¥ ¦ ¦     ¢ £¡ ¤ . Either binding may appear at the top-level of a module or within a where or let construct. namely: .

A simple pattern binding has form . A 4 ¡ A ( ) ¥ §  ¢ 4 A 8 8 ¥¥8     ¡   ¡ 8 8 ¥¥8 ¡ ¡ 8 8 ¥¡ ¥8 ¢ 8 8 ¥¥8 ¡ ¢ ¢ 8 8 ¥¥8 ¡ ¢ = \ ¢ -> case ( . as if there were an implicit ˜ in front of it. NESTED DECLARATIONS Translation: The general binding form for functions is semantically equivalent to the equation (i. in other words.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 .e.4. See the translation in Section 3. A note about syntax. a pattern binding is: is the same structure as for  ¡ ¥ §  ¢ ¥ §  ¢ 8 8 ¥¥8 4 ¡ ¡ 888 v ¢ where the are new identifiers. where a function bindings above. . It is usually straightforward to tell whether a binding is a pattern binding or a function binding. The pattern is matched “lazily” as an irrefutable pattern.3.4. simple pattern binding): ¡ ¥ § 57 4. but the existence of n+k patterns sometimes confuses the issue.2 Pattern bindings   A pattern binding binds variables to values.12. ) of ( )  ¢   ¡     ¡     ¡ ¡ .

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 Hindley-Milner inference rules. A dependency analysis transformation is first 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 defining 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 identifier bound in appears free in )
1

} in

A similar transformation is described in Peyton Jones’ book [10].

§

The first 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 Hindley-Milner type system assigns types to a let-expression in two stages. First, the righthand side of the declaration is typed, giving a type with no universal quantification. Second, all type variables that occur in this type are universally quantified 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 definition is . The generalization step attributes to g the polymorphic type , after which the typing of the “...” part can proceed. When typing overloaded definitions, 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 definition: 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 definitions 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 definition 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 definition: 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 simplified, 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 simplified 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 definition. 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 definition is ([ ] ). The ([ ] ); only can be universally generalization step attributes to g the type quantified 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 first 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 first 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 define 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 Hindley-Milner 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 non-simple 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

¢

¥

 

Rule 2 now states that the monomorphic type variable a is ambiguous. Hence. 63 Rule 2 is required because there is no way to enforce monomorphic use of an exported binding. Consequences The monomorphism rule has a number of consequences for the programmer. Consider module M where len1 = genericLength "Hello" len2 = (2*len1) :: Rational . (If the above code is actually what is wanted. However. len1 gets type Int. and must be resolved using the defaulting rules of Section 4.3. and not by any modules that import it. Double ) len1 = genericLength "Hello" module M2 where import M1(len1) len2 = (2*len1) :: Rational When type inference on module M1 is complete. in (f. There is no danger of recomputation here. Thus in f x y = x+y the function f may be used at any overloading in class Num. the user must be careful to affix these with type signatures to retain full overloading.4.5. len1 has the monomorphic type Num a => a (by Rule 1). STATIC SEMANTICS OF FUNCTION AND PATTERN BINDINGS The same constraint applies to pattern-bound functions. and its use in len2 is type-incorrect.4. The standard prelude contains many examples of this: sum sum :: (Num a) => [a] -> a = foldl (+) 0 Rule 1 applies to both top-level and nested definitions.) This issue does not arise for nested bindings. module M1(len1) where default( Int.(-)) both f and g are monomorphic regardless of any type signatures supplied for f or g. Rule 2 states that the exact types of all the variables bound in a module must be determined by that module alone. except by performing type inference on modules outside the current module. the same function defined with pattern syntax: f = \x -> \y -> x+y requires a type signature if f is to be fully overloaded. For example. because their entire scope is visible to the compiler. Anything defined with function syntax usually generalizes as a function is expected to. a type signature on len1 would solve the problem.g) = ((+). Many functions are most naturally defined using simple pattern bindings.

a synonym S and a class C. and classes within each group are determined using standard techniques of type inference and kind-preserving unification [7]. in such cases. This can be achieved in much the same way as the dependency analysis for value declarations that was described in Section 4. It is possible that some parts of an inferred kind may not be fully determined by the corresponding definitions. DECLARATIONS AND BINDINGS Here.5. and class definitions into dependency groups. respectively. respectively.64 CHAPTER 4. the parameter a appears as an argument of the function constructor (->) in the type of bar and hence must have kind . For example.     6   6     6   6 9     6        6 ¡ 6    6        6 ¡     6 9   6     6 ¡  ¡    ¡ ¡ . the actual kinds for these two constructors are and . to calculate a suitable kind for each type constructor and class appearing in a given program. for instance). and the type variable a is resolved to Rational when performing type inference on len2. in the definitions above. and instead generates a static error because the kind of []. constructors. For example. for any kind . i. 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. synonym. The first step in the kind inference process is to arrange the set of datatype. . For example. 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. 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. 4.6 Kind Inference This section describes the rules that are used to perform kind inference. and would require an extension to allow polymorphic kinds. For example. adding the following definition to those above does not influence the kind inferred for Tree (by changing it to . Instead.invalid This is important because it ensures that each constructor and class are used consistently with the same kind whenever they are in scope. a default of is assumed. the following program fragment includes the definition of a datatype constructor D.e. using the default binding . does not match the kind that is expected for an argument of Tree: type FunnyTree = Tree [] -. type inference finds that len1 has the monomorphic type (Num a => a). It follows that both D and S must have kind and that every instance of class C must have kind .

datatypes. Modules may be mutually recursive. type synonyms. default declarations scope over a single module (Section 4. The value of the program is the value of the identifier main in module Main.5) is affected by module boundaries. imported into. (see Chapter 4). A Haskell program is a collection of modules. and are not first class values. or class defined in. each giving the name of a module to be imported and specifying its entities to be imported. making them available to other modules. Modules are used for name-space control. etc. Rule 2 of the monomorphism restriction (Section 4... and its result (of type ) is discarded. When the program is executed.f module A where f = . and then concatenating all the module bodies1 . which must be a computation of type IO for some type (see Chapter 7). the computation main is performed. Second. Modules may reference other modules via explicit import declarations. A multi-module Haskell program can be converted into a single-module program by giving each entity a unique name. type. or perhaps exported from a module. We use the term entity to refer to a value. must be called Main and must export the value main. changing all occurrences to refer to the appropriate unique name. here is a three-module program: module Main where import A import B main = A. It is equivalent to the following single-module program: There are two minor exceptions to this statement. by convention. It exports some of these resources.f >> B.5.3. classes.Chapter 5 Modules A module defines a collection of values. For example. one of which... module B where f = . 1       65 . First.4). in an environment created by a set of imports (resources brought into scope from other modules).

.66 module Main where main = af >> bf af = . type synonyms. then the layout rule applies for the top level of the module. the header is assumed to be ‘module Main(main) where’. Section 5. . Chapter 4). data types. } } }  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 ¢ ¡  . . the module name. A module begins with a header: the keyword module. ( An abbreviated form of module.2 Export Lists  ¦ ¨ A§ ¤ !¤32 ¢ S  8 8 ¥¥8 ¡ ¤32 § ¤ ¢ ¡  ( . CHAPTER 5. with each module being associated with a unique module name (which are Haskell identifiers beginning with a capital letter. © 5. bf = . optionally restricting the imported bindings. This is followed by a possibly-empty list of top-level declarations . The header is followed by a possibly-empty list of import declarations ( . The name-space for modules themselves is flat.. plus a set of standard library modules that may be imported as required (see Part II). There is one distinguished module. MODULES Because they are allowed to be mutually recursive. classes.. modules allow a program to be partitioned freely without regard to dependencies. consisting only of the module body. . i. Prelude.. If the first lexeme in the abbreviated module is not a {.6). )   ¦ §   ¦ ¦    A   2§ 7 A ¥   ¦ ¡ 4 § ¡ 7 ¥ ¦ ¡ 8 8 ¥¥8 8 8 ¥¥8 .    7  ¦ © ¡   2§   © © 4§ ¡   2§ 7 ¥ ¦ ¡ 4 § ¡   7 ¥ ¦ § ¡ 32 ¦   2§ ¦ ¡ 4§ ¦ ¡ 4§ { { {  . which is imported into all modules by default (see Section 5.3) that specify modules to be imported. etc. (see Chapter 4).. is permitted. ¦ ¦ § 5. If this is used. .1 Module Structure A module defines a mutually recursive scope containing declarations for value bindings. ). and a list of entities (enclosed in round parentheses) to be exported.e.

For example.     ( . )  ¦ ¦§  ¦ ¦ §  ¢ ¢    ¢  ¡ ¢¨  ¦ ¦  § 2 4 ¦ 2  ¤     3¥ %§ ¦ 72  ¨  © ¡ ¨ ¤   ¢ ¢  %§         6 6   § ¤ ¤32 4 ¦ ¢ ¡ ¢ ¡   . 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 field names. The ability to export a type without its constructors allows the construction of abstract datatypes (see Section 5. EXPORT LISTS 67 . one of these subordinate names is legal if and only if (a) it names a constructor or field of . A type synonym is in scope.         3. and (b) the constructor or field is in scope in the module body regardless of whether it is in scope under a qualified or unqualified name. . A module implementation may only export an entity that it declares. Entities in an export list may be named as follows: 1. whether declared in the module body or imported. the (possibly-qualified) type constructor and field names in the second form are unqualified.     must be in scope. A value.) ( (.8). all values. ) An export list identifies the entities to be exported by a module declaration. types and classes defined in the module are exported. .. Operators be named by giving the name of the value as a s. A class with operations of three ways: 8 8 ¥¥8 ¢ The form names. where ¨ ¦ § ¨ A ¤  ¥¥8 ¡ ¤ 8 8 ¢ ¥¥8 ¢ A 5  4 ¦ ¡ ¢  4 ¦ 8 8 ¤ ¢ ¤ ¦ §   (. field name. Just ) ) where import qualified Maybe as Mb Data constructors cannot be named in export lists except as subordinate names. names the type and some or all of its constructors and field declared in a class declaration may be named in one  . because they cannot otherwise be distinguished from type constructors. The abbreviated form (. or class method. ¦ declared by a type declaration may be named by the form ¡     £ 8 8 ¥¥8 ¢ £ 4. which must be in scope.Maybe( Nothing. the following is legal module A( Mb. or that it imports from some other module. may . but not those that are imported.5.) ( module  . If the export list is omitted. The constructor In all cases.. ).) names the type and all its constructors and field names that are currently in scope (whether qualified or not).2. . should be enclosed in parentheses to turn them into   2..

Here the module Queue uses the module name Stack in its export list to abbreviate all the entities imported from Stack.1). It makes no difference to an importing module how an entity was exported. but there are name clashes in the export list   ¦ £ 8 8 ¥¥8 ¢ £ The form     ( .an invalid module There are no name clashes within module A itself. item (5)).f.. It is an error to use module M in an export list unless M is the module bearing the export list. In all cases. module Mod2 ) where import Mod2 import Mod3 Here module Mod1 exports all local definitions as well as those imported from Mod2 but not those imported from Mod3. For example: module Queue( module Stack. must be in scope. item(2)). because a local declaration brings into scope both a qualified and unqualified name (Section 5. For example: module Mod1( module Mod1. The form “module M” names the set of all entities that are in scope with both an unqualified name “e” and a qualified name “M. 5.. item (1) above). In the second form. For example. module B ) where import B(f) import qualified C(f. MODULES The abbreviated form (. names the class and some or all of its methods.).   ¡ £ . dequeue ) where import Stack .g) g = f True -. or by exporting an entire module (module M. For example module A ( C.g. C. ). . or as an implicitly-named member (T(. This set may be empty.68 CHAPTER 5.. item (2)).) names the class and all its methods that are in scope (whether qualified or not). 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.5. one of the (unqualified) subordinate names is legal if and only if (a) it names a class method of . The unqualified names of the entities exported by a module must all be distinct (within their respective namespace).. or as an explicitly-named member of its data type (T(f).e”. A module can name its own local definitions in its export list using its own name in the “module M” syntax. and (b) the class method is in scope in the module body regardless of whether it is in scope under a qualified or unqualified name. a field name f from data type T may be exported individually (f. enqueue. or M is imported by at least one import declaration (qualified or unqualified). g. ¡   ¦ The form   names the class but not the class methods.

5. ) ¨ ¨ A 5  4 ¦ ¢¥¥8 8 8 ¡ ¢  ¡ ¤ 4 ¦ ¢ (.) refers to all of the constructors. or field names exported from the module. The ordering of import declarations is irrelevant. IMPORT DECLARATIONS 69 between C. . and between module B and C. Items in the list have the same form as those in export lists. Imported names serve as top level declarations: they scope over the entire body of the module but may be shadowed by local non-top-level bindings.3. )  ¦ ¨ A !§ ¤ ¦ §     ¦ ¦§  ¦ 2 § § ¤   %§     4 ¢ ¢ ¥ ¦ 7 ¨¡    © 4 § ¨ § 2 4  ¡ ¡   ¦ ¦ . . hiding ( . The imported entities can be specified explicitly by listing them in parentheses. modules can import each other recursively). When the (. methods.) form of import is used for a type or class. The import declaration names the module to be imported and optionally specifies the entities to be imported... § 5. except qualifiers are not permitted and the ‘module ’ entity is not permitted. they may also be used as variables. ¨¡ 8 8 ¥¥8 A§ ¤ 2 4§ ¢ ¡ §¤¤32 4 § 8 8¡ ¥¥8 ¡§ ¤ 2  ( .1 What is imported Exactly which entities are to be imported can be specified in one of the following three ways: 1.g and g are different entities – remember.   2 4 ¨ import qualified as . )  ¦ ¦§   ¦ ¦ §  ¢  2 4§ ..f are different entities).) (  . 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.. The list may be empty. .g and g (assuming C. 5. )   ¦ ¦ ¡     ¦ 2  ¤      37 2 ¦ ¡ © 4§ ¤  ¢ ¢  %§  %§ 2 4       6 6 6 6 ¦ ¦ §        ¤ © 7    §      © ¤ 32 ¡ ¡ 4 ¦ ¢ ¡ ¤ ¦ ¡ 4§ 4§ 4§  .) ( (.3. the terminal symbols “as”. The list must name only entities exported by the imported module. rather than Lexically. ¦ ¦ § ¦ ¤ ¢  A¤  8 8 ¥¥8 .f (assuming B. in which case nothing except the instances is imported.f and C.3 Import Declarations § The entities exported by a module may be brought into scope in another module with an import declaration at the beginning of the module. They have special significance only in the context of an import declaration. A single module may be imported by more than one import declaration. the (. “qualified” and “hiding” are each a a .

If the qualified keyword is omitted. then both the qualified and unqualified name of the entity is brought into scope.   ©  5.++ l2 l1 * l2 = nub (l1 + l2) succ = (Prelude. the qualifier is not necessarily the name of the module in which the entity was originally declared. The qualifier on the imported name is either the name of the imported module. If the import declaration used the qualified keyword. ). is omitted then all the entities exported by the specified module are im- A !§ ¤ 2 ¡ 4§ 8 8 ¥¥8 ¡ 4§ ¡ ¡ . Section 5.3.2 Qualified import For each entity imported under the rules of Section 5. only the qualified name of the entity is brought into scope. This also allows a different module to be substituted for VeryLongModuleName without changing the 4§ 3. In contrast.3.3. in import M hiding (C) any constructor.’.1 describes qualified names in more detail. if ported. It is an error to hide an entity that is not.5. which specifies that all entities exported by the named module should be imported except for those named in the list. For example. Finally. Hence. the top-level environment is extended. or the local alias given in the as clause (Section 5.+ 1) -. Thus. in fact. MODULES 2.1.This * differs from the one in the Prelude 5.3) on the import statement.3.All Prelude names must be qualified -. using C in an import list names only a class or type. Data constructors may be named directly in hiding lists without being prefixed by the associated type. exported by the imported module. in import qualified VeryLongModuleName as C entities must be referenced using ‘C. or type named C is excluded.This + differs from the one in the Prelude -.70 ¡ ¤32 § ¤ CHAPTER 5. class. The ability to exclude the unqualified names allows full programmer control of the unqualified namespace: a locally defined entity can share the same name as a qualified import: module Ring where import qualified Prelude import List( nub ) l1 + l2 = l1 Prelude.3 Local aliases Imported modules may be assigned a local alias in the importing module using the as clause. Entities can be excluded by using the form hiding( .’ as a qualifier instead of ‘VeryLongModuleName. .

All instances in scope within a module are always exported and any import brings all instances in from the imported .x x. A.f This module is legal provided only that Foo and Baz do not both export f. A. IMPORTING AND EXPORTING INSTANCE DECLARATIONS 71 qualifiers used for the imported module. A.4).y (nothing) x. B.x.x.x. y.y A. It is legal for more than one module in scope to use the same qualifier.4 Examples To clarify the above import rules.y (nothing) A. B. A.x. An as clause may also be used on an un-qualified import statement: import Foo as A(f) This declaration brings into scope f and A. y. Then this table shows what names are brought into scope by the specified import statement: Import declaration import A import A() import A(x) import qualified A import qualified A() import qualified A(x) import A hiding () import A hiding (x) import qualified A hiding () import qualified A hiding (x) import A as B import A as B(x) import qualified A as B Names brought into scope x. A. provided that all names can still be resolved unambiguously.y y.x. 5. all instance declarations in scope in module A are imported (Section 5.x B.y In all cases.y x.3.y x. For example: module M where import qualified Foo as A import qualified Baz as A x = A. y.x A. A.f. 5. suppose the module A exports x and y.5.y A.4 Importing and Exporting Instance Declarations Instance declarations cannot be explicitly named on import or export lists.x.4. B. A. B. A.

f x x is legal.3). it is illegal to write module M where M. 4 ¦ ¢ ¦ ¦ (Section 2. import M() does not bring any new names in scope from module M. always brings into scope the qualified name of the imported entity (Section 5. whether qualified or not.. MODULES module. Thus.5.. therefore. Thus:   module M where f x = .. A top-level declaration brings into scope both the unqualified and the qualified name of the entity being defined..f. -. -. it must be possible unambiguously to resolve which entity is thereby referred to.. g x = M. there must be only one binding for f or A.ILLEGAL By an import declaration.5 Name Clashes and Closure 5.4).5.   5.f respectively. For example.1 Qualified names   § By a top level declaration.y = x+1 in . an instance declaration is in scope if and only if a chain of import declarations leads to the module containing the instance declaration.2 Name clashes If a module contains a bound occurrence of a name. that is.f x = . This allows a qualified import to be replaced with an unqualified one without forcing changes in the references to the imported names.. A qualified name is brought into scope: . but does bring in any instances visible in M. 2 4 A qualified name is written as .72 CHAPTER 5. For example module MyInstances() where instance Show (a -> b) where show fn = "<<function>>" instance Show (IO a) where show io = "<<IO action>>" 5. such as f or A. The defining occurrence must mention the unqualified name.ILLEGAL g x = let M. A module whose only purpose is to provide instance declarations can have an empty export list. An import declaration.

c = ... b. For example.sin x) The local declaration for sin is legal. NAME CLASHES AND CLOSURE 73 It is not an error for there to exist names that cannot be so resolved. and C.. module D( d ) where d = .. x.d. y = . c... . b = . y ) where import D x = . The ambiguity could be fixed by replacing the reference to x by B. The name occurring in a type signature or fixity declarations is always unqualified. or x declared in C.2). provided that the program does not mention those names.. The reference to x is ambiguous: it could mean x declared in B. y ) where import D x = ..         The reference to d is unambiguously resolved to d declared in D.x. 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. even though the Prelude function sin is implicitly in scope..x or C.. For example: module A where import B import C tup = (b. module C( d. The references to b and c can be unambiguously resolved to b declared in B.. and can be referred to in A by the names d. c.sin (F. d..4. x) module B( d.. There is no reference to y.5. and c declared in C respectively.d. and unambiguously refers to another declaration in the same declaration list (except that the fixity declaration for a class method can occur at top level — Section 4. y = . In this case the same entity is brought into scope by two routes (the import of B and the import of C). Consider the definition of tup.. the following module is legal: module F where sin :: Float -> Float sin x = (x::Float) f x = Prelude.5. B. x.

the definition of T is available to any module that encounters it whether or not the name T is in scope. called the “Standard Prelude. every name explicitly mentioned by the source code must be either defined locally or imported from another module. 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. For example. That is. entities that the compiler requires for type checking or other compile time analysis need not be imported if they are not mentioned by name. the type checker finds the definition of T if needed whether or not it is exported.74 CHAPTER 5.sin must both be qualified to make it unambiguous which sin is meant. The only reason to export T is to allow other modules to refer it by name.6 Standard Prelude Many of the features of Haskell are defined in Haskell itself as a library of standard datatypes. MODULES The references to Prelude. these are interchangeable even when T is not in scope. The Haskell compilation system is responsible for finding any information needed for compilation without the help of the programmer. However.3 Closure Every module in a Haskell program must be closed. The type of an exported entity is unaffected by non-exported type synonyms.5. 5. module M2 knows enough about T to correctly type check the program. That is. the unqualified name sin in the type signature in the first line of F unambiguously refers to the local declaration for sin. in module M(x) where type T = Int x :: T x = 1 the type of x is both T and Int. That is. However. classes. 5. there is no way to supply an explicit type signature for y since T is not in scope. 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. the Prelude is contained in the . and functions.” In Haskell. Whether or not T is explicitly exported.sin and F.

This means. and contains an unqualified reference to null on the right hand side of nonNull. 5.2 Shadowing Prelude Names The rules about the Prelude have been cast so that it is possible to use Prelude names for nonstandard purposes. they are not formally defined in Chapter 8. STANDARD PRELUDE 75 module Prelude. Prelude and library modules differ from other modules in that their semantics (but not their implementation) are a fixed part of the Haskell language definition. The latter would be ambiguous without the hiding(null) on the . arrays. and most of the input/output are all part of the standard libraries.6. nonNull ) where import Prelude hiding( null ) null. They are simply there to help explain the structure of the Prelude module. Chapter 8 defines the module Prelude using several other modules: PreludeList. for example. For example: module A( null. not part of the language definition. just like those from any other module. they should be considered part of its implementation. These are defined in Part II Separating libraries from the Prelude has the advantage of reducing the size and complexity of the Prelude.6. The implementation of Prelude is also incomplete in its treatment of tuples: there should be an infinite family of tuples and their instance declarations. Since the treatment of such entities depends on the implementation. if and only if it is not imported with an explicit import declaration. Some datatypes (such as Int) and functions (such as Int addition) cannot be specified directly in Haskell. that a compiler may optimize calls to functions in the Prelude without consulting the source code of the Prelude. This provision for explicit import allows entities defined in the Prelude to be selectively imported. but the implementation only gives a scheme. every module that does so must have an import declaration that makes this nonstandard usage explicit.1 The Prelude Module The Prelude module is imported automatically into all modules as if by the statement ‘import Prelude’. 5. There are also many predefined library modules. which provide less frequently used functions and types. and so on. For example.6. given in Chapter 8. PreludeIO.5. however. nonNull :: Int -> Bool null x = x == 0 nonNull x = not (null x) Module A redefines null. complex numberss. The semantics of the entities in Prelude is specified by a reference implementation of Prelude written in Haskell. and they cannot be imported separately. and increasing the space of useful names available to the programmer. allowing it to be more easily assimilated. These modules are not part of Haskell 98.

Other than the fact that it is implicitly imported. it is special only in that some objects in the Prelude are referenced by special syntactic constructs. The special syntax for tuples (such as (x. so it refers to ++ imported from MyPrelude. separate compilation of mutually recursive modules may require that imported modules contain additional information so that they may be referenced before they are compiled. The precise details of separate compilation are not defined by this report. for example. 5. an ADT for stacks could be defined as: module Stack( StkType. in module B where import Prelude() import MyPrelude f x = (x.76 CHAPTER 5. For example. pop. For example. Explicit type signatures for all exported values may be necessary to deal with mutual recursion. the Prelude is an ordinary Haskell module. MODULES import Prelude statement.8 Abstract Datatypes The ability to export a datatype without its constructors allows the construction of abstract datatypes (ADTs). It is possible to construct and use a different module to serve in place of the Prelude. to hide instance declarations in the Prelude.)) and lists (such as [x] and []) continues to refer to the tuples and lists defined by the standard Prelude. On the other hand. and then makes an unqualified reference to null must also resolve the ambiguous use of null just as A does. however. push. 5. there is no way to redefine the meaning of [x]. It is not possible. empty ) where data StkType a = EmptyStk | Stk a (StkType a) push x s = Stk x s pop (Stk _ s) = s empty = EmptyStk .7 Separate Compilation Depending on the Haskell implementation used. Thus there is little danger of accidentally shadowing Prelude names. For example.x) and (. in terms of a different implementation of lists.) x x h x = [x] ++ [] the explicit import Prelude() declaration prevents the automatic import of Prelude. the use of ++ is not special syntax. while the declaration import MyPrelude brings the non-standard prelude into scope. one cannot define a new instance for Show Char. Redefining names used by the Prelude does not affect the meaning of these special constructs.x) g x = (. Every module that imports A unqualified.

stacks can be defined with lists: module Stack( StkType. pop. 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. pop. and empty to construct such values. For example. they must use push. Instead. ABSTRACT DATATYPES 77 Modules importing Stack cannot construct values of type StkType because they do not have access to the constructors of the type. push.5.8.

78 CHAPTER 5. MODULES .

Bounded) The boolean type Bool is an enumeration. Most functions are not described in detail here as they can easily be understood from their definitions as given in Chapter 8.1. the Haskell definition of the type is given. Some definitions may not be completely valid on syntactic grounds but they faithfully convey the meaning of the underlying type. Ord. Show. The basic boolean functions are && (and).1. Show.1 Booleans data Bool = False | True deriving (Read. The name otherwise is defined as True to make guarded expressions more readable. types. Ord.Chapter 6 Predefined Types and Classes The Haskell Prelude contains predefined classes. 6. and 79 .4.2 Characters and Strings The character type Char is an enumeration whose values represent Unicode characters [11]. complex numbers. and rationals are defined in Part II. character literals are nullary constructors in the datatype Char. and functions that are implicitly imported into every Haskell program. Enum. || (or). In this chapter. The lexical syntax for characters is defined in Section 2. Enum. Eq. Other predefined types such as arrays. Numeric types are described in Section 6.1 Standard Haskell Types These types are defined by the Haskell Prelude. 6. and not. Eq.6. we describe the types and classes found in the Prelude. 6. When appropriate. Type Char is an instance of the classes Read.

y) and (.’r’. \t and \HT. Ord. (Int. \b and \BS.Int) and (. The Prelude and libraries define tuple functions such as zip for tuples up to a size of 7. curry. respectively. The module PreludeList (see Section 8. Show.1) defines many standard list functions. There is no upper bound on the size of a tuple. map characters to and from the Int type. and the second is ‘:’ (“cons”). thus. The same holds for tuple type constructors.11.) Int Bool Int denote the same type. Bounded. Read. there are the following equivalences: \a and \BEL. and MonadPlus. Monad. .’n’.’s’. All tuples are instances of Eq. two convenient syntaxes for special kinds of lists. 6.’t’. Arithmetic sequences and list comprehensions. A string is a list of characters: type String = [Char]   Strings may be abbreviated using the lexical syntax described in Section 2. Note that ASCII control characters each have several representations in character literals: numeric escapes. The first constructor is the null list. \v and \VT. The constructor for a tuple is written by omitting the expressions surrounding the commas. but some Haskell implementations may restrict the size of tuples.4 Tuples Tuples are algebraic datatypes with special syntax. The following functions are defined for pairs (2-tuples): fst.Bool. every Haskell implementation must support tuples up to size 15. snd. Similar functions are not predefined for larger tuples.’ ’. Lists are an instance of classes Read. ’i’. and uncurry. Ord. Bounded.10 and 3. as defined in Section 3. For example. Ord. "A string" abbreviates [ ’A’. \f and \FF. and the \ˆ notation. and limit the instances associated with larger tuples. and Show. The toEnum and fromEnum functions. thus (x. Functor. as described in Section 3.6. written ‘[]’ (“nil”). and \n and \LF..’g’] 6. standard functions from class Enum.) x y produce the same value. Read. and Show (provided. although with special syntax. \r and \CR.80 CHAPTER 6. However. Eq. Ord) Lists are an algebraic datatype of two constructors. together with the instances for Eq. of course. ASCII mnemonic escapes. that all their component types are).1. Each tuple type has a single constructor.8.3 Lists data [a] = [] | a : [a] deriving (Eq.7. are described in Sections 3.1. PREDEFINED TYPES AND CLASSES Bounded. In addition.

1. 6. Ord. Show) member.   The unit datatype () has one non- 6. a function argument is evaluated only when required. flip. Read. 6. using the seq function: seq :: a -> b -> b . Ord.7 The IO and IOError Types The IO type serves as a tag for operations (actions) that interact with the outside world. and Part II contains many more. IO is an instance of the Monad and Functor classes. Bounded. Read.8 Other Types data data data Maybe a Either a b Ordering = = = Nothing | Just a deriving (Eq. The following simple functions are found in the Prelude: id.6 Function Types Functions are an abstract type: no constructors directly create functional values. const.1. ($).). Enum.2. Enum. The Ordering type is used by compare in the class Ord. the nullary constructor (). STRICT EVALUATION 81 6.2 Strict Evaluation Function application in Haskell is non-strict.5 The Unit Datatype data () = () deriving (Eq. Sometimes it is desirable to force the evaluation of a value. Ord. The Prelude contains a few I/O functions (defined in Section 8. Bounded. (. Values of this type are constructed by the various I/O functions and are not presented in any further detail in this report. that is. Show) LT | EQ | GT deriving (Eq. Ord. Chapter 7 describes I/O operations. See also Section 3. Show) Left a | Right b deriving (Eq. 6. Read. Monad. It is an instance of Show and Eq. Read.1. The functions maybe and either are found in the Prelude.6.3).1. and until. IOError is an abstract type representing errors raised by I/O operations. The IO type is abstract: no constructors are visible to the user.9. Show) The Maybe type is an instance of classes Functor. and MonadPlus.

then all class methods must be given to fully specify an instance. the provision of seq has is important semantic consequences. PREDEFINED TYPES AND CLASSES The function seq is defined by the equations: seq is usually introduced to improve performance by avoiding unneeded laziness. so it sometimes allows parentheses to be omitted.1 The Eq Class class Eq a where (==).1) are defined in terms of the $! operator. or zipWith ($) fs xs. As a consequence. Strict datatypes (see Section 4.82 CHAPTER 6. right-associative binding precedence. ($!) :: (a -> b) -> a -> b f $ x = f x f $! x = x ‘seq‘ f x The non-strict application operator $ may appear redundant. The operator $! is strict (call-by-value) application. $ has low. for example: f $ g $ h x = f (g (h x))     It is also useful in higher-order situations. Default class method declarations (Section 4. $! ($). together with the default declarations.3. A comment with each class declaration in Chapter 8 specifies the smallest collection of method definitions that.1 shows the hierarchy of Haskell classes defined in the Prelude and the Prelude types that are instances of these classes.2. since ordinary application (f x) means the same as (f $ x).3 Standard Haskell Classes Figure 6. 6.3) are provided for many of the methods in standard classes. the not the same as \x -> existence of seq weakens Haskell’s parametricity properties. and is defined in terms of seq. such as map ($ 0) xs. . For the same reason. However. (/=) :: x /= y x == y a -> a -> Bool = not (x == y) = not (x /= y)     ¡¢ 0§   '   ' ¢ seq seq   '   . 6. The Prelude also defines the $ operator to perform non-strict application. If there is no such comment. infixr 0 $. However. since seq can be used to distinguish them. because it is available at every type. provide a reasonable definition for all the class methods.

Maybe Figure 6. Double Fractional Float.6. []. IOError Num Int. Float. Bool. Double Monad IO. Ordering.3. Maybe Functor IO.1: Standard Haskell Classes . Double RealFloat Float. () Ordering. Double Real Int. STANDARD HASKELL CLASSES 83 Eq All except IO. Char. Integer. (->) Ord All except (->) IO. Char. Bool. (->) Show All except IO. Double Bounded Int. Double Floating Float. Float. (->) Read All except IO. Float. Integer RealFrac Float. Int. Integer. Double Integral Int. []. Integer. tuples Enum ().

84 CHAPTER 6. (>=). = = = = max x y) = (x.x) y x x y The Ord class is used for totally ordered datatypes. The Ordering datatype allows a single comparison to determine the precise ordering of two objects. The declared order of the constructors in the data declaration determines the ordering in derived Ord instances. This declaration gives default method declarations for both /= and ==. The default declarations allow a user to create an Ord instance either with a type-specific compare function or with type-specific == and <= functions. neither default method is used.3. IO. Instances of Eq can be derived for any user-defined datatype whose constituents are also instances of Eq. and IOError. If both are defined.2 The Ord Class class (Eq a) => Ord a where compare :: a -> a -> Ordering (<). If one is defined. Instances of Ord can be derived for any user-defined datatype whose constituent types are in Ord. . each being defined in terms of the other. If an instance declaration for Eq defines neither == nor /=. All basic datatypes except for functions and IO are instances of this class.y) or (y. (>) :: a -> a -> Bool max. 6. are instances of this class. 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 -. then both will loop. PREDEFINED TYPES AND CLASSES The Eq class provides equality (==) and inequality (/=) methods. (<=).Note that (min x max x y | x <= y | otherwise min x y | x <= y | otherwise y. the default method for the other will make use of the one that is defined. All basic datatypes except for functions.

is also provided. 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.read: no parse" _ -> error "PreludeText.t) <. The method showList is provided to allow the programmer to give a specialised way of showing lists of values. by providing an instance declaration. which uses precedence context zero. default decl for showList given in Prelude The Read and Show classes are used to convert values to or from strings. showsPrec and showList return a String-to-String function.3 The Read and Show Classes type type ReadS a = String -> [(a.. a programmer can easily make functions and IO types into (vacuous) instances of Show...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 "" -. ("". and returns an ordinary String. STANDARD HASKELL CLASSES 85 6. This is particularly useful for the Char type.. The Int argument to showsPrec and readsPrec gives the operator precedence of the enclosing context (see Section 10. A specialised variant.String)] ShowS = String -> String class Read a where readsPrec :: Int -> ReadS a readList :: ReadS [a] -. where values of type String should be shown in double quotes. Derived instances of Read and Show replicate the style in which a constructor is declared: infix constructors and field names are used on input and output.. rather than between square brackets.3. to allow constant-time concatenation of its results using function composition.4). are instances of Show and Read. All Prelude types.6.reads s.. Strings produced by showsPrec are usually readable by readsPrec."") <. (If desired.lex t] of [x] -> x [] -> error "PreludeText.3. except function types and IO types.) For convenience. show.

The function lex :: ReadS String.. is also part of the Prelude. toEnum 7 :: Bool is an error. respectively. 6. methods are used when translating arithmetic sequences (Section 3. lex returns a single successful “lexeme” consisting of the empty string. discarding initial white space. (Thus lex "" = [("". of a value.. The read function reads input from a string. which must be completely consumed by the input process.) If there is no legal lexeme at the beginning of the input string. The functions succ and pred return the successor and predecessor.       fromEnum and toEnum should give a runtime error if the result value is not representable in the result type. and returning the characters that constitute the lexeme.m] [n. The enumFrom. It reads a single lexeme from the input.e.n’.10). PREDEFINED TYPES AND CLASSES shows and reads use a default precedence of 0.] [n.. The functions fromEnum and toEnum map values from a type in Enum to and from Int. enumFrom and enumFromThen should be defined with an implicit bound..m] -.3. If the input string contains only white space.. lex fails (i. pred :: toEnum :: fromEnum :: enumFrom :: enumFromThen :: enumFromTo :: enumFromThenTo :: a -> a Int -> a a -> Int a -> [a] a -> a -> [a] a -> a -> [a] a -> a -> a -> [a] ----- [n.4 The Enum Class class Enum a where succ. For example.Default declarations given in Prelude Class Enum defines operations on sequentially ordered types. used by read..86 CHAPTER 6. see Chapter 10."")]. 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: .n’. Instances of Enum may be derived for any enumeration type (types whose constructors have no fields).] [n. the following should hold: The calls succ maxBound and pred minBound should result in a runtime error. returns []). For any type that is an instance of class Bounded as well as Enum.

For the types Int and Integer. and Ordering. the digits after the decimal point may be lost.3. Lists. . where the increment. all of the enumFrom family of functions are strict in all their arguments.   £   ¡     ¥ ¤  § £   £ ¤¡ § ]. the semantics of the enumFrom family is given by the rules for Int above. For example. all the list elements are the same. For all four of these Prelude numeric types. . . If the increment is zero. . except that the list terminates when the elements become greater than for positive increment . [LT. the list terminates when . 8 8 ¥¥8 ¤   § §   ¢¥ 8 8 ¥¥8 ¤ ¥   ¥ ¢    ¡ ¢¢    £ ¥¡ §   ¡ ¡¤    ¡ ¡¢    § ¡     ¡ ¢¤  ¡ ¢  ¤   § ¥ ¤  £   ¡   ¥     ¡¥   ¥ ¤  ¡   The sequence enumFromTo .5 The Functor Class class Functor f where fmap :: (a -> b) -> f a -> f b The Functor class is used for types that can be mapped over. ¥ ¢  The sequence enumFromThenTo is the list [ . the list is empty if negative. . empty if is the list [ . If the increment is positive or zero.GT]. 8 8 ¥¥8 § ¤ ¤   ¡ ¡¢  8 8 ¥¥8 §   ¢¢  ¡   ¡ ¡¢  ¡ ¢    ¡ ¡¢  ¡   £   ¡   ¡   ¡ ¤  The sequence enumFrom is the list [ . and pred subtracts 1. Integer.] is the list [LT. and Maybe are in this class. . is . . In the case of Float and Double. It is implementation-dependent what fromEnum returns when applied to a value that is too large to fit in an Int.EQ. ¤  . or when they become less than for negative . The semantics of these instances is given next. succ adds 1. IO. . STANDARD HASKELL CLASSES   87 Enumeration types: ().3. Double. enumFromTo ’a’ ’z’ denotes the list of lowercase letters in alphabetical order. Float. 6. The list is   ¥   § ¦ §   . Bool. based on the primitive functions that convert between a Char and an Int. ]. ¥ ¢  For Float and Double. the list is empty if . is . the list terminates when the next element would be less than . ]. If the increment is the next element would be greater than ..6. The conversions fromEnum and toEnum convert between the type and Int. Char: the instance is given in Chapter 8. The semantics of these instances is given by Chapter 10. The increment may be zero or negative. the enumeration functions have the following meaning: The sequence enumFromThen is the list [ . . For example.             Numeric types: Int. ]. For all four numeric types. where the increment.

g) id fmap f .14). 6. lists. In the Prelude.3). and IO are all instances of Monad.3. See Chapter 7 for more information about monads. Instances of Monad should satisfy the following laws: Instances of both Monad and Functor should additionally satisfy the law: All instances of Monad defined in the Prelude satisfy these laws. The fail method is invoked on pattern-match failure in a do expression.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 defines the basic operations over a monad. fmap g k a m (m >>= k) >>= h . Maybe. PREDEFINED TYPES AND CLASSES Instances of Functor should satisfy the following laws: All instances of Functor defined in the Prelude satisfy these laws. The fail method for lists returns the empty list []. for Maybe returns Nothing. and for IO raises a user exception in the IO monad (see Section 7.88 CHAPTER 6. The Prelude provides the following auxiliary functions: sequence sequence_ mapM mapM_ (=<<) :: :: :: :: :: Monad Monad Monad Monad Monad m m m m m => => => => => [m [m (a (a (a a] a] -> -> -> -> m -> m m b) m b) m b) [a] () -> [a] -> m [b] -> [a] -> m () -> m a -> m b  fmap f xs xs >>= return . f    return a >>= k m >>= return m >>= (\x -> k x >>= h)   fmap id fmap (f . “do” expressions provide a convenient syntax for writing monadic expressions (see Section 3.

arbitrary precision integers (Integer). The standard numeric types are listed in Table 6. aspects of the IEEE floating point standard have been accounted for in Prelude class RealFloat. it is desirable that this type be at least equal in range and precision to the IEEE single-precision type.1 shows the class dependencies and built-in types that are instances of the numeric classes. an implementation may choose error ( . The standard numeric classes and other numeric functions defined in the Prelude are shown in Figures 6. using several type classes with an inclusion relation shown in Figure 6. Numeric function names and operators are usually overloaded. The results of exceptional conditions (such as overflow or underflow) on the fixed-precision numeric types are undefined. The types Int.4. Bounded may also be derived for single-constructor datatypes whose constituent types are in Bounded.6. 6. The Bounded class may be derived for any enumeration type. The default floating point operations defined by the Haskell Prelude do not conform to current language independent arithmetic (LIA) standards. Char. the numeric types and the operations upon them have been heavily influenced by Common Lisp and Scheme. The Prelude defines only the most basic numeric types: fixed sized integers (Int). Ord is not a superclass of Bounded since types that are not totally ordered may also have upper and lower bounds.1. and the class Floating contains all floating-point types. semantically). Other numeric types such as rationals and complex numbers are defined in libraries. but not all. both real and complex.   ¨      ¡£ ¤     ¡£ ¤     . the class Fractional contains all non-integral types. etc. and double precision floating (Double). Figure 6. indefinite. Float is implementation-defined. Double should cover IEEE double-precision. or a special value such as infinity. The finite-precision integer type Int covers at . the type Rational is a ratio of two Integer values. since all numbers may be compared for equality. Similarly. These standards require considerably more complexity in the numeric structure and have thus been relegated to a library. NUMBERS 89 6. its subclass Real is also a subclass of Ord. a truncated value. Bool. The class Num of numeric types is a subclass of Eq. ().2–6.3.4 Numbers Haskell provides several kinds of numbers. minBound is the first constructor listed in the data declaration and maxBound is the last. as defined in the Ratio library. single precision floating (Float). maxBound and least the range minBound can be used to determine the exact Int range defined by an implementation. maxBound :: a The Bounded class is used to name the upper and lower limits of a type. Some. page 83. As Int is an instance of the Bounded class.7 The Bounded Class class Bounded a where minBound.3. In particular. The class Integral contains integers of both limited and unlimited range. and all tuples are instances of Bounded.1. Ordering. since the other comparison operations apply to all but complex numbers (defined in the Complex library).

4) apply to all numbers. rem. rem. Ratio Integer). while the result of ‘div‘ is truncated toward negative infinity. a floating literal stands for an application of fromRational to a value of type Rational (that is.3. even .4. div. Given the typings: fromInteger :: (Num a) => Integer -> a fromRational :: (Fractional a) => Rational -> a integer and floating literals have the typings (Num a) => a and (Fractional a) => a. single precision Real floating-point.4. divMod is defined similarly: quotRem x y divMod x y = = (x `quot y. The quot. and the unary function negate (which can also be written as a prefix minus sign. (*). while the class method (/) applies only to fractional ones.1: Standard Numeric Types 6.1 Numeric Literals The syntax of numeric literals is given in Section 2. x ` ` y) ` rem (x `div y. See Section 4. and mod apply only to integral numbers. see section 3. and mod class methods satisfy these laws if y is non-zero: (x ` quot y)*y + (x ` ` y) == x ` rem (x ` ` y)*y + (x ` ` y) == x div mod ‘quot‘ is integer division truncated toward zero. respectively.5.2 Arithmetic and Number-Theoretic Operations The infix class methods (+). div. Similarly. The quotRem class method takes a dividend and a divisor as arguments and returns a (quotient. 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 Arbitrary-precision integers Fixed-precision integers Rational numbers Real floating-point. The class methods quot. x `mod y) ` ` Also available on integral numbers are the even and odd predicates: even x = odd = x ` ` 2 == 0 rem not .90 CHAPTER 6. Numeric literals are defined in this indirect way so that they may be interpreted as values of any appropriate numeric type. remainder) pair. 6. (-). An integer literal represents the application of the function fromInteger to the appropriate value of type Integer.4 for a discussion of overloading ambiguity. double precision Complex floating-point Table 6.

gcd 0 0 raises a runtime error. tan :: a -> a asin. gcd 0 4 = 4. including zero. divMod toInteger => :: :: :: Integral a where a -> a -> a a -> a -> (a. for example gcd (-3) 6 = 3. cosh. Part 1 Finally. 6. div. and (**) takes two floating-point arguments. logBase returns the logarithm of in base .  ¢  )¢ lcm is the smallest positive integer that both and divide. acosh. Enum a) quot. sqrt returns the principal square root of a floating-point number. atan :: a -> a sinh. signum fromInteger a) :: :: :: :: => Num a where a -> a -> a a -> a a -> a Integer -> a 91 class (Num a. There are three two-argument exponentiation operations: (ˆ) raises any number to a nonnegative integer power. 0** is undefined. Ord a) => Real a where toRational :: a -> Rational class (Real a. cos. (-). (ˆˆ) raises a fractional number to any integer power. logBase :: a -> a -> a sin. tanh :: a -> a asinh. log. The value of ˆ0 or ˆˆ0 is 1 for any . rem. atanh :: a -> a Figure 6.a) a -> Integer class (Num a) => Fractional a where (/) :: a -> a -> a recip :: a -> a fromRational :: Rational -> a class (Fractional a) => Floating a where pi :: a exp. acos.4. (*) negate abs. mod quotRem. there are the greatest common divisor and least common multiple functions. gcd is the greatest (positive) integer that divides both and .2: Standard Numeric Classes and Related Operations. NUMBERS class (Eq a. ¢ ¢ ¢ ¢ ¢  ¢ ¢ ¢    ¢  .6. gcd (-3) (-6) = 3.4. sqrt :: a -> a (**). Show (+).3 Exponentiation and Logarithms The one-argument exponential function exp and the logarithm function log act on floating-point numbers and use base .

92 CHAPTER 6. The functions abs and signum apply to any number and satisfy the law: abs x * signum x == x For real numbers. Integral b) => a -> b -> a (ˆˆ) :: (Fractional a. these functions are defined by: abs x | x >= 0 | x < 0 = x = -x = 1 = 0 = -1 signum x | x > 0 | x == 0 | x < 0 .Int) encodeFloat :: Integer -> Int -> a exponent :: a -> Int significand :: a -> a scaleFloat :: Int -> a -> a isNaN. isDenormalized. isNegativeZero. isInfinite. Integral b) => a -> b -> a fromIntegral :: (Integral a.4. Num b) => a -> b realToFrac :: (Real a. Floating a) => RealFloat a where floatRadix :: a -> Integer floatDigits :: a -> Int floatRange :: a -> (Int. isIEEE :: a -> Bool atan2 :: a -> a -> a gcd.4 Magnitude and Sign A number has a magnitude and a sign.3: Standard Numeric Classes and Related Operations. Fractional a) => RealFrac properFraction :: (Integral b) => a truncate.a) b b class (Real a. Part 2 6. lcm :: (Integral a) => a -> a-> a (ˆ) :: (Num a. PREDEFINED TYPES AND CLASSES a -> -> -> where (b. Fractional b) => a -> b Figure 6. round :: (Integral b) => a ceiling. floor :: (Integral b) => a class (RealFrac a.Int) decodeFloat :: a -> (Integer.

and furthermore. truncate. with in a type that is RealFloat. and is a fraction with the same type and sign as . should return the same value as atan . Two functions convert numbers to type Rational: toRational returns the rational equivalent of its real argument with full precision. floor. **. the greatest integer not greater than . machine-independent access to the components of a floating-point number. the even integer if is equidistant between two integers. either and are both zero or else of floatDigits x. but implementors are free to provide more accurate implementations. then x is equal in value to . and the lowest and highest values the exponent may assume. atan2 returns a value in the range [-pi.4. where is the value radix. atan2 computes the angle (from the positive x-axis) of the vector from the origin to the point . tanh. cosine.5 Trigonometric Functions Class Floating provides the circular and hyperbolic sine. atan2 1. truncate. and with absolute value less than 1. pi]. round returns the nearest integer to . ceiling returns the least integer not less than . and floor . truncate yields the integer nearest between and . floor. The functions floatRadix.6. and round functions can be defined in terms of properFraction. approxRational takes two real fractional arguments and and returns the simplest rational number within of . which in turn follows Penfield’s proposal for APL [9]. The precise definition of the above functions is as in Common Lisp. inclusive. See these references for discussions of branch cuts.6 Coercions and Component Extraction The ceiling. ). and round functions each take a real fractional argument and return an integral result. The function decodeFloat applied to a real floating-point number returns the significand expressed as an Integer and an appropriately scaled exponent (an Int). where a rational in reduced form is simpler than another if and . A default definition of atan2 is provided. note that is the simplest rational of all. Default implementations of tan. For real floating and . The ceiling. It follows the Common Lisp semantics for the origin when signed zeroes are supported. Class RealFloat provides a version of arctangent taking two real floating-point arguments.4. If decodeFloat x yields ( . logBase. and: is an integral number with the same sign as . encodeFloat performs the inverse of this transformation. NUMBERS 93 6. where is the floating-point . floatDigits. and tangent functions and their inverses. and sqrt are provided. and implementation. The function properFraction takes a real fractional number and returns a pair such that . The functions ¦ ' ¥ ¢ ¢ ¢  0 ¦ ¦   0  ¢ ¢ £  ¡ ¢ ' 0 ¦ ¢ 4 A ¢ '   ¢ 4 ¡ ¦¥ ' ¥ ¢   ¢ 1 ¢ ¢   ¢ ¢  1 ¡ ¦ ¢   ¦ £  ¡   ¤ 4 4 1 £  1 ¡ ¢  £   ¢  ¦ ¢  ¢ 0 ¢   ¦  ¢   . discontinuities. respectively. Every real interval contains a unique simplest rational.4. the number of digits of this radix in the significand. The class methods of class RealFloat allow efficient. and floatRange give the parameters of a floating-point type: the radix of the representation.    ¢  ¢  6. but implementors can provide a more accurate implementation. in particular.

Fractional b) => a -> b        . scaled to lie in the open interval .94 CHAPTER 6. Num b) => a -> b realToFrac :: (Real a. isDenormalized. The functions isNaN. significand x yields a value of the same type as x. isInfinite. Also available are the following coercion functions: fromIntegral :: (Integral a. For non-IEEE floating point numbers. PREDEFINED TYPES AND CLASSES significand and exponent together provide the same information as decodeFloat. scaleFloat multiplies a floating-point number by an integer power of the radix. and isIEEE all support numbers represented using the IEEE standard. these may all return false. but rather than an Integer. exponent 0 is zero. isNegativeZero.

In the following. it is best to think of a monad as an abstract datatype. may read as a single newline character. see Section 6.3. however. and which are described in this section. For example. Some operations are primitive actions. The term comes from a branch of mathematics known as category theory. and an implementation is obliged to preserve this order. To achieve this. yet has all of the expressive power found in conventional programming languages. it is possible to write many Haskell programs using only the few simple functions that are exported from the Prelude. Haskell’s I/O monad provides the user with a way to specify the sequential chaining of actions. must be ordered in a welldefined manner for program execution – and I/O in particular – to be meaningful.1 Standard I/O Functions Although Haskell provides fairly sophisticated I/O facilities. corresponding to sequencing operators (such as the semicolon) in imperative languages. as defined in the IO library. The order of evaluation of expressions in Haskell is constrained only by data dependencies. however. © ¦ 332 § §  ¤¢ ©   $  7. The treatment of the newline character will vary on different systems. All I/O functions defined here are character oriented. two characters of input. 95 ¦ ¢ ¦ 32 4 7 3¢ ¦ ¢ ¦ 32 4 © ¦ 332 § §  ¤¢ . Special operations (methods in the class Monad. return and linefeed. an implementation has a great deal of freedom in choosing this order.1. These functions cannot be used portably for binary I/O. Actions. 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. recall that String is a synonym for [Char] (Section 6.2).6) sequentially compose actions. Haskell uses a to integrate I/O operations into a purely functional context. In the case of the I/O monad. From the perspective of a Haskell programmer. corresponding to conventional I/O operations.Chapter 7 Basic Input/Output The I/O system in Haskell is purely functional. the abstract values are the mentioned above.

adds a newline Show a => a -> IO () The print function outputs a value of any printable type to the standard output device. The readIO function is similar to read except that it signals parse failure to the I/O monad instead of terminating the program. The readLn function combines getLine and readIO. The following program simply removes all non-ASCII characters from its standard input and echoes the result on its standard output.96 CHAPTER 7. which is read lazily as it is needed. The getContents operation returns all user input as a single string. a program to print the first 20 integers and their powers of 2 could be written as: main = print ([(n.3) on end-of-file. Printable types are those that are instances of class Show. Typically.[0. a predicate isEOFError that identifies this exception is defined in the IO library. BASIC INPUT/OUTPUT Output Functions These functions write to the standard output device (this is normally the user’s terminal). the read operation from class Read is used to convert the string to a value. 2ˆn) | n <. and the resulting string is output on the standard output device. The getLine operation raises an exception under the same circumstances as hGetLine. print converts values to strings for output using the show operation and adds a newline. For example. (The isAscii function is defined in a library. defined the IO library. The entire input from the standard input device is passed to this function as its argument. The interact function takes a function of type String->String as its argument. putChar putStr putStrLn print :: :: :: :: Char -> IO () String -> IO () String -> IO () -..19]]) Input Functions terminal). These functions read input from the standard input device (normally the user’s :: :: :: :: :: :: IO Char IO String IO String (String -> String) -> IO () Read a => String -> IO a Read a => IO a getChar getLine getContents interact readIO readLn The getChar operation raises an exception (Section 7.) main = interact (filter isAscii) .

SEQUENCING I/O OPERATIONS 97 Files These functions operate on files of characters.x*x) | x <.2.0.2]]) 7.[0. The two monadic binding functions. The readFile function reads a file and returns the contents of the file as a string. but takes its input from "input-file" and writes its output to "output-file". as with getContents. main = appendFile "squares" (show [(x. their first argument. The file is read lazily. 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 file. The >>= operation passes the result of the first operation as an argument to the second operation. as with print. for example when it is (). on demand.2 Sequencing I/O Operations The type constructor IO is an instance of the Monad class. use the show function to convert the value to a string first. To write a value of any printable type.7. The writeFile and appendFile functions write or append the string. A message is printed on the standard output before the program completes. to the file. The >> function is used where the result of the first operation is uninteresting. their second argument.1. main = readFile "input-file" writeFile "output-file" (filter isAscii s) putStr "Filtering successful\n" >>= \ s -> >> is similar to the previous example using interact. methods in the Monad class. Files are named by strings using some implementation-specific method to resolve strings as file names. are used to compose a series of I/O operations. A slightly more elaborate version of the previous example would be: . The do notation allows programming in a more imperative syntactic style.. (>>=) :: IO a -> (a -> IO b) -> IO b (>>) :: IO a -> IO b -> IO b For example.

BASIC INPUT/OUTPUT main = do putStr "Input file: " ifile <. The IO library defines functions that construct and examine IOError values. 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. An exception is caught by the most recent handler established by catch. For example. For example. Exceptions in the I/O monad are represented by values of type IOError. The isEOFError function is part of IO library. This is an abstract type: its constructors are hidden from the user. getLine is defined in terms of getChar. Any I/O operation may raise an exception instead of returning a result.getChar if c == ’\n’ then return "" else do s <.getLine putStr "Output file: " ofile <.readFile ifile writeFile ofile (filter isAscii s) putStr "Filtering successful\n" The return function is used to define the result of an I/O operation. Exception propagation must be explicitly provided in a handler by re-raising any unwanted exceptions.isEOFError e then return [] else ioError e) the function f returns [] when an end-of-file exception occurs in g.getLine s <.getLine return (c:s) 7. . using return to define the result: getLine :: IO String getLine = do c <. otherwise. User error values include a string describing the error. the catch function establishes a handler that receives any exception raised in the action protected by catch.98 CHAPTER 7. the exception is propagated to the next outer handler.3 Exception Handling in the I/O Monad The I/O monad includes a simple exception handling system. in f = catch g (\e -> if IO. These handlers are not selective: all exceptions are caught. The only Prelude function that creates an IOError value is userError.

bindings for return.7. EXCEPTION HANDLING IN THE I/O MONAD 99 When an exception propagates outside the main program..3.. the Haskell system prints the associated IOError value and exits the program.3. (>>) fail s = ioError (userError s) The exceptions raised by the I/O functions in the Prelude are defined in Chapter 21.6) raises a userError. . (>>=). thus: instance Monad IO where . The fail method of the IO instance of the Monad class (Section 6.

100 CHAPTER 7. BASIC INPUT/OUTPUT .

They do not constitute a specification of the meaning of the method in all instances. PreludeList. such as Integral a or Num a. Only the exports of module Prelude are significant. IO.Chapter 8 Standard Prelude In this chapter the entire Haskell Prelude is given.” is often used in places where the remainder of a definition cannot be given in Haskell. Primitives that are not definable in Haskell. This structure is purely presentational. an implementation is free to import more. It constitutes a specification for the Prelude. constitute a specification only of the default method. drop. and it is not required that the specification be implemented as shown here. a number of commonly-used functions over lists use the Int type rather than using a more general numeric type. are defined in a system dependent manner in module PreludeBuiltin and are not shown here.. given with class declarations. These imports are not. These functions are: take. To reduce the occurrence of unexpected ambiguity errors. and Numeric. of course. The Prelude shown here is organized into a root module. and PreludeIO.. indicated by names starting with “prim”. as it pleases. That is. Many of the definitions are written with clarity rather than efficiency in mind. 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). nor are these three modules available for import separately. such as Char. and to improve efficiency. Some of the more verbose instances with obvious functionality have been left out for the sake of brevity. length. Prelude. The default method definitions. part of the specification of the Prelude. !!. Some of these modules import Library modules. An ellipsis “. An implementation is not required to use this organisation for the Prelude. 101 . and three sub-modules. Instance declarations that simply bind primitives to class methods are omitted. Declarations for special types such as Integer. or () are included in the Prelude for completeness even though the declaration may be incomplete or syntactically invalid. of the Library modules. or less. To take one particular example. PreludeText. These modules are described fully in Part II. Monad.

The more general versions are given in the List library. . for example genericLength. STANDARD PRELUDE splitAt. with the prefix “generic”.102 CHAPTER 8. and replicate.

mapM. isNegativeZero. toInteger).Contains all ‘prim’ values -.. atan2). atan. round. mapM_. negate.)((. encodeFloat. Num((+). (>). True). Monad((>>=). sinh. isDenormalized. Ordering(LT. enumFromTo. maxBound). Enum(succ. const. IO. (-). isInfinite. (/=)). asinh. fromIntegral. tan. sqrt. ceiling. (&&). rem. log. sequence_. acos. min). div.)((. fromEnum. exp. EQ. Fractional((/). odd. curry. gcd. List type: []((:).)). (<=). realToFrac. subtract. asin. flip. fst. (||). Just). Double. floor). sin. Bool(False. but are denoted by built-in syntax. enumFromThenTo). mod. GT). floatRange. (<). Either(Left. etc. seq. cosh. quotRem.103 module Prelude ( module PreludeList. id.Unicode primitives . scaleFloat. divMod. Floating(pi. (. Integer. (. recip. String. floatDigits. exponent. Bounded(minBound. -------These built-in types are defined in the Prelude. not. Trivial type: ()(()) Functions: (->) Eq((==). (ˆˆ). even. enumFromThen. fromInteger). Integral(quot. (>>).)). truncate. Int. maybe. (**). otherwise. enumFrom. Real(toRational). acosh. undefined. uncurry. signum. module PreludeText. fromRational). isNaN. (=<<). pred. Float. RealFloat(floatRadix. abs.. decodeFloat. Ord(compare. ($). cos. and cannot legally appear in an export list. []) Tuple types: (. Functor(fmap). toEnum. fail). lcm. error. atanh). Right). Char. Rational.). (>=). (ˆ). either. sequence. module PreludeIO. logBase. max. return. snd. asTypeOf. RealFrac(properFraction. Maybe(Nothing. significand. until. (*). tanh. ($!) ) where import import import import import import PreludeBuiltin UnicodePrims( primUnicodeMaxChar ) PreludeList PreludeText PreludeIO Ratio( Rational ) -. isIEEE.

a fixity declaration.The (:) operator is built-in syntax. <=. >>= =<< $. but its fixity is given by: -infixr 5 : infix infixr infixr infixl infixr infixr 4 3 2 1 1 0 ==. STANDARD PRELUDE .y) or (y. ˆ. $!.104 infixr infixr infixl infixl 9 8 7 6 CHAPTER 8. ˆˆ. ‘div‘. ‘mod‘ +. /=. > && || >>. ‘rem‘. (>) :: a -> a -> Bool max. ‘seq‘ -.x) max x y | x <= y = y | otherwise = x min x y | x <= y = x | otherwise = y . <. classes.Standard types. 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 -. instances and related functions -.Equality and Ordered classes class Eq a where (==).Minimal complete definition: -(<=) or compare -. min :: a -> a -> a -. >=. (<=). (/=) :: a -> a -> Bool -.Using compare can be more efficient for complex types.note that (min x y. (>=). - -.Minimal complete definition: -(==) or (/=) x /= y = not (x == y) x == y = not (x /= y) class (Eq a) => Ord a where compare :: a -> a -> Ordering (<). /. and cannot legally be given -. ** *. ‘quot‘. max x y) = (x.

NOTE: these default methods only make sense for types -that map injectively into Int using fromEnum -and toEnum. signum :: a -> a fromInteger :: Integer -> a -. fromEnum y] enumFromThen x y = map toEnum [fromEnum x.Numeric classes class (Eq a.n’. fromEnum z] class Bounded a minBound maxBound where :: a :: a -..n’. (*) :: a -> a -> a negate :: a -> a abs. (+1) .] enumFromThenTo x y z = map toEnum [fromEnum x.. fromEnum pred = toEnum . Show a) => Num a where (+). Ord a) => Real a where toRational :: a -> Rational .] [n.. except x ...Minimal complete definition: -toEnum. pred toEnum fromEnum enumFrom enumFromThen enumFromTo enumFromThenTo :: :: :: :: :: :: :: a -> a Int -> a a -> Int a -> [a] a -> a -> [a] a -> a -> [a] a -> a -> a -> [a] ----- [n.Minimal complete -All. (-).. fromEnum y . fromEnum --.] enumFromTo x y = map toEnum [fromEnum x .Enumeration and Bounded classes class Enum a where succ.y = x + negate x = 0 definition: negate or (-) negate y x class (Num a. fromEnum enumFrom x = map toEnum [fromEnum x .105 -. succ = toEnum ...] [n. (subtract 1) .m] -. fromEnum y .m] [n.

r) = n ‘mod‘ d = r where (q. atan -asinh. cos.r) = n ‘rem‘ d = r where (q. atan :: a -> a sinh. Enum quot. acosh. cosh -asin. r+d) else qr quotRem n d -. atanh x ** y = exp (log x * y) logBase x y = log y / log x sqrt x = x ** 0. toInteger n ‘quot‘ d = q where (q. logBase :: a -> a -> a sin. STANDARD PRELUDE => Integral a where a -> a -> a a -> a -> a a -> a -> (a.a) a -> Integer -. tan :: a -> a asin. sqrt :: a -> a (**). log.106 class (Real a. exp. atanh :: a -> a -. acosh. mod quotRem. sin. sinh.r) = divMod n d = if signum r == where qr@(q.Minimal complete definition: -fromRational and (recip or (/)) recip x = 1 / x x / y = x * recip y class (Fractional a) => Floating a where pi :: a exp. log. acos.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 (q-1. acos.r) = n ‘div‘ d = q where (q. tanh :: a -> a asinh. cosh. divMod toInteger a) :: :: :: :: CHAPTER 8. rem div.5 tan x = sin x / cos x tanh x = sinh x / cosh x .Minimal complete definition: -pi.Minimal complete definition: -quotRem. cos.

floor :: (Integral b) => a a -> -> -> where (b. Fractional a) => RealFrac properFraction :: (Integral b) => a truncate.Minimal complete definition: -properFraction truncate x = m where (m.5) of -1 -> n 0 -> if even n then n else m 1 -> m if r > 0 then n + 1 else n where (n.0.r) = properFraction x if r < 0 then n . round :: (Integral b) => a ceiling._) = properFraction x round x = let (n.r) = properFraction x ceiling x floor x = = .a) b b -.1 else n + 1 in case signum (abs r .r) = properFraction x m = if r < 0 then n .1 else n where (n.107 class (Real a.

isInfinite.n) = decodeFloat x atan2 y x | x>0 = atan (y/x) | x==0 && y>0 = pi/2 | x<0 && y>0 = pi + atan (y/x) |(x<=0 && y<0) || (x<0 && isNegativeZero y) || (isNegativeZero x && isNegativeZero y) = -atan2 (-y) x | y==0 && (x<0 || isNegativeZero x) = pi -.floatDigits x) where (m.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 significand x scaleFloat k x = = encodeFloat m (. Floating a) => RealFloat a where floatRadix :: a -> Integer floatDigits :: a -> Int floatRange :: a -> (Int. return a NaN (via +) -. isDenormalized. atan2 exponent x = if m == 0 then 0 else n + floatDigits x where (m. even :: (Integral a) => a -> a -> a = error "Prelude.Int) decodeFloat :: a -> (Integer. STANDARD PRELUDE class (RealFrac a._) = decodeFloat x encodeFloat m (n+k) where (m. isNegativeZero.Minimal complete definition: -All except exponent.must be after the other double zero tests | otherwise = x + y -.x or y is a NaN.must be after the previous test on zero y | x==0 && y==0 = y -. 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 .108 CHAPTER 8.Numeric functions subtract subtract even.Int) encodeFloat :: Integer -> Int -> a exponent :: a -> Int significand :: a -> a scaleFloat :: Int -> a -> a isNaN. isIEEE :: a -> Bool atan2 :: a -> a -> a -. significand. -scaleFloat.

Integral b) => a -> b -> a = 1 = f x (n-1) 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 (n-1) (x*y) = error "Prelude. toRational -. Fractional b) => a -> b = fromRational .list element to a monad type mapM :: Monad m => (a -> m b) -> [a] -> m [b] mapM f as = sequence (map f as) mapM_ mapM_ f as (=<<) f =<< x :: Monad m => (a -> m b) -> [a] -> m () = sequence_ (map f as) :: Monad m => (a -> m b) -> m a -> m b = x >>= f . Integral b) => a -> b -> a = if n >= 0 then xˆn else recip (xˆ(-n)) :: (Integral a.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. 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 ()) -.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. but lift the function or -. toInteger :: (Real a. Num b) => a -> b = fromInteger .ˆ: negative exponent" :: (Fractional a.

. Read. STANDARD PRELUDE = () deriving (Eq.flip f takes its (first) two arguments in the reverse order of f. True False True False (||) && x && _ || _ || x :: = = = = Bool -> Bool -> Bool x False True x not not True not False otherwise otherwise :: Bool -> Bool = False = True :: Bool = True -.. Enum.Function type -..function composition (..(useful in continuation-passing style) ($).Boolean functions (&&). -. -.Trivial type data () CHAPTER 8. Ord.Not legal Haskell.110 -. for illustration only -. ’a’ | ’b’ . g = \ x -> f (g x) -. Show. Ord. Enum.constant function const :: a -> b -> a const x _ = x -.. ($!) :: (a -> b) -> a -> b f $ x = f x f $! x = x ‘seq‘ f x -.Unicode values instance Eq Char c == c’ where = fromEnum c == fromEnum c’ .Primitive -.Boolean type data Bool = False | True deriving (Eq..) :: (b -> c) -> (a -> b) -> a -> c f . Bounded) -. flip :: (a -> b -> c) -> b -> a -> c flip f x y = f y x seq :: a -> b -> b seq = .Character type data Char = .identity function id :: a -> a id x = x -.right-associating infix application operators -. Bounded) -.

Read. Read... Ord. Ord.abstract instance Functor IO where fmap f x = x >>= (return ...IO type data IO a = ..Either type data Either a b = Left a | Right b deriving (Eq. fromEnum c’ . fromEnum (maxBound::Char)] enumFromThen c c’ = map toEnum [fromEnum c.. fromEnum lastChar] where lastChar :: Char lastChar | c’ < c = minBound | otherwise = maxBound instance Bounded Char where minBound = ’\0’ maxBound = primUnicodeMaxChar type String = [Char] -. Show) either :: (a -> c) -> (b -> c) -> Either a b -> c either f g (Left x) = f x either f g (Right y) = g y -.. fail s = ioError (userError s) . f) instance Monad IO where (>>=) = . return = . 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 -..Maybe type data Maybe a = Nothing | Just a deriving (Eq. -.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 .

. Read. -1 | 0 | 1 ... .far too large...... . Ord.. ... instance Eq Integer where . data Float instance Eq instance Ord instance Num instance Real instance Fractional instance Floating instance RealFrac instance RealFloat data Double instance Eq instance Ord instance Num instance Real instance Fractional instance Floating instance RealFrac instance RealFloat Float Float Float Float Float Float Float Float Double Double Double Double Double Double Double Double where where where where where where where where ....Standard numeric types.. . ... .. instance Num Integer where . instance Integral Integer where ... .. where where where where where where where where ....... Bounded) -...... Enum. ... maxBound ...... . Show. ...112 -.. . -1 Eq Int where Ord Int where Num Int where Real Int where Integral Int where Enum Int where Bounded Int where | 0 | 1 ....Ordering type data CHAPTER 8. The data declarations for these types cannot -. . data Integer = ...... data Int instance instance instance instance instance instance instance = minBound . .. ... . . .. instance Ord Integer where .. ... .. STANDARD PRELUDE Ordering = LT | EQ | GT deriving (Eq.. instance Enum Integer where .. ..be expressed directly in Haskell since the constructor lists would be -... instance Real Integer where ... ..

The ‘toEnum’ function truncates numbers to Int. The definitions of enumFrom and enumFromThen allow floats to be used in arithmetic series: [0. truncate enumFrom = numericEnumFrom enumFromThen = numericEnumFromThen enumFromTo = numericEnumFromTo enumFromThenTo = numericEnumFromThenTo numericEnumFrom :: numericEnumFromThen :: numericEnumFromTo :: numericEnumFromThenTo :: numericEnumFrom = numericEnumFromThen n m = numericEnumFromTo n m = numericEnumFromThenTo n n’ -.0. Ord a) => a -> a -> a -> [a] iterate (+1) iterate (+(m-n)) 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) -. where = x+1 = x-1 = fromIntegral = fromInteger . Ord) -. depending on how 0. roundoff errors make these somewhat dubious. However.may overflow instance Enum Double where succ x = x+1 pred x = x-1 toEnum = fromIntegral fromEnum = fromInteger .may overflow (Fractional a) => a -> [a] (Fractional a) => a -> a -> [a] (Fractional a. 0.1 is represented.Not legal Haskell.95]. This example may have either 10 or 11 elements.113 ------The Enum instances for Floats and Doubles are slightly unusual.. for illustration only instance Functor [] where fmap = map instance Monad [] m >>= k return x fail s where = concat (map k m) = [x] = [] . truncate = numericEnumFrom = numericEnumFromThen = numericEnumFromTo = numericEnumFromThenTo instance Enum Float succ x pred x toEnum fromEnum enumFrom enumFromThen enumFromTo enumFromThenTo -. Ord a) => a -> a -> [a] (Fractional a.Lists data [a] = [] | a : [a] deriving (Eq.1 .

appears.curry converts an uncurried function to a curried function.until p f yields the result of applying f until p holds.b) deriving (Eq. Bounded) -. undefined undefined :: a = error "Prelude. etc. Ord. b) -> c) = f (fst p) (snd p) -.(NB: not provided for triples. curry :: ((a.undefined" . -.b) = (a.114 -. It is usually used -.messages that are more appropriate to the context in which undefined -.Tuples data data CHAPTER 8. for illustration only -.) fst :: (a. STANDARD PRELUDE (a.component projections for pairs: -.It is expected that compilers will recognize this and insert error -.b) -> a fst (x. b) -> c) -> a -> b -> c curry f x y = f (x.(which is usually overloaded) to have the same type as the second.as an infix operator.b. and its typing forces its first argument -.asTypeOf is a type-restricted version of const.Not legal Haskell.error stops execution and displays an error message error error :: String -> a = primError -.y) :: (a. Bounded) (a. asTypeOf :: a -> a -> a asTypeOf = const -.b. Ord.c) = (a. until :: (a -> Bool) -> (a -> a) -> a -> a until p f x | p x = x | otherwise = until p f (f x) -.c) deriving (Eq.Misc functions -.b) -> b = y -. y) uncurry uncurry f p :: (a -> b -> c) -> ((a.uncurry converts a curried function to a function on pairs. quadruples.y) = x snd snd (x.

cycle. dropWhile. replicate. and. foldr. iterate.1 Prelude PreludeList -. unzip. product. ‘notElem‘ -. zip. map f ----head and tail extract the first element and remaining elements. zip3. or. PRELUDE PRELUDELIST 115 8. lookup. zipWith3. maximum. takeWhile. last and init are the dual functions working from the end of a finite list. lines. take.8. splitAt. scanr1. minimum.1. scanr. of a list. break. scanl. tail. span. which must be non-empty. foldl. (++). all. unwords. rather than the beginning. foldr1. drop. reverse. :: [a] -> a = x = error "Prelude. last. unlines. sum.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 . zipWith.Standard list functions module PreludeList ( map. length.tail: empty list" head head (x:_) head [] tail tail (_:xs) tail [] . repeat. init. words. concatMap. respectively. foldl1. null. filter. (!!). elem. concat. unzip3) where import qualified Char(isSpace) infixl 9 infixr 5 infix 4 !! ++ ‘elem‘. any.head: empty list" :: [a] -> [a] = xs = error "Prelude. scanl1. head. notElem.

List index (subscript) operator..length returns the length of a finite list as an Int.. but returns a list of successive reduced values from the left: scanl f z [x1.. scanl is similar to foldl. x2. . xn] == (.) ‘f‘ xn foldl1 is a variant that has no starting value argument.last: empty list" [a] -> [a] [] x : init xs error "Prelude. . and thus must be applied to non-empty lists. z ‘f‘ x1. x1 ‘f‘ x2.!!: negative index" [] !! _ = error "Prelude... 0-origin (!!) :: [a] -> Int -> a xs !! n | n < 0 = error "Prelude.init: empty list" :: [a] -> Bool = True = False -.. length :: [a] -> Int length [] = 0 length (_:l) = 1 + length l -.((z ‘f‘ x1) ‘f‘ x2) ‘f‘. (z ‘f‘ x1) ‘f‘ x2... .] == [x1..116 last last [x] last (_:xs) last [] init init [x] init (x:xs) init [] null null [] null (_:_) :: = = = :: = = = CHAPTER 8.!!: index too large" (x:_) !! 0 = x (_:xs) !! n = xs !! (n-1) -----------foldl. applied to a binary operator. scanl1 is similar. and a list.] == [z. again without the starting element: scanl1 f [x1.. .] Note that last (scanl f z xs) == foldl f z xs. reduces the list using the binary operator.. .. x2. from left to right: foldl f z [x1. a starting value (typically the left-identity of the operator).. STANDARD PRELUDE [a] -> a x last xs error "Prelude..foldl1: empty list" :: (a -> b -> a) -> a -> [b] -> [a] = q : (case xs of [] -> [] x:xs -> scanl f (f q x) xs) :: (a -> a -> a) -> [a] -> [a] = scanl f x xs = [] scanl1 scanl1 f (x:xs) scanl1 _ [] . x2..] foldl :: (a -> b -> a) -> a -> [b] -> a foldl f z [] = z foldl f z (x:xs) = foldl f (f z x) xs foldl1 foldl1 f (x:xs) foldl1 _ [] scanl scanl f q xs :: (a -> a -> a) -> [a] -> a = foldl f x xs = error "Prelude.

iterate f x returns an infinite list of repeated applications of f to x: -. or xs itself if n > length xs.the infinite repetition of the original list. PRELUDE PRELUDELIST 117 -.] iterate :: (a -> a) -> a -> [a] iterate f x = x : iterate f (f x) -.on infinite lists.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) -. It is the identity -. and scanr1 are the right-to-left duals of the -. Int -> [a] -> [a] [] [] x : take (n-1) xs take :: take n _ | n <= 0 = take _ [] = take n (x:xs) = . with x the value of every element. f 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 -. returns the prefix of xs of length n.. foldr1.foldr.iterate f x == [x.cycle: empty list" = xs’ where xs’ = xs ++ xs’ take n. cycle cycle [] cycle xs ----:: [a] -> [a] = error "Prelude. or [] if n > length xs. splitAt n xs is equivalent to (take n xs. scanr. foldr :: (a -> b -> b) -> b -> [a] -> b foldr f z [] = z foldr f z (x:xs) = f x (foldr f z xs) foldr1 foldr1 f [x] foldr1 f (x:xs) foldr1 _ [] :: = = = (a -> a -> a) -> [a] -> a x f x (foldr1 f xs) error "Prelude. . repeat :: a -> [a] repeat x = xs where xs = x:xs -.repeat x is an infinite list.above functions.8. f (f x). applied to a list xs. drop n xs). -.1.cycle ties a finite list into a circular one. or equivalently. drop n xs returns the suffix of xs after the first n elements.

break :: (a -> Bool) -> [a] -> ([a].xs) where (ys. span p xs is equivalent to (takeWhile p xs. which were delimited by white space.[a]) span p [] = ([]. :: (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.isSpace s’ lines lines "" lines s words words s .[]) span p xs@(x:xs’) | p x = (x:ys. dropWhile p xs returns the remaining suffix.isSpace s of "" -> [] s’ -> w : words s’’ where (w. drop n xs) takeWhile. and unwords joins words with separating spaces.118 drop :: drop n xs | n <= 0 = drop _ [] = drop n (_:xs) = splitAt splitAt n xs ----- CHAPTER 8. while break p uses the negation of p. unlines joins lines with terminating newlines. returns the longest prefix (possibly empty) of xs of elements that satisfy p. p) lines breaks a string up into a list of strings at newline characters. STANDARD PRELUDE Int -> [a] -> [a] xs [] drop (n-1) xs :: Int -> [a] -> ([a]. applied to a predicate p and a list xs. s’’) = break Char.zs) | otherwise = ([]. dropWhile p xs).zs) = span p xs’ break p ------= span (not . Similary. words breaks a string up into a list of words.[a]) = (take n xs. unlines and unwords are the inverse operations. s’) = break (== ’\n’) s in l : case s’ of [] -> [] (_:s’’) -> lines s’’ :: String -> [String] = case dropWhile Char. The resulting strings do not contain newlines.

product :: (Num a) => [a] -> a sum = foldl (+) 0 product = foldl (*) 1 -.. the list must be finite. x ‘elem‘ xs. lookup :: (Eq a) => a -> [(a.y):xys) | key == x = Just y | otherwise = lookup key xys -. map p -. -. or :: [Bool] -> Bool and = foldr (&&) True or = foldr (||) False -. map p all p = and . and of an ordered type. Similarly.maximum and minimum return the maximum or minimum value from a list. For the result to be -.minimum: empty list" foldl1 min xs .8.sum and product compute the sum or product of a finite list of numbers.reverse xs returns the elements of xs in reverse order.disjunctive dual of and. or is the -. notElem is the negation.True.e.Applied to a predicate and a list. sum.1. for all.and returns the conjunction of a Boolean list. minimum :: (Ord a) => [a] -> a maximum [] = error "Prelude. elem.value at a finite index of a finite or infinite list. and. notElem :: (Eq a) => a -> [a] -> Bool elem x = any (== x) notElem x = all (/= x) -. -. maximum.g. PRELUDE PRELUDELIST unlines unlines unwords unwords [] unwords ws :: [String] -> String = concatMap (++ "\n") :: [String] -> String = "" = foldr1 (\w s -> w ++ ’ ’:s) ws 119 -. results from a False -. False. any determines if any element -. reverse :: [a] -> [a] reverse = foldl (flip (:)) [] xs must be finite.elem is the list membership predicate.maximum: empty list" maximum xs = foldl1 max xs minimum [] minimum xs = = error "Prelude.which must be non-empty.of the list satisfies the predicate. any. however.b)] -> Maybe b lookup key [] = Nothing lookup key ((x. finite. -.lookup key assocs looks up a key in an association list. usually written in infix form. all :: (a -> Bool) -> [a] -> Bool any p = or .

zip3 takes three lists and returns a list of triples.bs.c)] -> ([a]..120 ----- CHAPTER 8.[].) :: [a] -> [b] -> [c] -> [(a.c) ˜(as.b)] = zipWith (. unzip unzip unzip3 unzip3 :: [(a.b)] -> ([a].b:bs)) ([]. If one input list is short. STANDARD PRELUDE zip takes two lists and returns a list of corresponding pairs.cs) -> (a:as.[]) :: [(a.unzip transforms a list of pairs into a pair of lists. zipWith (+) is applied to two lists to produce the list of corresponding sums. Zips for larger tuples are in the List library :: [a] -> [b] -> [(a.b. 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.b) ˜(as.[b].b.c:cs)) ([].b. For example. instead of a tupling function.bs) -> (a:as.c)] = zipWith3 (. excess elements of the longer list are discarded.[b]) = foldr (\(a.) zip zip zip3 zip3 ----- The zipWith family generalises the zip family by zipping with the function given as the first argument.[c]) = foldr (\(a.

isAlpha. showChar. Either. readSigned. readl’ t] lex s] ++ lex s. readFloat. showString.u) (xs. Read(readsPrec. isDigit.are done via "deriving" clauses in Prelude. isAlphaNum.’ .String)] = String -> String where :: Int -> ReadS a :: ReadS [a] class Read a readsPrec readList -. lexDigits) type type ReadS a ShowS = String -> [(a.t) | ("]".8. show. showInt. showList). shows x . readParen.v) | (". showLitChar.t) (x.v) class Show a showsPrec show showList where :: Int -> a -> ShowS :: a -> String :: [a] -> ShowS <<<<<<<<<- lex r. Ordering -.2. read. shows. showl xs .t) | ("]". reads.s) pr where readl s = [([].t) [(x:xs. lex. showParen ) where -. readl s]) lex s] ++ reads s. lexLitChar) import Numeric(showSigned. Maybe.2 Prelude PreludeText module PreludeText ( ReadS.The instances of Read and Show for -Bool. PRELUDE PRELUDETEXT 121 8. readList). showl xs where showl [] = showChar ’]’ showl (x:xs) = showChar ’.u) | (x. showFloat. readLitChar.u) readl’ s = [([]. readDec.t) (xs. readl’ u] -. Show(showsPrec. shows x .". ShowS.Minimal complete definition: -readsPrec readList = readParen False (\r -> [pr | ("[".t) [(x:xs.hs import Char(isSpace.Mimimal complete definition: -show or showsPrec showsPrec _ x s = show x ++ s show x showList [] showList (x:xs) = showsPrec 0 x "" = showString "[]" = showChar ’[’ . reads t.

122 reads reads shows shows read read s :: (Read a) => ReadS a = readsPrec 0 :: (Show a) => a -> ShowS = showsPrec 0 CHAPTER 8. ch /= "’" ] [(’"’:str.Current limitations: -Qualified names are not handled properly -Octal and hexidecimal numerics are not recognized as a single token -Comments are not treated properly lex lex "" lex (c:s) | isSpace c lex (’\’’:s) lex (’"’:s) :: ReadS String = [("".s)] lexStrItem (’\\’:c:s) | isSpace c = [("\\&".t) (")".lexString t ] lexStrItem (’\\’:’&’:s) = [("\\&".t) <. ("".lexStrItem s. <.s)] lexString s = [(ch++str.This lexer is not completely faithful to the Haskell lexical syntax.read: ambiguous parse" :: Char -> ShowS = (:) :: String -> ShowS = (++) :: Bool -> ShowS -> ShowS = if b then showChar ’(’ .u) <.t) <. p . STANDARD PRELUDE :: (Read a) => String -> a = case [x | (x. t) | (str.s) (x.t) | ’\\’:t <[dropWhile isSpace s]] lexStrItem s = lexLitChar s . <.reads s.lex r. (str.u) | ("(".’\’’:t) <.lex t] of [x] -> x [] -> error "Prelude.lexString s] where lexString (’"’:s) = [("\""."") <. t) | (ch. -.read: no parse" _ -> error "Prelude.optional s. showChar ’)’ else p :: Bool -> ReadS a -> ReadS a = if b then mandatory else optional where optional r = g r ++ mandatory mandatory r = [(x.lexLitChar s.t) <.u) showChar showChar showString showString showParen showParen b p readParen readParen b g r <."")] = = = lex (dropWhile isSpace s) [(’\’’:ch++"’". u) | (ch.lex t ] -.

lexDigits s] instance Show Int where showsPrec n = showsPrec n .[span isDigit s]. (ds.s)] [(c:sym.u) | (c:t) [(e:ds. (e.Reading at the Integer type avoids -. c ‘elem‘ "+-".u) <.[span isIdChar s]] | (ds.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 "()" .8. t) | (i.t) <.t) lexExp s = [("".t) <.lexDigits (c:cs).[span isSym s]] | (nam.t) [(c:nam.lexFracExp s ] -. PRELUDE PRELUDETEXT lex (c:s) | | | | isSingle c isSym c isAlpha c isDigit c = = = = [([c].()[]{}_‘" isSym c = c ‘elem‘ "!@#$%&*+. toInteger -.readsPrec p r] -./<=>?\\ˆ|:-˜" isIdChar c = isAlphaNum c || c ‘elem‘ "_’" | (sym.possible difficulty with minInt instance Read Int where readsPrec p r = [(fromInteger i.t) <.lexExp t] lexFracExp s = lexExp s lexExp (e:s) | e ‘elem‘ "eE" = [(e:c:ds.’:ds++e..Converting to Integer avoids -. (fe.lexDigits t] ++ | (ds.[s].’:c:cs) | isDigit c = [(’.t) <.bad character lexFracExp (’.t) <.s)] <.s) <.t) 123 | otherwise = [] where isSingle c = c ‘elem‘ ".2.u) | (ds.t) <.t) [(c:ds++fe.u) <.

u) <. showChar ’.".lex r.’ . showl cs where showl "" = showChar ’"’ showl (’"’:cs) = showString "\\\"" .y) = showChar ’(’ . reads s. showl cs showl (c:cs) = showLitChar c . lex v ] ) . t) <.b) where readsPrec p = readParen False (\r -> [((x.t) (". shows x .s) (x.w) -. lex t.t) | (’\’’:s. (cs. showLitChar c .readLitChar s]) readList = readParen False (\r -> [(l.readLitChar s.t) <.b) where showsPrec p (x.s)] readl (’\\’:’&’:s) = readl s readl s = [(c:cs.readl t ] instance (Show a) => Show [a] where showsPrec p = showList instance (Read a) => Read [a] where readsPrec p = readList -.t) | (’"’:s. Show b) => Show (a.t) <.s) <.t) | ("(". w) | ("(". shows y .u) | (c .lex s ] ) instance Show Char where showsPrec p ’\’’ = showString "’\\’’" showsPrec p c = showChar ’\’’ .v) (")".lex r.readl s ]) where readl (’"’:s) = [("". (c. Read b) => Read (a._) <.t)<. showChar ’)’ instance (Read a.Other tuples have similar Read and Show instances <<<<<- lex r. showChar ’\’’ showList cs = showChar ’"’ . (l.y).lex r.124 CHAPTER 8.Tuples instance (Show a."\’") <. reads u. showl cs instance Read Char readsPrec p where = readParen False (\r -> [(c.u) (y. (")". STANDARD PRELUDE instance Read () where readsPrec p = readParen False (\r -> [(().

appendFile. writeFile. userError. Eq IOError where . :: = :: = :: = IOError -> IO a primIOError String -> IOError primUserError IO a -> (IOError -> IO a) -> IO a primCatch :: Char -> IO () = primPutChar :: String -> IO () = mapM_ putChar s putStrLn :: String -> IO () putStrLn s = do putStr s putStr "\n" print print x getChar getChar getLine getLine :: Show a => a -> IO () = putStrLn (show x) :: IO Char = primGetChar :: IO String = do c <.. interact... putChar. getChar. readFile.8. print. putStrLn.getLine return (c:s) getContents :: IO String getContents = primGetContents ..3 Prelude PreludeIO module PreludeIO ( FilePath. readLn ) where import PreludeBuiltin type FilePath = String -. PRELUDE PRELUDEIO 125 8. getContents.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 .3. getLine. ioError.getChar if c == ’\n’ then return "" else do s <. IOError. putStr. readIO. catch.

reads s.readIO: ambiguous parse") readLn :: Read a => IO a readLn = do l <.raises an exception instead of an error readIO :: Read a => String -> IO a readIO s = case [x | (x. ("".The hSetBuffering ensures the expected interactive behaviour interact f = do hSetBuffering stdin NoBuffering hSetBuffering stdout NoBuffering s <.getContents putStr (f s) readFile readFile writeFile writeFile :: FilePath -> IO String = primReadFile :: FilePath -> String -> IO () = primWriteFile appendFile :: FilePath -> String -> IO () appendFile = primAppendFile -.readIO: no parse") _ -> ioError (userError "Prelude.lex t] of [x] -> return x [] -> ioError (userError "Prelude. STANDARD PRELUDE interact :: (String -> String) -> IO () -.t) <.getLine r <.126 CHAPTER 8.readIO l return r ."") <.

and lambda abstractions extend to the right as far as possible. . Similarly. A precedence-level variable ranges from 0 to 9. this means that conditionals. right. the nonterminals . there are some ambiguities that are to be resolved by making grammatical phrases as long as possible. this is the “maximal munch” rule. 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  ¢ . In both the lexical and the context-free syntax. . or for left-. Thus. In the lexical syntax.or nonassociativity and a precedence level. In the context-free syntax. resolving shift/reduce conflicts by shifting). for example actually stands for 30 productions. 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). and may have a double index: a letter .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 BNF-like syntax is used throughout. let-expressions. an associativity variable varies over . proceeding from left to right (in shift-reduce parsing.Chapter 9 Syntax Reference 9.

. / < = > ? \ ˆ | . 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.{-} a carriage return a line feed a vertical tab a form feed a space a horizontal tab any Unicode character defined as whitespace CHAPTER 9. [ ] ` { }       ¤ ¤©  ¤ ¥  § 2 " § ! ¢  §¢   ©    ¥¢  ¤   ¤   © ¦ 7 ¦ 43¤   3§ ¢ 32 ¡    ©     ¢   § ¦ ¨¦¤   © § ¥ £  ¤¢ ¡   ¤¥      § ¦ § ¤   § § 7 3§ ¢ ¤ 7  4¦ ¢   ¡  ¢ 7  -.˜ any Unicode symbol or punctuation y B         2 4 3 t  ¢ h h h h A v f 4 x"$ wg " 5 7 2 ' 4 3 t § ¦ £$  § 7 2 ' 4 3 t  © ¢ A B Z any uppercase or titlecase Unicode letter _ : " ’    %¤   ¢ u  8 8 8 @¥¥9 ¦ £$    2¤   ¢ u  ¢ © 2 3© 4  7 ' § £$   2¤   ¦ ¢u ©   %¤   ¢ ¢ u ¢7   %¤    S¢RQFP§   4 32 ¦    © G E C ¦ 4  _ a b z any Unicode lowercase letter  77 !3¢ 4 t §  8 8 8 @¥¥9  ¦ £$  4 © 77 03¢  ¢ t 4 § £$ ¦ 703¢ 7 4 t © 77 !3¢  §¢© t 4 77 !3¢  § #¥ ¡3 §¢ ¦  ¤   G E QFC    © G E S¢RQFC ¢   © G E C 4 ¡  IHFD32   ©   ¥ ©  ¢ ¦ § ¦¥  4 32 ¦ 4 4 2   B2  © 4 2  ¥  ¥2 ¦ 7  ¡ ©   ¥ © ¦ ¦ ¥  4 4 ¢ 2 §    § ¨)§ § ¥ (   ¦ £$ ' ¨¢ § © ¤ ¥   § ¨¦£ § ¥ ¢  & $ § © § ¥ %¤  § ¨¦£  ¢ ¤£¡ © § ¥   § ¨¦£ §  ¤¢ ¡     1§3¥0 0 4 ¤ 2 ¦ § ¥   ¤ ' #¢   ¢2  ¦ §   0 ¦ ¦¤ $§ §£%¢  ¤7 ¦§ £   ¦ 7   6  6 6 6 7 ¤ 3¢ ¥  § ¡ § 7 3¢ 7   ©   ¥  ¡  4 ¢ 4 ¤ ¡&¤ 7   2 ¢ ¡ .

¤ ¦ ¦ § ¦ ¦ § ¦ ¦ § ¦ ¦ § ¦ ¦ § ¦ ¦ 2 4 2 4   2 4   2 4   2 4   2 4        § ¦32 ¦ § ¦32 ¦ ¦ 32 § ¦ § ¤ ’ " \ 0o 0x e E + - . .-> 0 1 9 any Unicode decimal digit 0 1 7 A F a f variables constructors type variables type constructors type classes modules    y   @  7 2 '  8 8 8 @¥¥9   8¥8¥8   § §   § ¦  8 8 8 @¥¥9   8 8 8 @¥¥9  .4§    §§ ©   § 2  7 ¢  7 3¢  ¦  ¢       ©      ©  ) h ¡ 5)¢ ¡ 5¢   ¢ ¨£¡    ©      ©  ) h ¡ 5¢   ¢ ¨£¡ o \&   ¢ ¦  ¤   ¡ §¢  ¤   ¡ §¢  4§   ¨    7 3¢ §  ¦  ¦ ¦32 ¢¡    4 §    7 ¨ §   ¦32 ¡  ¦ ¢ 4 §   ¡ 3¢ 4 §    ¦ ¦ ¦ 7 ¢ 4 §   ¢¡  ¡ ¥   73 ¢  4 §   3¢ ¡  ¥  7 ¢  ¦ ¢ 7 ¢   ¦ ¢ § 2 § 2 7 ¢ 4§   7 3¢  ¦ 7 3¢   § § S  ¢ ¥ § § ¡  ¥ ¢  §§ § § 2  § § § 2  §§ §   §   § §   §  ¦  ¦ § 43¦ 2 ¨  © 4 S¤ `¨  ©  © ¢ %§ ¨    `¨ ¦ 72  3¥ %§ ¨ ¦ ¦ § § ¦ 2 ¨ ¢      ¦       ˜ => ¥ h 9 f £   f 4 f S¥ X¤¢%w5         4  ) " 9¡¦fX¤  f24w5¡    2 3© ¥ £ f  4 ©7 ' 2 4  ©     7 '  : )     4 f ¡$ 4 ¡ "     9. .. . 0O ’ \ " \ 0X ’ 129 " x 7 3¢ 4§    ¦ ¢ ¢ ¡  ¥   ©   § ¨¥ § ¨¥ ¤ ¥ 6 6 6    6 6 6 §   ©   ¡ §¢    #¦ § ¤ § © ¤ ¢ ¡ ¢ 2 ¥  ¢ ¡  ¦ ¦ ¥  32 § ! ¤       § ¦ § 6 4§   7 6 3¢  6 6 6 6 6 6 6 6 6 6 ¦ ¦ ¦ ¢ § 2 73§ ¢    4  ¢ S  ¥ 7 ¢ 4 ¦   © ¦ 32  © 4 © 3¤ ¦ 37 2 § § §      ¢ %§   ¦ 32 ¤ ¢  %§    6  ¦ ¦ © 2 4  %§   %§    ¢ ¤ ¦ ¦ 72  3¥ %§ § ¢¦ 2 § ¦ ¤ ¢ 6 6 6   6 6 6 2   ¥¢  ¤  ¤   © ¡ ¦ 43¦ 2  © 4 S¤   © ¢ ¦ ¦ §   ¥¢   ¤   © ¦ ¦ § § ¦ 2 ¢ ¤   ¤ 6 6 6 6 §§  § §§  § § § S  ¥ ¢ §§§ € § €  2 ¦ £$ © ¢ . . .2. : :: = \ | <. 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¢  : : .

The effect of layout is specified in this section by describing how to add braces and semicolons to a laid-out program. – A positive integer. this lexeme is preceded by where is the indentation of the lexeme. So in the fragment f = ("Hello \ \Bill". The meaning of this augmented program is now layout insensitive. "Jake") There is no inserted before the \Bill. SYNTAX REFERENCE 9. The specification takes the form of a function that performs the translation. The input to is: A stream of lexemes as specified by the lexical syntax in the Haskell report. ¦  ¦ – If the first lexeme of a module is not { or module. (NB: a string literal it is not. provided that . because it is not the beginning of a complete lexeme. as a consequence of the first two rules. where is the indentation of the next lexeme if there is one.7 gives an informal discussion of the layout rule. with the following additional tokens: – If a let. or of keyword is not followed by the lexeme {. preceded by may span multiple lines – Section 2. or if the end of file has been reached. then no layout tokens will be inserted until either the enclosing context ends or a new context is pushed.. nor before the . The meaning of a Haskell program may depend on its layout.e.130 CHAPTER 9.) A stack of “layout contexts”. If the innermost context is 0. which is the indentation column of the enclosing layout context. u u   – Where the start of a lexeme is preceded only by white space on the same line.3 Layout Section 2. where  ¦    ¦              ¤ ¥   § §#¥¦£ ¤ ¥   § ¨¦£ § ¥   ©   ¢      y  ¢    2¤ ¢ u   ¢                  ¤§ ¦ ¦ ¦     £   ¦ ¦    £  ¦ ¦ 7  ¦    6 6 6 6  ©   7 § @§ ¤ ¡ ¤ § 5¢¦ ¢  ©  ¥  a b f n r t v \ " ’ & ˆ NUL SOH STX ETX EOT ENQ ACK BEL BS HT LF VT FF CR SO SI DLE DC1 DC2 DC3 DC4 NAK SYN ETB CAN EM SUB ESC FS GS RS US SP DEL [ \ ] ˆ _ \ \ ¢   .6. indicating that the enclosing context is explicit (i. then it is preceded by is the indentation of the lexeme. The effect of layout on its meaning can be completely described by adding braces and semicolons in places determined by the layout. in which each element is either:   – Zero. do. where. the programmer supplied the opening brace. the token is inserted after the keyword. because it is not preceded only by white space. This section defines it more precisely.

delivers a layout-insensitive translation of . Unicode characters in a source program are considered to be of the same. where we use “ ” as a stream construction operator.3. where is the result of lexically analysing a module and adding column-number indicators to it as described above. to avoid visual confusion. not 0. u  ¤ ¨ ¥ } ¡ if  !£ ¡   ¤  £      ¡ ¡ ©      § § ¥ © § © ¡        ¥ } ¥ ¡ ¡ if and parse-error   ©  & § © ¥ ¤ § ¡ ¡     ¥ ¨         § © ¥  § § ©  © ©  ¥   § § ¡ ¡ ¨ ©    ¨ ¨     ¥ { ¥ ¡ {    £  £ ¡ ¡ ¡ ¡     § ©   § ¡    ¥    ¥ ¤ § § © ©   § § ¡ ¡ ¥ ¥ } } } parse-error   £ ¡ ¡     ¥ £ § © § ¡ ¥ }     £ £ £ ¡ ¡   £ £ ¤ £ ¡ ¡ ¥   §  & § ¡ ¥ ¥ ¥ ¦  ! ¨ ¥     § ¡    ¥  ¥ ¥ { { { ¡ if if £ ¡   © ©  ¦ ¥ ¥  § § ©  & ©  § ¡ ¥ © ¥ £ ¥ ¥  ¦ § ¡ §      © §  ¥ ¥ . LAYOUT 131 The “indentation” of a lexeme is the column number of the first character of that lexeme. programmers should avoid writing programs in which the meaning of implicit layout depends on the width of non-space characters. . and ¦ ¦ 7 7 . the indentation of a line is the indentation of its leftmost lexeme. .9. fixed. all start a new line. To determine the column number. assume a fixed-width font with the following conventions:     1§3¥0 0 4 ¤ 2 © The first column is designated column 1. § § ¥ ©  § © © ©  ¨©       § §  ¡ ¡  § § § ¥ ¥ ¡ ¡ ¡ £ £ ¥ ¥ ¥ § ¡    ¥ ¥ ¥ ¥ ¥ ¥ ¦ ¦    ¡                              . and “ ” for the empty stream. width as an ASCII character.   For the purposes of the layout rule. } ¡ if if ¥ © ¨   © ¦ ¥  ¢ 2§ ¨   § § ¥ £ ¡ ¨¦¤¢ ¢ © © ¦ ¥  ©  ¡ ¢   The application   ¢2    0 § 2§ ¡ ¦§    ¦¤ $ §£%§   ¤   ¦ §          §  £   ¥ § © ¥ ¦ © The characters   . The definition of is as follows.   A tab character causes the insertion of enough spaces to align the current position with the next tab stop. However.   Tab stops are 8 characters apart.

Note 3. An example is:   § §  &§ u   © u £ ¥ ¦ . ¤ ¥ Note 6. Note 5. any pending close-braces are inserted. checks that an implicitly-added closing brace would match an implicit open 4 £ ¦ Note 1. to mimic the situation if the empty braces had been explicit. the expression ¦  4    The test brace. we ensure that an explicit close brace can only match an explicit open brace. although they could be: for example let }. It is an error at this point to be within a non-layout context (i.132 CHAPTER 9. the definition of p is indented less than the indentation of the enclosing context. because it translates to let { x = e. This clause means that all brace pairs are treated as explicit layout contexts. It can fail for instance when the end of the input is reached. and the tokens generated so far by followed by the token “}” represent a valid prefix of the Haskell grammar.e. A parse error results if an explicit close brace matches an implicit open brace. so empty braces are inserted. For example let x = e. y = x in e’ is valid. ). The side condition parse-error is to be interpreted as follows: if the tokens generated so far by together with the next token represent an invalid prefix of the Haskell grammar. Note 4. For example. since the close brace is missing. If the first token after a where (say) is not indented more than the enclosing layout context. y = x } in e’ The close brace is inserted due to the parse error rule above. Note 1 implements the feature that layout processing can be stopped prematurely by a parse error. u f x = let h y = let p z = z in p in h Here. Some error conditions are not detected by the algorithm.15). The parse-error rule is hard to implement in its full generality. If not. A nested context must be further indented than the enclosing context ( fails. At the end of the input. because doing so involves fixities. including labelled construction and update (Section 3. then parse-error is true. then the algorithm fails. then the block must be empty.4. The token is replaced by . By matching against 0 for the current layout context. which is set in this case by the definition of h. SYNTAX REFERENCE ). Note 2. This is a difference between this formulation and Haskell 1. and the compiler should indicate a layout error. and a non-layout context is active. If none of the rules given above matches.

3. . LAYOUT do a == b == c has a single unambiguous (albeit probably type-incorrect) parse. Programmers are therefore advised to avoid writing code that requires the parser to insert a closing brace in such situations. namely (do { a == b }) == c 133 because (==) is non-associative.9.

Layout and comments apply exactly as described in Chapter 9 in the resulting text. The literate style encourages comments by making them the default. SYNTAX REFERENCE 9.lhs” indicating a literate Haskell file. is an alternative style for encoding Haskell source code.hs” indicating a usual Haskell file and “. with “.134 CHAPTER 9.4 Literate comments The “literate comment” convention. and inspired in turn by Donald Knuth’s “literate programming”.readLine > putStr "n!= " > print (fact (read l)) This is the factorial function. first developed by Richard Bird and Philip Wadler for Orwell. > fact :: Integer -> Integer > fact 0 = 1 > fact n = n * fact (n-1) An alternative style of literate programming is particularly suitable for use with the LaTeX text processing system. The program text is recovered by taking only those lines beginning with “>”. In this convention. and replacing the leading “>” with a space.   Program code ends just before a subsequent line that begins \end{code} (ignoring string literals. By convention. though it may be stylistically desirable. a simple factorial program would be: This literate program prompts the user for a number and prints the factorial of that number: > main :: IO () > main = do putStr "Enter a number: " > l <.   It is not necessary to insert additional blank lines before or after these delimiters. the style of comment is indicated by the file extension. all other lines are comment. all other lines are comment. only those parts of the literate program that are entirely enclosed between \begin{code} \end{code} delimiters are treated as program text. A line in which “>” is the first character is treated as part of the program. 8 8 ¥¥8 . of course). For example. More precisely: Program code begins on the first line following a line that begins \begin{code}. where a line is taken as blank if it consists only of whitespace. Using this style. it is an error for a program line to appear adjacent to a non-blank comment line. To capture some cases where one omits an “>” by mistake.

.9.[1. LITERATE COMMENTS \documentstyle{article} \begin{document} \section{Introduction} 135 This is a trivial program that prints the first 20 factorials.4. It is not advisable to mix these two styles in the same file.n]) | n <.. \begin{code} main :: IO () main = print [ (n.20]] \end{code} \end{document} This style uses the same file extension. . product [1.

as . ¨ §¤ A A 5  4 ¦ ¢ ) 8 8 ¥¥8 . . ) ¨ A§ ¤ 2 4§ 4§ ¡ §¤¤32 4 § ¡§ ¤ 2 8 8¡ ¥¥8 (. ¨ A 5  4 ¦ ¢¥¥8 8 8 ¡ ¢  . .) ( module . .. . . .  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.) ( (.  ¦ ¦ 2  ¤  ©     37 2 ¦  ¤ ¢ 4§ ¡   ©  %§         3¥ %§ ¦ 72  ¤ ¢ ¢ ¡  ¡ ¤32 § ¤ { type data newtype class instance default ( .. )   ¨¡ 8 8 ¥¥8 A !§ ¤ 2 . } . hiding ( .) ( .   4§ 8 8 ¥¥8 ¡ 7 ¥ ¦ ¡ ( . A §¤  8 8 ¥¥8   ¡ ¤ 4 ¦ ¢  2 4 . . . = => => => => . .. . } = ) = where where ) ) )  ¦ A   8 8 ¥¥8 7¥   ¦ 7 ¥ ¦      6 6 ©    2§ 7¥   ¦ ¡ 2 § 7 ¥ ¦ ¡ ¢   %§  %§     6 6   § 4 ¦ ¢  ¤ 32 ¡ © 4§ 4§ 4§ ¡ 6    ¡ ¡   6 7   ¦    6 6 § ¤ ¤32 ¢ ¡  ¡ ¡ ©§ ¤ @¤32 ¢ ¡  4§    6 6 6 © 7    ¦ ¡ 4§  ¦ ' 2   $ 7 ¦ 2 4 CHAPTER 9.   8 8 ¥¥8 ¡ ¢  import qualified 2 4 ¨   ¦ ¦ §  ¡ ¤ 4 ¢¦  8 8 ¥¥8 ( .) ( (. } } ©   2§ . .5 Context-Free Syntax 136 module where  2 ¨ ©§ ¤ 5@¤32 ¢ ¡  § 2 4 ¦ ' { { { . ) ¦ ¨ A§ ¤ !¤32 ¢ S  (.. SYNTAX REFERENCE .

}  ¦ ¡ 7  ¦ $ ¥ £0 7      ¦      ¦ { . CONTEXT-FREE SYNTAX { . . ) unit type list constructor function constructor tupling constructors   ¦ 32       %§  ¡ ¡  %§  %§  %§ ¡ ¤  ( ( ) ) )  ¦ A © S© ¢ ¥ ©¡ 7 7 § S  § ¢ 4§ © ©  ¦ 32 © © ¢ ¥ 7 ¦ 2  § ¡  § ¢ ¦ 32   %§     ¡    %§ ¢ '  %§   ' ¡    %§ 6 ¡ 6 6 6   6 6 6 ©  %§ § ¢    © S¤ © ¢ 2 ¡ ¢ 2 ¡  ¢  7 ¥ ¦   ¦ ¥       § ¦ § 7   ¦ 7  6 6 ©     7¥   ¦ 7 ¥ ¦  137 . . infixl infixr infix   ¦ A §¤  ¦ A¢ 2 ¡  8¥¥8 8 8 8 ¥¥8 ©   ¨ -> function type type application   ¨     ¡  %§  %§ ¢   ¨   ¡    %§ '  %§  ¡ ¡ ¤ ¡  %§ § ¢   © ¤ ( [ ( . . }  empty  ¦ A   § :: => type signature fixity declaration empty declaration  . ] ) . . ) 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. . .5.

! } . CHAPTER 9.   { :: } :: ! deriving ( . .      ¡   ¡ v v       ¢ S  ¡  ¡ ¡ v ¢ ¡  ¡ ¡ v   A!¡ § 8 8 ¥¥8 7  ¡ § ¢ ¡ ¢ ¡ ¢ ¤ £5¢ 2  ¡ £v §¢ ¡  p v §e ¢  ¦  ¢ ¡  2 ¢ ¡   s ¡ p v §e ¢© ¨ ¡ expression type signature ¡  ¡  V  ¤ ¡ ¦   ¡       ¦ © ¥ ¨© ¨ 7 © ¥ 7 ¥ ¦   ¡     9§ § ¢ §¢ ¤  £5¢ 2 ¡ ¢ ¡ § v ¢£¡ p v ¢ §e ¡  § ¡ v © ¢ £¡ p v ¢ §e § 2 ¡ v ¢£¡ p v ¢ 0e $  § ¡ ¢ ¡ £5¢   © ¥ £0 ¦ $ ¤  ¡7 v § ¢ 2¢ &¤  § £¡ ¡ ¢ v £ 7¡ ¢ ¤  ¡ v§ ¢ ¢ ¤ £ ¡ ¢  §   ¢ ¡ £5¢ ¢ ¢ ¢   ¤  ¢ ¦ § ¢      £ ¤  %§ ¡ ¤  %§ ¢ ¤ ¢  %§  ¢  ¤  %§ ¥¥8  ¡ ¤  %§ 8 8   ¤ B%§ ¢ ¥¥8 ¡ ¤  %§ ¦ 2 ¢ %§     8 8     ¢ ¢  %§ ¦ 32  © ¦ §  ¢ ¥ ¦ 7  ¦ ¦ §   2©¦ 2   ¡ ¦32    ¦    arity infix  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   %§  ¡ ¢  ¢ %§ ¡  { ! . ] -> . )  © 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   . SYNTAX REFERENCE )  ¦  A© §S© 8 8 ¥¥8 ¡ © ¤S©  © S© 7 ¥  %§  ¢ 7¥ 3  ¦ ¡  %§ ¢  ¢ 7¥  ¦    ¡  %§ ¡  %§ ¤   ¡     ( ( [ ( ) distinct distinct  © S¤ ¢  %§  .

. . .5. ]  ¦  )   )   )  -    ( ) right section labeled construction labeled update  { ¦ §    . . CONTEXT-FREE SYNTAX do { } do expression function application  variable general constructor  ¤ ¢  ¡ © @§ ¢ S  ¢ 4§ © ¨ ¡ ¢   S¢0  139 ¡ ¢   S¢0 ( ( [ [ [ ( ( ( ) . }   ¦     { . = ¢ ¡    + 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 § © . ]     . ) ]       ¢ £  . ¨ ©   ¦ ¨5© 7    7 ¥ ¦ A§   -> where where . ¡  §     § § ¦ 4 ¢ ©  %§ ¡ 4 ¥   © ¦ §  ¢ £¡ ¦   ¡ §  3  § § ¢ ¦¤ 5  § 7 3¢    %§ ¡ 4    ¦     7 3¢   £¡ ¦ ¢ ¢ £¡ ¢ ¡  §   ¡ ¥¥8 ¢ £¡ ¡§ 8 8 7 3¢ ©   A ¦§ ¦ ' ¡       0 ¡ ¦§ 0 8 8 ¥¥8 ) A 9 g © ¡  ¨ ¢ ¦ A ¦ § 0 8¥¥8 ' ¡ ¦ § 0 ¦¡ 2 ¢ 8 ¦ ¦ ' '  ¢ S  ¤ ) 2  v ¡ p v ¢ ¡e ¡   ¢ S  ) 2  ¡ v ¡ p v ¢ $0e ¡ 2  v S  ¢ p v ¢ 5e ¡ A ¡ ¡ 7 2  ¢ ¡ v ¡ p v £!e ¡ ¢ $ A  ¥8¥8 $ ¡  $ ¢ ¡  8 7 3¢ ¨ ¥ ¢¡  ¢ ¡¢ ¨ £ 7 ¡  ¢ ¡ ¡  ¡   ¢ S  ¢ 8¡ ¥¥8   ¡ ¡ ¡  8   ¡¡ ¡¢ ¢S  ¡ ¡  8 ¥8¥8   ¡¡ ¡ ¡  ¢ ¡   § § ¤ 7 3¢ ¦ 2 7      9. .. }  ¦ <let generator local declaration guard   ¢ ¡  7  . . <let . -> . | parenthesized expression tuple list arithmetic sequence list comprehension left section left section right section  ¤ ¥ £  ¢  .   ¢ ¡  ¨ § .

. . SYNTAX REFERENCE negative literal arity  as pattern arity labeled pattern       £¡ ¢ ¢ £¡ ¢ ¡ £§¢ ¨§  ¦ 32    { . }  § 0 8 8 ¥¥8 ¡§ 0 ¤   § § 7 3¢ ¦ 2 7 ¦ 2 ¤   y   _ ( ( [ ˜ wildcard parenthesized pattern tuple pattern list pattern irrefutable pattern   ) .  ¤  ¢      £¡ ¢ §   £¡ ¢ . . .  4 © ¦ 3332   2 ¦ ©32    2 ¤   ¡ ©¦ 2  ¡ &¤¢  2 2  ¦ ¡ 4  ©¡ ¢ § 32   3¦ 2   ¦ ¦ 4 © ¦ § 32  33 2 ¦   4 S¤   ©  § ¤   ¦ ¢ 4 © 3¤¢  § ¤   ¦ 4 32 ¢    § ¦ 2 ¢   © ¦ ¦ ¦ 4 © ¦ 3332  § 3 2 ¦ 43¤    § ¤  ©   4 © 3¢S¤   ¦ § ¤¢  ¦ ¢ ¢ ( ( ( ( ` ` ` ` ¢ £¡      ¦ § ¢  ¦    ¦ 32   ¢   ¢          ¢ £¡ ¡ 2©¦32  ¡      § ¦ 2   8 ¥8¥8 ¡ §   ¢ §¢ ¡ ¢£¡§¢ §  ¢ ¡ £§¢  ¡ v§  v§ ¤ v 2 ©¦32  §  ¢ ¡ ¢£¡  p  ¢ § §e 2 ¡ !¡ ¤¥      ¡ § ¦ v § £¡  ¢ § 2 ©¦32 s¢  ¡ v §  §  ¡ v © ¢ £¡ p v ¢ §e ¡  ¢ ¡ v £ 7¡ ¤ ¢ § v £¡ ¢ § v ¢£ 7¡ ¨ ¡ v§ § v ¢£¡ p v ¢ §e ¦ ¢ £¡     ¤ § 140 - CHAPTER 9. ) ) variable qualified variable constructor qualified constructor variable operator qualified variable operator constructor operator qualified constructor operator operator qualified operator   )   )   )   `   `   `   `     6 6 6 6 6 6 6 6 6 6    6 6  ¦ 2   ¤ ¢ § ¢£§¢ ¡ ¡§ ¢£¡ ¡§ ¢£¡ ¢ £¡ § :    4 32    © ¦ 2  ¡ 2 2 ¦ ©32 ¡  ¡ ©¦  2 2 ¡ &¤  2  ¡ 2 ¤¢  ¡ ¦32 ¢  ¦ 2 ¤    ¤¢ ¢  ¦ 32    6 § ¢ £¡ 0           ¢  6 § ¢ ¡ £§¢  6 6    6 6 6 § ¢ ¤ ¤ ¡ £¡ § v ¢£¡ §  ¢£ 7¡ ¢ £ 7¡ v § v § ¢ £¡ . ) ]       ¢   § 8¥¥8 8 8 8 ¥¥8 = § () [] (.

Chapter 10

Specification 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 definition of the associated type. Derived instances are possible only for classes known to the compiler: those defined in either the Prelude or a standard library. In this chapter, we describe the derivation of classes defined 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 fixpoint 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 defined 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 defined 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 first 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 left-to-right 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 definitions 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 first 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 define the minimal and maximal elements of the type. For an enumeration, the first 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 satisfies the law: showsPrec d x r ++ s == showsPrec d x (r ++ s) The representation will be enclosed in parentheses if the precedence of the top-level 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 tree-like 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 infix 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 non-standard 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 fixity declarations in force at the point where the type is declared. It contains only the constructor names defined in the data type, parentheses, and spaces. When labelled constructor fields are used, braces, commas, field 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 defined in the Prelude but may not be true for user-defined instances.) Derived instances of Read make the following assumptions, which derived instances of Show obey: If the constructor is defined to be an infix operator, then the derived Read instance will parse only infix applications of the constructor (not the prefix 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 defined using record syntax, the derived Read will parse only the recordsyntax form, and furthermore, the fields 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 inefficient; reading a large structure may be quite slow. There is no user control over the printing of types defined in the Prelude. For example, there is no way to change the formatting of floating 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 single-constructor datatype. The complete instance declarations for Tree are shown in Figure 10.1, Note the implicit use of default class method definitions—for example, only <= is defined for Ord, with the other class methods (<, >, >=, max, and min) being defined by the defaults given in the class declaration shown in Figure 6.1 (page 83).

(":ˆ:".the most tightly-binding operator Figure 10.Note: right-associativity instance (Read a) => Read (Tree a) where readsPrec d r = readParen (d > up_prec) (\r -> [(u:ˆ:v. (m.s) <.readsPrec (up_prec+1) r. . (v.readsPrec (up_prec+1) t]) r > up_prec) showStr u .w) <.s) <.t) <. 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 " .t) <.146 CHAPTER 10.Precedence of :ˆ: -.lex s. showsPrec (app_prec+1) m showsPrec d (u :ˆ: v) = showParen (d where showStr = showsPrec (up_prec+1) showString " :ˆ: " showsPrec (up_prec+1) -.readsPrec (app_prec+1) s]) r up_prec = 5 app_prec = 10 -. v of :ˆ: ignored ++ readParen (d > app_prec) (\r -> [(Leaf m.t) | ("Leaf".Application has precedence one more than -.1: Example of Derived Instances .lex r.w) | (u.

Chapter 11 Compiler Pragmas Some compiler implementations support compiler pragmas. Lexically. This may be prevented by the NOINLINE pragma. #-}   ¢    ¡  © S¤ ¡   {-# INLINE {-# NOINLINE   ¢ ¡  %§ ¥ §¥ © ¤ ¢  6 6 6 6 7¥   ¦ 7 ¥ ¦  ¡   7 ¥ ¦ #-} #-}     © . An implementation is not required to respect any pragma. This chapter summarizes this existing practice.2 Specialization    © Specialization is used to avoid inefficiencies involved in dispatching overloaded functions. For example. but which do not form part of the Haskell language proper and do not change a program’s semantics.1 Inlining ¢ ¤ © © The INLINE pragma instructs the compiler to inline the specified variables at their use sites. pragmas appear as comments. except that the enclosing syntax is {-# #-}. 11. . which are used to give additional instructions or hints to the compiler. but the pragma should be ignored if an implementation is not prepared to handle it. Compilers will often automatically inline simple expressions. 11. in 147 8 8 ¥¥8 ¡   {-# SPECIALIZE   .

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 (n-1) {-# SPECIALIZE factorial :: Int -> Int. .148 CHAPTER 11.

Part II The Haskell 98 Libraries 149 .

.

. the results may be unpredictable.. The functions numerator and denominator extract the components of a ratio. and Show... Show (Ratio a) where ... Enum (Ratio a) where . RealFrac. If is a bounded type. approxRational ) where infixl 7 % data (Integral a) => type Rational = (%) :: numerator. Ord. Fractional (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. for example Ratio Int may give rise to integer overflow even for rational numbers of small absolute size.. Rational. numerator.. In each case. Ratio Integer (Integral a) => a -> a -> Ratio a (Integral a) => Ratio a -> a (RealFrac a) => a -> a -> Rational Eq (Ratio a) where .. 151 ¡ ¡ ¡ ¡ ¡ ¡ . (%). the instance for Ratio simply “lifts” the corresponding operations over . reducing the fraction to terms with no common factor and such that the denominator is positive.. Ord (Ratio a) where . Num. these are in reduced form with a positive denominator. RealFrac (Ratio a) where . Real (Ratio a) where . Num (Ratio a) where . Read. a) => Read (Ratio a) where .. The type name Rational is a synonym for Ratio Integer. there is a type Ratio of rational pairs with components of type .. The operator (%) forms the ratio of two integral numbers. Enum... Ratio is an instance of classes Eq.... Fractional.Integral instance (Integral a) => Ratio a = .Chapter 12 Rational Numbers module Ratio ( Ratio. Real. denominator.... For example. 12 % 8 is reduced to 3/2 and 12 % (-8) is reduced to (-3)/2. For each Integral type . Ratio is an abstract type.

1 ¦   ¦   1 ¦    ¦   1  1 ¦   ¦    ¦   ¡¦ .152 CHAPTER 12. RATIONAL NUMBERS The approxRational function. A rational number in reduced form is said to be simpler than another if and . 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 .

Rational. LIBRARY RATIO 153 12.1. denominator.. (%).Standard functions on rational numbers module Ratio ( Ratio. It normalises a ratio by dividing both numerator and denominator by their greatest common divisor. numerator.g. denominator approxRational ------- :: (Integral a) => a -> a -> Ratio a :: (Integral a) => Ratio a -> a :: (RealFrac a) => a -> a -> Rational "reduce" is a subsidiary function used only in this module.1 Library Ratio -.12. E. approxRational ) where infixl 7 % ratPrec = 7 :: Int data type (Integral a) Rational => Ratio a = !a :% !a = Ratio Integer deriving (Eq) (%) numerator.% : zero denominator" (x ‘quot‘ d) :% (y ‘quot‘ d) where d = gcd x y reduce (x * signum y) (abs y) x y => Ord (Ratio a) where = x * y’ <= x’ * y = x * y’ < x’ * y => = = = = = = Num (Ratio a) where reduce (x*y’ + x’*y) (y*y’) reduce (x * x’) (y * y’) (-x) :% y abs x :% y signum x :% 1 fromInteger x :% 1 => Real (Ratio a) where = toInteger x :% toInteger y => = = = Fractional (Ratio a) where (x*y’) % (y*x’) y % x fromInteger x :% fromInteger y . 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.

simplest’ (-n’) d’ (-n) d | otherwise = 0 :% 1 where xr@(n:%d) = toRational x (n’:%d’) = toRational y simplest’ n | | | d n’ d’ r == 0 q /= q’ otherwise -.assumes 0 < n%d < n’%d’ = q :% 1 = (q+1) :% 1 = (q*n’’+d’’) :% n’’ where (q. RATIONAL NUMBERS instance (Integral a) => RealFrac (Ratio a) where properFraction (x:%y) = (fromIntegral q.hs but not exported from it! instance (Read a. showsPrec (ratPrec+1) y) approxRational x eps = simplest (x-eps) (x+eps) where simplest x y | y < x = simplest y x | x == y = xr | x > 0 = simplest’ n d n’ d’ | y < 0 = .u) | (x.154 CHAPTER 12.r) = quotRem n d (q’.u) <. r:%y) where (q.t) <. truncate -numericEnumFrom -numericEnumFromThen -numericEnumFromTo -numericEnumFromThenTo May overflow These numericEnumXXX functions are as defined in Prelude. ("%".readsPrec (ratPrec+1) r.r) = quotRem x y instance (Integral a) succ x = pred x = toEnum = fromEnum = enumFrom = enumFromThen = enumFromTo = enumFromThenTo = => Enum (Ratio a) where x+1 x-1 fromIntegral fromInteger .lex s. showString " % " .r’) = quotRem n’ d’ (n’’:%d’’) = simplest’ d’ r’ d r . (y.s) <.readsPrec (ratPrec+1) t ]) instance (Integral a) showsPrec p (x:%y) => Show (Ratio a) where = showParen (p > ratPrec) (showsPrec (ratPrec+1) x . Integral a) => Read (Ratio a) where readsPrec p = readParen (p > ratPrec) (\r -> [(x%y.

. the entire number is .Chapter 13 Complex Numbers module Complex ( Complex((:+)).. (RealFloat a) realPart. conjugate. A complex number may also be formed from polar components of magnitude and phase by the function mkPolar. cis... if the magnitude is zero. magnitude. imagPart conjugate mkPolar cis polar magnitude. 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. imagPart. The function cis produces a complex number from an angle . phase) pair in canonical form: The magnitude is nonnegative. . . in the range . realPart. The constructor (:+) forms a complex number from its real and imaginary rectangular components. and the phase. . Put another way. polar... 155 § ¨           §     ¡¤ §  . The function polar takes a complex number and returns a (magnitude. cis is a complex value with magnitude and phase (modulo )... mkPolar. . 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..a) Complex a -> a a) a) a) a) a) a) where where where where where where .. This constructor is strict: if either the real part or the imaginary part of the number is .. then so is the phase.. .

abs is a number with the magnitude of . conjugate.     13.156 CHAPTER 13.Show) (RealFloat a) realPart. mkPolar.k phase :: (RealFloat a) => Complex a -> a phase (0 :+ 0) = 0 phase (x :+ y) = atan2 y x .1 Library Complex module Complex(Complex((:+)).a) = (magnitude z. polar. The function conjugate computes the conjugate of a complex number in the usual way. whereas signum has the phase of . phase z) magnitude :: (RealFloat a) => Complex a -> a magnitude (x:+y) = scaleFloat k (sqrt ((scaleFloat mk x)ˆ2 + (scaleFloat mk y)ˆ2)) where k = max (exponent x) (exponent y) mk = . phase) where infix data 6 :+ => Complex a = !a :+ !a deriving (Eq. imagPart. 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. realPart. but unit magnitude. cis. magnitude.Read. but oriented in the positive real direction. COMPLEX NUMBERS The functions realPart and imagPart extract the rectangular components of a complex number and the functions magnitude and phase extract the polar components of a complex number. The magnitude and sign of a complex number are defined as follows: abs z signum 0 signum z@(x:+y)   = = = magnitude z :+ 0 0 x/r :+ y/r where r = magnitude z   That is.

13.1. LIBRARY COMPLEX instance (RealFloat a) (x:+y) + (x’:+y’) (x:+y) .max (exponent x’) (exponent y’) d = x’*x’’ + y’*y’’ fromRational a = fromRational a :+ 0 .(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’) (x-x’) :+ (y-y’) (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 = .

z*z)) y’’:+(-x’’) where (x’’:+y’’) = log (z + ((-y’):+x’)) (x’:+y’) = sqrt (1 . COMPLEX NUMBERS instance (RealFloat a) => Floating (Complex a) where pi = pi :+ 0 exp (x:+y) = expx * cos y :+ expx * sin y where expx = exp x log z = log (magnitude z) :+ phase z sqrt 0 sqrt z@(x:+y) = = 0 u :+ (if y < 0 then -v else v) where (u.z*z) y’:+(-x’) where (x’:+y’) = log (((1-y):+x) / sqrt (1+z*z)) log (z + sqrt (1+z*z)) log (z + (z+1) * sqrt ((z-1)/(z+1))) log ((1+z) / sqrt (1-z*z)) sin (x:+y) cos (x:+y) tan (x:+y) = = = sinh (x:+y) cosh (x:+y) tanh (x:+y) = = = asin z@(x:+y) acos z@(x:+y) = = atan z@(x:+y) asinh z acosh z atanh z = = = = .158 CHAPTER 13.sin x * sinh y) (sinx*coshy:+cosx*sinhy)/(cosx*coshy:+(-sinx*sinhy)) where sinx = sin x cosx = cos x sinhy = sinh y coshy = cosh y cos y * sinh x :+ sin y * cosh x cos y * cosh x :+ sin y * sinh x (cosy*sinhx:+siny*coshx)/(cosy*coshx:+siny*sinhx) where siny = sin y cosy = cos y sinhx = sinh x coshx = cosh x y’:+(-x’) where (x’:+y’) = log (((-y):+x) + sqrt (1 .v) = if x < 0 then (v’.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 :+ (.u’) else (u’.

floatToDigits. showOct. showFFloat. showEFloat. lexDigits) where fromRat showSigned showIntAtBase showInt showOct showHex readSigned readInt readDec readOct readHex showEFloat showFFloat showGFloat showFloat floatToDigits readFloat lexDigits :: (RealFloat a) => Rational -> a :: :: :: :: :: (Real a) Integral Integral Integral Integral => (a -> ShowS) -> Int -> a -> ShowS a => a -> (Int -> Char) -> a -> ShowS a => a -> ShowS a => a -> ShowS a => a -> ShowS :: (Real a) => ReadS a -> ReadS a :: (Integral a) => a -> (Char -> Bool) -> (Char -> Int) -> ReadS a :: (Integral a) => ReadS a :: (Integral a) => ReadS a :: (Integral a) => ReadS a :: :: :: :: (RealFloat (RealFloat (RealFloat (RealFloat a) a) a) a) => => => => Maybe Int -> a -> ShowS Maybe Int -> a -> ShowS Maybe Int -> a -> ShowS a -> ShowS :: (RealFloat a) => Integer -> a -> ([Int]. readDec. showInt. readHex. showGFloat. readInt. showFloat. readOct. showHex. readSigned. showIntAtBase. readFloat. showSigned. Int) :: (RealFrac a) => ReadS a :: ReadS String 159 .Chapter 14 Numeric module Numeric(fromRat.

showGFloat :: (RealFloat a) => Maybe Int -> a -> ShowS These three functions all show signed RealFloat values: – showFFloat uses standard decimal notation (e. – showEFloat uses scientific (exponential) notation (e.           showInt. showIntAtBase :: Integral a => a -> (Int -> Char) -> a -> ShowS shows a non-negative Integral number using the base specified by the first argument. plus an exponent. and is a function that can show unsigned values. recall the following type definitions from the Prelude: type ShowS = String -> String type ReadS = String -> [(a.45e2.String)] 14. showOct. 2. and 16 respectively. 0. £    ¤ ¡ ¡     ¡ ¢  ¦ 7 3¢ ¦  7 3¢    7 3¢ ©  §  ¦  ¤ ¥  £   2 ¤ ¥ © ¡ ©  § ¦ ¡ £ ¦ 2   ¥ © ©  §  ¦ ¡  ) . is the value to show. and scientific notation otherwise. NUMERIC This library contains assorted numeric functions. showEFloat. 1. many of which are used in the standard Prelude.5e-3). then at most digits after the decimal point are shown. the value is shown to full preciIn the call showEFloat sion.1 Showing functions showSigned :: (Real a) => (a -> ShowS) -> Int -> a -> ShowS converts a possibly-negative Real value of type a to a string.1 and 9. 8. and the character representation specified by the second. . showHex :: Integral a => a -> ShowS show non-negative Integral numbers in base 10. 245000. floatToDigits :: (RealFloat a) => Integer -> a -> ([Int]. In what follows.999.g.g.999. More specifically.160 CHAPTER 14. if ©  § then the following properties hold: £ £ ¤ – ¤ £       ¡ ¤ – (when ¥ ¤ ¢    ¨£ –   £ 888 ¤ £ ¢ £8 ¤     – ¥ ) £888 ¤ £ ¢ £  floatToDigits ([ ]. Exactly the same applies to the argument of the other two functions. – showGFloat uses standard decimal notation for arguments whose absolute value lies between 0. Int) converts a base and a value to the representation of the value in digits. if is Nothing. In the call showSigned . showFFloat. if is Just .0015). is the precedence of the enclosing context.

showIntAtBase. showHex. is the base.2 Reading functions readSigned :: (Real a) => ReadS a -> ReadS a reads a signed Real value. in decimal.3 Miscellaneous fromRat :: (RealFloat a) => Rational -> a converts a Rational value into any type in class RealFloat.2. readOct. octal. readOct.  § (NB: readInt is the “dual” of showIntAtBase. isHexDigit digitToInt. readHex. showFFloat. showFloat.             readInt :: (Integral a) => a -> (Char->Bool) -> (Char->Int) -> ReadS a reads an unsigned Integral value in an arbitrary base. readFloat :: (RealFrac a) => ReadS a reads an unsigned RealFrac value. showEFloat. readInt. numerator. denominator ) (!). In the hexadecimal case. readFloat. given a reader for an unsigned value. is a predicate distinguishing valid digits in this base. readDec. intToDigit ) (%). lexDigits) where import Char import Ratio import Array ( . READING FUNCTIONS 161 14. showSigned. array ) ¦ ©§   ¢© ¢ '  § ¤ ¦  § ¦ ©§ § ¤ ¦   ¢© ¢ '  . Array. 14. The inconsistent naming is a historical accident. readHex :: (Integral a) => ReadS a each read an unsigned number. expressed in decimal scientific notation. showGFloat. and readDec is the “dual” of showInt. showOct.14. isOctDigit. and hexadecimal notation respectively. both upper or lower case letters are allowed. showInt.) 14. floatToDigits.4 Library Numeric module Numeric(fromRat. lexDigits :: ReadS String reads a non-empty string of decimal digits. and converts a valid digit character to an Int. ( ( isDigit. In the call readInt . readDec. readSigned.

Then round the rational to an Integer and encode it with the exponent -.p) ‘max‘ minExp f = if p0 < 0 then 1 % expt b (-p0) else expt b p0 % 1 (x’.162 CHAPTER 14.Scale x until xMin <= x < xMax. -. -.p -.Conversion process: -. fromRat :: (RealFloat a) => Rational -> a fromRat x = if x == 0 then encodeFloat 0 0 else if x < 0 then . Int) scaleRat b minExp xMin xMax p x = if p <= minExp then (x.first.Exponentiation with a cache for the most common numbers.Scale the rational number by the RealFloat base until -.Handle exceptional cases -. 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 . 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 (p-1) (x*b) else (x.it lies in the range of the mantissa (as used by decodeFloat/encodeFloat).that we got from the scaling.the real minimum exponent xMin = toRational (expt b (p-1)) xMax = toRational (expt b p) p0 = (integerLogBase b (numerator x) integerLogBase b (denominator x) .To speed up the scaling process we compute the log2 of the number to get -.Fractional instances of Float and Double.a first guess of the exponent.This converts a rational to a floating. p) -. fromRat’ :: (RealFloat a) => Rational -> a fromRat’ x = r where b = floatRadix r p = floatDigits r (minExp0. or p (the exponent) <= minExp. -.fromRat’ (-x) else fromRat’ x -. This should be used in the -. scaleRat :: Rational -> Int -> Rational -> Rational -> Int -> Rational -> (Rational. _) = floatRange r minExp = minExp0 . NUMERIC -. p’) = scaleRat (toRational b) minExp xMin xMax p0 (x / f) r = encodeFloat (round x’) p’ -.

-. maxExpt]] 163 -. 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 -. showOct.Simplest way would be just divide i by b until it’s smaller then b.maxExpt) [(n.14. showHex are used for positive numbers only showInt.s) | (str. integerLogBase :: Integer -> Integer -> Int integerLogBase b i = if i < b then 0 else -."") <<<<- lex r.t) | ("-".showIntAtBase: can’t show negative numbers" | n’ == 0 = rest’ | otherwise = showIntAtBase base intToDig n’ rest’ where (n’.Misc utilities to show integers and floats showSigned :: Real a => (a -> ShowS) -> Int -> a -> ShowS showSigned showPos p x | x < 0 = showParen (p > 6) (showChar ’-’ . showHex :: Integral a => a -> ShowS showOct = showIntAtBase 8 intToDigit showInt = showIntAtBase 10 intToDigit showHex = showIntAtBase 16 intToDigit showIntAtBase :: Integral a => a -.digit to char -> a -. -. LIBRARY NUMERIC expts :: Array Int Integer expts = array (minExpt.4. readPos str] .. showOct.but that would be very slow! We are just slightly more clever.Compute the (floor of the) log of i in base 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.t) read’’ r = [(n.Try squaring the base first to cut down the number of divisions.base -> (Int -> Char) -. showPos (-x)) | otherwise = showPos x -. read’’ s] lex r.showInt.s) (n.2ˆn) | n <.[minExpt .s) (x.number to show -> ShowS showIntAtBase base intToDig n rest | n < 0 = error "Numeric.

readInt reads a string of digits using an arbitrary base. r) | (ds. data FFFormat = FFExponent | FFFixed | FFGeneric . -. digToInt) ds). -. NUMERIC -.164 CHAPTER 14. readInt :: (Integral a) => a -> (Char -> Bool) -> (Char -> Int) -> ReadS a readInt radix isDig digToInt s = [(foldl1 (\n d -> n * radix + d) (map (fromIntegral .Unsigned readers for various bases readDec.r) <.nonnull isDig s ] -. readOct. 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.Leading minus signs must be handled elsewhere.These are the format types.

14. e) FFExponent -> case decs of Nothing -> case ds of [] -> "0.’:take dec’ (repeat ’0’) ++ "e0" _ -> let (ei.’:ds ++ "e" ++ show (e-1+ei) FFFixed -> case decs of Nothing -. is’) = roundTo base (dec’+1) is d:ds = map intToDigit (if ei > 0 then init is’ else is’) in d:’.Always prints a decimal point | e > 0 -> take e (ds ++ repeat ’0’) .4. 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.0e0" [d] -> d : ". e) = let ds = map intToDigit is in case fmt of FFGeneric -> doFmt (if e < 0 || e > 7 then FFExponent else FFFixed) (is.0e" ++ show (e-1) d:ds -> d : ’.’ : ds ++ ’e’:show (e-1) Just dec -> let dec’ = max dec 1 in case is of [] -> ’0’:’.

digits after the decimal point roundTo :: Int -> Int -> [Int] -> (Int.base-1]) -.. b. z]. rs) = splitAt (e+ei) (map intToDigit is’) in mk0 ls ++ mkdot0 rs else let (ei. It should be improved. . [Int]) roundTo base d is = case f d is of (0. not .Print 0. K. Dybvig.34.This function returns a non-empty list of digits (Ints in [0. 1 : is) where b2 = base ‘div‘ 2 f n [] = (0. Int) .Print decimal point iff dec > 0 let dec’ = max dec 0 in if e >= 0 then let (ei. 0:ds) else (0.. is’) = roundTo base (dec’ + e) is (ls.G. if -floatToDigits r = ([a. ds) = f (d-1) is i’ = c + i in if i’ == base then (1.. -.34 mk0 s = s mkdot0 "" = "" mkdot0 s = ’. is) -> (1.and an exponent. -.’ : mk0 (drop e ds) | otherwise -> "0. is) -> (0. NUMERIC ++ ’. Burger and R. In general. in PLDI 96.z * baseˆe -floatToDigits :: (RealFloat a) => Integer -> a -> ([Int].Print 34.166 CHAPTER 14.when the format specifies no -.." ++ mk0 (replicate (-e) ’0’ ++ ds) Just dec -> -. e) -. replicate n 0) f 0 (i:_) = (if i >= b2 then 1 else 0.’ : s -. is) (1. i’:ds) -----Based on "Printing Floating-Point Numbers Quickly and Accurately" by R. The version here uses a much slower logarithm estimator. 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" -. not 34. []) f d (i:is) = let (c.then -r = 0.ab.

the following will err on the low side. 0) floatToDigits base x = let (f0.will have an impossibly low exponent. 1) else (f*2. mDn) = if e >= 0 then let be = bˆe in if f == bˆ(p-1) then (f*be*b*2. _) = floatRange x p = floatDigits x b = floatRadix x minExp = minExp0 .the real minimum exponent -.e0 in if n > 0 then (f0 ‘div‘ (bˆn). Adjust for this. 2. b) else (f*be*2. e0) (r. 1) k = let k0 = if b==2 && base==10 then -. bˆ(-e)*2.logBase 10 2 is slightly bigger than 3/10 so -. s. 1. (p .14. e0) = decodeFloat x (minExp0. e) = let n = minExp . Ignoring -.p 167 -.the fraction will make it err even more.4. be*b.1 + e0) * 3 ‘div‘ 10 else ceiling ((log (fromInteger (f+1)) + fromIntegral e * log (fromInteger b)) / log (fromInteger base)) fixup n = if n >= 0 then if r + mUp <= expt base n * s then n else fixup (n+1) else if expt base (-n) * (r + mUp) <= s then n . e0+n) else (f0. be) else if e > minExp && f == bˆ(p-1) then (f*b*2.Haskell promises that p-1 <= logBase b f < p. LIBRARY NUMERIC floatToDigits _ 0 = ([].Haskell requires that f be adjusted so denormalized numbers -. be. mUp. 2*b. b. bˆ(-e+1)*2. f :: Integer e :: Int (f. -.

s)] readExp’ (’-’:s) = [(-k. t) | ("Infinity".lex r] where readFix r = [(read (ds++ds’).’ is optional.t) | (k.t) <.s) <. True) -> dn+1 : ds (True.t) <.s)] readExp (e:s) | e ‘elem‘ "eE" = readExp’ s readExp s = [(0.d.t) | (n.This floating point reader uses a less restrictive syntax for floating -.lexDigits r. False) -> dn : ds (False. k) in -.readDec s] readExp’ (’+’:s) = readDec s readExp’ s = readDec s lexDigits lexDigits nonnull nonnull p s :: ReadS String = nonnull isDigit :: (Char -> Bool) -> ReadS String = [(cs.t) <. readFloat readFloat r :: (RealFrac a) => ReadS a = [(fromRational ((n%1)*10ˆˆ(k-d)).point than the Haskell lexer. NUMERIC else fixup (n+1) in fixup k0 gen ds rn sN mUpN mDnN = let (dn. rn’) = (rn * base) ‘divMod‘ sN mUpN’ = mUpN * base mDnN’ = mDnN * base in case (rn’ < mDnN’. (k.readExp s] ++ [ (0/0. False) -> gen (dn:ds) rn’ sN mUpN’ mDnN’ rds = if k >= 0 then gen [] r (s * expt base k) mUp mDn else let bk = expt base (-k) in gen [] (r * bk) s (mUp * bk) (mDn * bk) (map fromIntegral (reverse rds).lex r] ++ [ (1/0. True) -> if rn’ * 2 < sN then dn : ds else dn+1 : ds (False. t) | (ds.d) <. length ds’. The ‘.lexFrac d ] lexFrac (’.168 CHAPTER 14.t) <.t) <. (ds’. rn’ + mUpN’ > sN) of (True. t) | ("NaN".readFix r.t) <.[span p s]] .’:ds) = lexDigits ds lexFrac s = [("".t) | (cs@(_:_).

b) where where where where .a) -> [a] a -> Int a -> Bool Int Char Int Integer (a. inRange. It is used primarily for array indexing (see Chapter 16). where .u) i == i ‘elem‘ range (l. index.u) map index (range (l. The range operation enumerates all subscripts..a) -> (a.a) -> (a.Chapter 15 Indexing Operations module Ix ( Ix(range. .. .rangeSize (l... which defines the lower and upper bounds of the range. An implementation is entitled to assume the following laws about these operations: range (l.u)) == [0.u)] 169 ....when i is in range inRange (l. instance instance instance instance (Ix a. the inRange operation tells whether a particular subscript lies in the range defined by a bounding pair.. rangeSize) ) where class Ord a => range index inRange rangeSize Ix :: :: :: :: a where (a.a) -> (a. and a subscript. and inRange. The Ix class contains the methods range.. index. The Ix class is used to map a contiguous subrange of values in a type onto integers.u) i == i -.. The index operation maps a bounding pair.et cetera instance instance Ix Ix Ix => Ix Ix Bool Ix Ordering where . to an integer. Ix b) -...u) !! index (l.. .

170 CHAPTER 15. For an enumeration.1 Deriving Instances of Ix It is possible to derive an instance of Ix automatically. datatypes having only nullary constructors) and single-constructor datatypes.Blue] 1 False . For example. using a deriving clause on a data declaration (Section 4.Green. given the datatype: data Colour = Red | Orange | Yellow | Green | Blue | Indigo | Violet we would have: range (Yellow. This is the same numbering defined by the Enum class.3. the derived instance declarations are as shown for tuples in Figure 15. Such derived instance declarations for the class Ix are only possible for enumerations (i. INDEXING OPERATIONS 15.e.Blue) index (Yellow. £   ¥ ¤   == == == [Yellow.1. whose constituent types are instances of Ix.Blue) Green inRange (Yellow.Blue) Red   For single-constructor datatypes. the nullary constructors are assumed to be numbered left-to-right with the indices being to inclusive. A Haskell implementation must provide Ix instances for tuples up to at least size 15.3).

lk).. DERIVING INSTANCES OF IX 171 instance (Ix a..l’).(u1...u) i && inRange (l’.l’). Ix a2.ik) = -inRange (l1.u2).u1) i1 && inRange (l2.. Ix ak) => Ix (a1.u’)) = [(i.u2...range (l’.l’)..instance (Ix a1.u2) i2 && -.15....i’) = inRange (l..uk)) = -[(i1.range (l2.i’) = index (l.ak) where -range ((l1.....l2. -ik <...u’) + index (l’.i’) | i <.uk-1) * ( -.i2..range (l1..u1))) --inRange ((l1..uk)) (i1..u’)) (i..ik) = -index (lk.b) where range ((l...uk-1) ik-1 + rangeSize (lk-1. -index (l1.l2.Instances for other tuples are obtained from this scheme: --. Ix b) => Ix (a.u1).u’)) (i.u2... -.uk) * ( -index (lk-1....(u.u). && inRange (lk.1: Derivation of Ix instances . ..ik) | i1 <.range (lk. -i2 <.l2....u’) i’ -.uk) ik + rangeSize (lk..uk)) (i1..uk) ik Figure 15...a2.(u1......lk).i2.i2.(u. .uk)] --index ((l1..lk).u) i * rangeSize (l’.(u1..range (l.(u...u’)] index ((l.u’) i’ inRange ((l.u2. i’ <.1.

.2). For example.n) i = m <= i && i <= n instance instance instance instance (Ix a..2) <= (2.index: Index out of range.a) -> a -> Bool rangeSize :: (a.n) i | inRange b i = fromInteger (i .. index.fromEnum c | otherwise = error "Ix. rangeSize) ) where class Ord a => Ix a where range :: (a.1)) = [] instance Ix Char where range (m.fails if the bounds are tuples.(2.as derived.c’) ci | inRange b ci = fromEnum ci .a) -> [a] index :: (a.index: Index out of range.as derived Ix Ordering -.n] index b@(c.c’) i = c <= i && i <= c’ instance Ix Int where range (m.index: Index out of range.NB: replacing "null (range b)" by "not (l <= h)" -." inRange (c.1) -.a) -> Int rangeSize b@(l.172 CHAPTER 15.2 Library Ix module Ix ( Ix(range." m <= i && i <= n instance Ix Integer where range (m. -(1.Ix b) => Ix (a.n) i | inRange b i | otherwise inRange (m.but the range is nevertheless empty -range ((1. for all tuples Ix Bool -.as derived Ix () -.n] = = = i . b) -. INDEXING OPERATIONS 15.n) index b@(m.m) | otherwise = error "Ix.as derived .n) i = [m.n) = [m.n) = [m.n] index b@(m.a) -> a -> Int inRange :: (a.h) | null (range b) = 0 | otherwise = index b h + 1 -." inRange (m. inRange.m error "Ix.

b)] (b -> c -> b) -> b -> (a.. elems. Ix b) => (a. accumArray. .a) -> (a -> b) -> Array b c -> Array a c Eq b) Ord b) Show a.c)] -> Array a b :: (Ix a) => Array a b -> [(a. a.b)] -> Array a b :: (Ix a) => (b -> c -> b) -> Array a b -> [(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 .c)] -> Array a b :: (Ix a. 173 .b)] -> Array a b (a.export all of Ix for convenience Array....a) -> [(a. (//). accum.. indices..a) -> [b] -> Array a b Array a b -> a -> b Array a b -> (a.. a..a) Array a b -> [a] Array a b -> [b] Array a b -> [(a. listArray.Chapter 16 Arrays module Array ( module Ix..Abstract (Ix a) array listArray (!) bounds indices elems assocs accumArray (//) accum ixmap instance instance instance instance instance (a. bounds. assocs. // => Array a b = . array.. . ixmap ) where import Ix infixl 9 data !. . (!). a. . (Ix (Ix (Ix (Ix a. Show b) Read a. -.a) -> [(a. :: :: :: :: :: :: :: :: (Ix (Ix (Ix (Ix (Ix (Ix (Ix (Ix a) a) a) a) a) a) a) a) => => => => => => => => -..

ARRAYS Haskell provides indexable arrays. accumArray. ). the lower bound is greater than the upper bound. a programmer may reasonably expect rapid access to the components. Indexing an empty array always gives an array-bounds error. ). in any dimension. ).     16.e.1 Array Construction If a is an index type and b is any type. arrays are treated as data. the type of arrays with indices in a and elements in b is written Array a b. relaxes the restriction that a given index may appear at most once in the association list.100) ((1. To ensure the possibility of such an implementation.e. in index order. array is strict in the bounds argument and in the indices of the association list. or associations. For example. The array is undefined (i. and a one-origin 10 by 10 matrix has bounds ((1. The (!) operator denotes array subscripting.e. The first argument of array is a pair of bounds. If any two associations in the list have the same index. .174 CHAPTER 16. then the array is legal. The bounds function applied to an array returns its bounds. elements. An array may be constructed from a pair of bounds and a list of values in index order using the function listArray. ) if any index in the list is out of bounds. this The second argument of array is a list of associations of the form ( list will be expressed as a comprehension. a one-origin vector of length 10 has bounds (1.1).(10. not as general functions. Because the indices must be checked for these errors. Since most array functions involve the class Ix. An array may be created by the function array.1 shows some examples that use the array constructor. If. in particular.1. and assocs. return lists of the indices. each of the index type of the array. i * a!(i-1)) | i <.10).1 Accumulated Arrays Another array creation function.[2.100]]) Not every index within the bounds of the array need appear in the association list. Thus. in that order. x) defines the value of the array at index i to be x. elems. respectively.1) : [(i. but bounds still yields the bounds with which the array was constructed. using an accumulating function which combines the values of associations with the same index. An association (i. but the values associated with indices that do not appear will be undefined (i.. the value at that index is undefined (i. Functions restricted in this way can be implemented efficiently.10)). These bounds are the lowest and highest indices in the array. 16. Typically. Figure 16. The functions indices. but nonstrict in the values. but empty. The first argument of accumArray is the accumulating £ £ ¤¢  £ ¡  £ £ ¥     . which may be thought of as functions whose domains are isomorphic to contiguous subsets of the integers. recurrences such as the following are possible: a = array (1. when applied to an array. this module is exported from Array so that modules need not import both Array and Ix.

inRange bnds i] If the accumulating function is strict. a!i * x) | i <. i) | i <.i). 0) | i <.2. given a list of values of some index type. (As with the array function. Num b) => (a. the indices in the association list must be unique for the updated elements to be defined.Inverting an array that holds a permutation of its indices invPerm :: (Ix a) => Array a a -> Array a a invPerm a = array b [(a!i. unlike ordinary arrays.16. 1) | i<-is.a) -> [a] -> Array a b hist bnds is = accumArray (+) 0 bnds [(i. INCREMENTAL ARRAY UPDATES -.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. Thus.The inner product of two vectors inner :: (Ix a.[1. For example.. if m is a 1-origin. as well as the indices.) For example. z) | i <.range b]) 0 0 . hist produces a histogram of the number of occurrences of each index within a specified range: hist :: (Ix a. accumulated arrays should not in general be recursive.range b] where b = bounds a -.range b] = bounds a 175 -. Ix scale x a = array b where b of numbers by a given number: b) => a -> Array b a -> Array b a [(i. as for the array function. accum takes an array and an association list and accumulates pairs from the list into the array with the accumulating function . the second is an initial value. Thus accumArray can be defined using accum: accumArray f z b = accum f (array b [(i. in the association list. n by n matrix. 16. except with the diagonal zeroed. then accumArray is strict in the values. Num b) => Array a b -> Array a b -> b inner v w = if b == bounds w then sum [v!i * w!i | i <.1: Array examples function.range b] else error "inconformable arrays for inner product" where b = bounds v Figure 16. then m//[((i.n]] is the same matrix. the remaining two arguments are a bounds pair and an association list.Scaling an array scale :: (Num a.

ixmap ) where import Ix import List( (\\) ) infixl 9 !.a) (a -> b) deriving () . // data (Ix a) => Array a b = MkArray (a. bounds. elems. assocs. with the mapping that the original array embodies.3 Derived Arrays The two functions fmap and ixmap derive new arrays from existing ones. accum. accumArray. The fmap function transforms the array values while ixmap allows for transformations on array indices._).A row of a matrix row :: (Ix a.i)) x where ((l.Diagonal of a matrix (assumed to be square) diag :: (Ix a) => Array (a.c) -> Array a b firstArray = fmap (\(x.176 CHAPTER 16.j)) x where ((_.y)->x) Figure 16.b) c -> Array b c row i x = ixmap (l’. 16.u) (\i->(i.u’)) = bounds x -. array.a) b -> Array a b diag x = ixmap (l. (//). Figure 16. they may be thought of as providing function composition on the left and right. ARRAYS -.(_. listArray. respectively.4 Library Array module Array ( module Ix.Projection of first components of an array of pairs firstArray :: (Ix a) => Array a (b. (!).(u._)) = bounds x -. indices.2: Derived array examples 16.2 shows some examples.export all of Ix Array.l’). Ix b) => a -> Array (a.a) -> Array a b -> Array a b subArray bnds = ixmap bnds (\i->i) -.A rectangular subarray subArray :: (Ix a) => (a.u’) (\j->(i. -.

a!i) | i <.b)] -> Array a b array b ivs = if and [inRange b i | (i.f (a!i) v)]) :: (Ix a) => (b -> c -> b) -> b -> (a.a) -> (a -> b) -> Array b c -> Array a c = array b [(i.!: \ \multiply defined array element") else error "Array.a) -> [b] -> Array a b = array b (zipWith (\ a b -> (a.z) | i <. LIBRARY ARRAY 177 array :: (Ix a) => (a.v) -> a // [(i. Eq b) => Eq (Array a b) a == a’ = assocs a == assocs a’ where . f) instance (Ix a.a) = b :: (Ix a) => Array a b -> [a] = range .range b]) :: (Ix a.b)] -> Array a b = array (bounds a) (old_ivs ++ new_ivs) where old_ivs = [(i. Ix b) => (a._) <.16. i ‘notElem‘ new_is] new_is = [i | (i.indices a.b)] = [(i. i == j] of [v] -> v [] -> error "Array._) <. bounds :: (Ix a) => Array a b -> [b] = [a!i | i <.v) <.indices a] :: (Ix a) => Array a b -> [(a.new_ivs] :: (Ix a) => (b -> c -> b) -> Array a b -> [(a.range b] accum accum f accumArray accumArray f z b ixmap ixmap b f a instance (Ix a) => Functor (Array a) where fmap fn (MkArray b f) = MkArray b (fn .c)] -> Array a b = accum f (array b [(i.b)) (range b) vs) :: (Ix a) => Array a b -> a -> b = f :: (Ix a) => Array a b -> (a.a) -> [(a.!: \ \undefined array element" _ -> error "Array.ivs. a!i) | i <.a) -> [(a.4.c)] -> Array a b = foldl (\a (i.array: out-of-range array association" listArray listArray b vs (!) (!) (MkArray _ f) bounds bounds (MkArray b _) indices indices elems elems a assocs assocs a (//) a // new_ivs :: (Ix a) => (a.ivs] then MkArray b (\j -> case [v | (i.indices a] :: (Ix a) => Array a b -> [(a. a ! f i) | i <.

Ord b) => Ord (Array a b) a <= a’ = assocs a <= assocs a’ where CHAPTER 16. u) | ("array". (b. ARRAYS instance (Ix a. showsPrec (arrPrec+1) (assocs a) ) instance (Ix a.lex r.readsPrec (arrPrec+1) t ]) -.178 instance (Ix a. Show a.Precedence of the ’array’ function is that of application itself arrPrec = 10 . Show b) => Show (Array a b) where showsPrec p a = showParen (p > arrPrec) ( showString "array " .t) <. showChar ’ ’ .u) <. Read b) => Read (Array a b) where readsPrec p = readParen (p > arrPrec) (\r -> [ (array b as. Read a. (as. showsPrec (arrPrec+1) (bounds a) .readsPrec (arrPrec+1) s.s) <.

179 .

reverse. null. drop. replicate. nubBy. all. take. unlines. takeWhile. zipWith6. zipWith4. sort. genericReplicate. intersect. product. 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] . mapAccumL. mapAccumR. (\\). scanl1.. last. transpose. sortBy. lookup. init. dropWhile. span. any. intersperse. genericDrop. unwords. zip6. groupBy.. insert. concatMap. -. zip5. zip. (!!). zip7.180 CHAPTER 17. partition. head. elemIndices. deleteBy. unfoldr. intersectBy. deleteFirstsBy. unzip7. filter.[]((:). delete. zipWith. genericLength. group. repeat. unzip5. foldl1. tails. iterate. unionBy. scanl. scanr1. break. words. foldr1.and what the Prelude exports -. zip3. LIST UTILITIES Chapter 17 List Utilities module List ( elemIndex. zipWith5. foldl. splitAt. minimum. foldr. cycle. unzip. genericTake. scanr. maximum.This is built-in syntax map. sum. []). and. union. isPrefixOf. maximumBy. (++). notElem. unzip6. tail. length. -. find. findIndices. isSuffixOf. minimumBy. unzip4. inits. lines. concat. zipWith7. zipWith3. nub. zip4. genericIndex. elem.. findIndex. or. genericSplitAt. insertBy.

e.d.c.d.[a]) Eq a => [a] -> [[a]] (a -> a -> Bool) -> [a] -> [[a]] [a] -> [[a]] [a] -> [[a]] Eq a => [a] -> [a] -> Bool Eq a => [a] -> [a] -> Bool (a -> b -> (a.[f].e.f)] :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [(a.c.c.b.d.b)) -> b -> [a] Ord a => [a] -> [a] (a -> a -> Ordering) -> [a] -> [a] Ord a => a -> [a] -> [a] (a -> a -> Ordering) -> a -> [a] -> [a] (a -> a -> Ordering) -> [a] -> a (a -> a -> Ordering) -> [a] -> a Integral a => [b] -> a Integral a => a -> [b] -> [b] Integral a => a -> [b] -> [b] Integral a => a -> [b] -> ([b]. c)) -> a -> [b] -> (a.d)] -> ([a].d.c.b.b.[c].[d].[b]. c)) -> a -> [b] -> (a.b.[e]) :: [(a.b.[g]) This library defines some lesser-used operations over lists. [c]) (b -> Maybe (a.[c].[c].[e].e.d.f)] -> ([a]. .e.d.b.[e].e)] -> ([a].[c].c.[d].[b].g)] :: (a->b->c->d->e) -> [a]->[b]->[c]->[d]->[e] :: (a->b->c->d->e->f) -> [a]->[b]->[c]->[d]->[e]->[f] :: (a->b->c->d->e->f->g) -> [a]->[b]->[c]->[d]->[e]->[f]->[g] :: (a->b->c->d->e->f->g->h) -> [a]->[b]->[c]->[d]->[e]->[f]->[g]->[h] :: [(a.[d].c.b.b.181 intersect intersectBy intersperse transpose partition group groupBy inits tails isPrefixOf isSuffixOf mapAccumL mapAccumR unfoldr sort sortBy insert insertBy maximumBy minimumBy genericLength genericTake genericDrop genericSplitAt genericIndex genericReplicate zip4 zip5 zip6 zip7 zipWith4 zipWith5 zipWith6 zipWith7 unzip4 unzip5 unzip6 unzip7 :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: Eq a => [a] -> [a] -> [a] (a -> a -> Bool) -> [a] -> [a] -> [a] a -> [a] -> [a] [[a]] -> [[a]] (a -> Bool) -> [a] -> ([a].f.d)] :: [a] -> [b] -> [c] -> [d] -> [e] -> [(a.[f]) :: [(a.c.[b].[b]) Integral a => [b] -> a -> b Integral a => a -> b -> [b] :: [a] -> [b] -> [c] -> [d] -> [(a.[d]) :: [(a.f.[b]. [c]) (a -> b -> (a.e)] :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [(a.g)] -> ([a].c.

if there is no such element.g. if any. provided that their first argument contains no duplicates.1.4. giving the occurrences of val in list. LIST UTILITIES 17. nub (meaning “essence”) removes duplicates elements from a list. findIndex returns the corresponding index. For example: nub [1.3. Nothing is returned if not (val ‘elem‘ list). union and intersect (and their By variants) preserve the invariant that their result does not contain duplicates.1 Indexing lists elemIndex val list returns the index of the first occurrence. (xs ++ ys) \\ xs == ys. findIndices returns a list of all such indices.g. of val in list as Just index. e.4.g.4] . "dog" ‘union‘ "cow" == "dogcw" intersect is list intersection. find returns the first element of a list that satisfies a predicate. In the result of xs \\ ys.182 CHAPTER 17. or Nothing.4] ‘intersect‘ [2.3. union is list union..6. Thus. delete. nub removes duplicate elements from a list.3. delete ’a’ "banana" == "bnana" (\\) is list difference (non-associative).8] == [2. e..2 “Set” operations There are a number of “set” operations defined over the List type. e. the first occurrence of each element of ys in turn (if any) has been removed from xs. 17.3.4] delete x removes the first occurrence of x from its list argument. [1.3] = [1.2.                 elemIndices val list returns an in-order list of indices. (\\)..

adjacent elements.3.3].c. "bc". i.17.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."i".[2."a".. p) xs) sort implement a stable sorting algorithm.2. longest first.5].’ "abcde" == "a.[3."ss". "c".""] mapAccumL f s l applies f to an accumulating “state” parameter s and to each element of l in turn.g."pp".[4.e" transpose transposes the rows and columns of its argument.                     intersperse ’. here specified in terms of the insertBy function. shortest first.b.4]."abc"] tails returns the list of all final segments of its argument list. mapAccumR is similar to mapAccumL except that the list is processed from right-to-left rather than left-to-right."i".5. For example group "Mississippi" == ["M". unfoldr builds a list from a seed value. 17.6]] == [[1.e. transpose [[1.4 unfoldr The unfoldr function is a “dual” to foldr: while foldr reduces a list to a summary value. which inserts objects into a list according to the specified ordering relation. LIST TRANSFORMATIONS 183 17. group splits its list argument into a list of lists of equal...3 List transformations intersperse sep inserts sep between the elements of its list argument."ss". inits "abc" == [""."i". respectively. e.g. tails "abc" == ["abc". For example: . insert inserts a new element into an ordered list (arranged in increasing order)."i"] inits returns the list of initial segments of its argument list."ab".d. partition p xs == (filter p xs. filter (not . e.

because any (eq x) does the same job as elemBy eq x would. insertBy. The “By” variants are as follows: nubBy. LIST UTILITIES iterate f == unfoldr (\x -> Just (x. isPrefixOf. groupBy. intersectBy. unfoldr can undo a foldr operation: unfoldr f’ (foldr f z xs) == xs if the following holds: f’ (f x y) = Just (x. 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. maximumBy.184 CHAPTER 17. When the “By” function replaces an Eq context by a binary predicate. unionBy. . when the “By” function replaces an Ord context by a binary predicate. isSuffixOf) were not considered important enough to have “By” variants. the equality method may not be appropriate in all situations.y) f’ z = Nothing 17. the predicate is assumed to define a total ordering. For example. sortBy. deleteBy.6 The “By” operations By convention.5 Predicates isPrefixOf and isSuffixOf check whether the first argument is a prefix (resp. The library does not provide elemBy. 17. A handful of overloaded functions (elemIndex. deleteFirstsBy (the By variant of \\). the predicate is assumed to define an equivalence. f x)) In some cases. elemIndices. suffix) of the second argument. the function nub could be defined as follows: nub nub [] nub (x:xs) :: (Eq a) => [a] -> [a] = [] = x : nub (filter (\y -> not (x == y)) xs) However. overloaded functions have a non-overloaded counterpart whose name is suffixed with “By”. minimumBy.

unzip. genericSplitAt. zipWith. genericIndex (the generic version of !!).8 Further “zip” operations The Prelude provides zip. and 7 arguments. The “generic” operations are as follows: genericLength. 6. :: Integral a => [b] -> a 17. and zipWith3.17. THE “GENERIC” OPERATIONS 185 17. . For example. unzip3. genericReplicate. genericTake. genericDrop. The List library provides these same three operations for 4. zip3.7. 5.7 The “generic” operations The prefix “generic” indicates an overloaded function that is a generalised version of a Prelude function. genericLength is a generalised version of length.

nub. replicate.. sum. 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 . lines. group. zipWith6. repeat. scanl. all. inits. filter. minimumBy.. sortBy. elemIndices. isPrefixOf. genericLength. (!!). foldr. tail. -. lookup. concat. and. isSuffixOf. deleteFirstsBy. -. cycle. zipWith4. product. p x ] :: Eq a => [a] -> [a] = nubBy (==) . null. head. findIndices p :: (a -> Bool) -> [a] -> [Int] = [ i | (x. (\\). unlines. zip4.186 CHAPTER 17. unfoldr. unzip7. scanl1. notElem. elem. sort. break. zip5. last. zip6. genericTake. tails. words.This is built-in syntax map. intersectBy. filter p :: (a -> Bool) -> [a] -> Maybe Int = listToMaybe . zip3. concatMap.[]((:). foldr1. zip. length. foldl1. partition. zipWith. intersperse. find. unzip6. iterate. insertBy. union..zip xs [0. (++). groupBy. unionBy. findIndex. zipWith5.and what the Prelude exports -. or.]. init. mapAccumL. drop. maximumBy. any. LIST UTILITIES 17. takeWhile. dropWhile. zipWith3. zipWith7.9 Library List module List ( elemIndex. foldl. scanr1. mapAccumR. unzip. unwords.. minimum. scanr. splitAt. unzip5. genericIndex. findIndices. genericSplitAt. unzip4. span. insert. delete. zip7. transpose. genericDrop. take. reverse. nubBy. deleteBy. intersect. []). maximum. genericReplicate.i) <.

5].[a]) = (filter p xs.2]."i"] group :: Eq a => [a] -> [[a]] group = groupBy (==) .transpose is lazy in both rows and columns."ss"."i".g.9.[3..[5]] -.4].17."i"."i".xss]) partition partition p xs :: (a -> Bool) -> [a] -> ([a]. filter (not .For example. transpose [[1. any (eq x) ys] :: = = = a -> [a] -> [a] [] [x] x : sep : intersperse sep xs -.group "Mississippi" == ["M".Note that [h | (h:t) <.xss]) : transpose (xs : [t | (h:t) <."ss".elements.4.[]] = [[1. 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 <. -and works for non-rectangular ’matrices’ -."pp".xs.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) <. e.[2. p) xs) -.group splits its list argument into a list of lists of equal. -.3]. adjacent -.

inits "abc" == inits inits [] inits (x:xs) -.tails xs returns the -."a". [c]) = (s.e. y:ys) where (s’’.zs) = span (eq x) xs list of initial segments of xs. shortest first..g. [""..g. ["abc". LIST UTILITIES :: (a -> a -> Bool) -> [a] -> [[a]] = [] = (x:ys) : groupBy eq zs where (ys.e.b)) -> b -> [a] = case f b of Nothing -> [] Just (a.""] :: [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.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 . c)) -> a -> [b] -> (a. []) = (s’’.inits xs returns the -.188 groupBy groupBy eq [] groupBy eq (x:xs) -. [c]) = (s. tails "abc" == tails tails [] tails xxs@(_:xs) CHAPTER 17."ab".y:ys) where (s’. c)) -> a -> [b] -> (a.y ) = f s’ x (s’. "bc"."abc"] :: [a] -> [[a]] = [[]] = [[]] ++ map (x:) (inits xs) list of all final segments of xs. y ) = f s x (s’’. longest first. []) = (s’’. "c". ys) = mapAccumR f s xs :: (b -> Maybe (a.ys) = mapAccumL f s’ xs :: (a -> b -> (a.

genericTake: negative argument" minimumBy minimumBy cmp [] minimumBy cmp xs genericLength genericLength [] genericLength (x:xs) genericTake genericTake _ [] genericTake 0 _ genericTake n (x:xs) | n > 0 | otherwise genericDrop genericDrop 0 xs genericDrop _ [] genericDrop n (_:xs) | n > 0 | otherwise genericSplitAt genericSplitAt 0 xs genericSplitAt _ [] genericSplitAt n (x:xs) | n > 0 | otherwise where (xs’.genericDrop: negative argument" :: (Integral a) => a -> [b] -> ([b].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 (n-1) xs error "List.[]) = = = (x:xs’. LIBRARY LIST insertBy :: (a -> a -> insertBy cmp x [] = [x] insertBy cmp x ys@(y:ys’) = case cmp x GT -> _ -> maximumBy maximumBy cmp [] maximumBy cmp xs Ordering) -> a -> [a] -> [a] 189 y of y : insertBy cmp x ys’ x : ys :: (a -> a -> Ordering) -> [a] -> a = error "List.[b]) = ([].maximumBy: empty list" = foldl1 max xs where max x y = case cmp x y of GT -> x _ -> y :: (a -> a -> Ordering) -> [a] -> a = error "List.xs) = ([].17.genericSplitAt: negative argument" genericSplitAt (n-1) xs .xs’’) :: (Integral a) => a -> [b] -> [b] = xs = [] = = genericDrop (n-1) xs error "List.xs’’) error "List.9.

.b..b.190 genericIndex genericIndex (x:_) 0 genericIndex (_:xs) n | n > 0 | otherwise genericIndex _ _ genericReplicate genericReplicate n x zip4 zip4 zip5 zip5 zip6 zip6 zip7 zip7 CHAPTER 17.d.e)] = zipWith5 (.c.[c].bs.b:bs.c.genericIndex: negative argument" error "List.d)] -> ([a].c:cs.c.d)] = zipWith4 (.) 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.[]..[b].ds) -> (a:as..c.genericIndex: index too large" :: (Integral a) => a -> b -> [b] = genericTake n (repeat x) :: [a] -> [b] -> [c] -> [d] -> [(a.c.cs.[]..c.b..b.e.f.e.d) ˜(as...g)] = zipWith7 (.) :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [(a....d.b.f)] = zipWith6 (..) :: [a] -> [b] -> [c] -> [d] -> [e] -> [(a.b...d.d:ds)) ([].) :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [(a. LIST UTILITIES :: (Integral a) => [b] -> a -> b = x = = = genericIndex xs (n-1) error "List.[]) zipWith7 zipWith6 .[d]) = foldr (\(a.

LIBRARY LIST unzip5 unzip5 :: [(a.ds.c:cs.bs.b.b.es) -> (a:as.[]) unzip7 unzip7 .fs.[].g) ˜(as.c.[d].gs) -> (a:as.[].cs.b.[c].b:bs.cs.[]) :: [(a.d.d:ds.b:bs.c.d.[g]) = foldr (\(a.b:bs.e.e.bs.[c].g:gs)) ([].17.ds.e:es.c.d:ds.f)] -> ([a].[].c.[]) 191 unzip6 unzip6 :: [(a.d.[].e) ˜(as.g)] -> ([a].[].[b].f:fs.f) ˜(as.e:es)) ([].[e].[b].[c].d.f.[e]) = foldr (\(a.e:es.[b].[d].d.[f].e)] -> ([a].[].c:cs.ds.d.cs.9.e.c.[].bs.[].[d].f:fs)) ([].[e].[].e.es.b.fs) -> (a:as.f.[f]) = foldr (\(a.b.d:ds.c.[].[].[].es.b.c:cs.

LIST UTILITIES .192 CHAPTER 17.

A correct result is encapsulated by wrapping it in Just. Just). listToMaybe.. catMaybes. Other operations on Maybe are provided as part of the monadic classes in the Prelude. fromMaybe.and what the Prelude exports Maybe(Nothing. fromJust. maybe ) where isJust. 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 defined 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... an incorrect result is returned as Nothing. isNothing. maybeToList. and without using IOError from the IO monad. -.Chapter 18 Maybe Utilities module Maybe( isJust. which would cause the expression to become monadic. mapMaybe. as would happen if error were used. 193 .

. map f . mapMaybe. isNothing. Just).ms ] :: (a -> Maybe b) -> [a] -> [b] = catMaybes . MAYBE UTILITIES 18. fromMaybe.and what the Prelude exports Maybe(Nothing. -.fromJust: Nothing" :: a -> Maybe a -> a = d = a :: Maybe a -> [a] = [] = [a] :: [a] -> Maybe a = Nothing = Just a :: [Maybe a] -> [a] = [ m | Just m <.. catMaybes. listToMaybe.. maybeToList.194 CHAPTER 18. isJust :: Maybe a -> a = a = error "Maybe. fromJust. 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 .1 Library Maybe module Maybe( isJust.

intToDigit.Chapter 19 Character Utilities module Char ( isAscii. isPrint. isUpper. toLower. For the purposes of Haskell. isOctDigit. isHexDigit. lexLitChar. toUpper. isLower. digitToInt... 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. isHexDigit. showLitChar. and other printable characters. isAlpha. String ) where isAscii. other alphabetic.. isAlphaNum. isPrint.and what the Prelude exports Char. isDigit. isSpace. isLatin1. readLitChar. isSpace. numeric digits. isOctDigit. with the next 128 entries comes the remainder of the Latin-1 character set. isLower. -. the full set of Unicode character attributes is not accessible in this library. isLatin1. This module offers only a limited view of the full Unicode character set. lower case alphabetic. isDigit. ord. isAlphaNum :: Char -> Bool toUpper. chr. any 195 . isUpper. isControl. The first 128 entries of this character set are identical to the ASCII set. Unicode characters may be divided into five general categories: non-printing. isAlpha. isControl.

but recognises both upper and lower-case hexadecimal digits (i. For each sort of Unicode character. "Hello")] [(’\n’. Any Unicode letter which has an upper-case equivalent is transformed.15. ’a’.’F’). and isHexDigit functions select only ASCII characters.196 CHAPTER 19. and title). "Hello")] Function toUpper converts a letter to the corresponding upper-case letter. For example: showLitChar ’\n’ s lexLitChar "\\nHello" readLitChar "\\nHello" = = = "\\n" ++ s [("\\n". and generates lower-case hexadecimal digits. The function showLitChar converts a character to a string using only printable characters. using Haskell source-language escape conventions. .. The ord and chr functions are fromEnum and toEnum restricted to the type Char.’9’. ’0’. leaving any other character unchanged. lower. but in addition converts the to the character that it encodes.. intToDigit and digitToInt convert between a single digit Char and the corresponding Int. intToDigit fails unless its argument is in the range 0. here are the predicates which return True: Character Type Lower Case Alphabetic Other Alphabetic Digits Other Printable Non-printing Predicates isPrint isPrint isPrint isPrint isAlphaNum isAlphaNum isAlphaNum isAlpha isAlpha isLower isUpper The isDigit. CHARACTER UTILITIES alphabetic character which is not lower case is treated as upper case (Unicode actually has three cases: upper. digitToInt operates fails unless its argument satisfies isHexDigit.e. Similarly. The function lexLitChar does the reverse.’f’. Numeric digits may be part of identifiers but digits outside the ASCII range are not used by the reader to represent numbers.. leaving any other character unchanged. The function readLitChar does the same. isOctDigit. returning the sequence of characters that encode the character. The isSpace function recognizes only white characters in the Latin-1 range.. toLower converts a letter to the corresponding lower-case letter. ’A’.

toUpper.Only Latin-1 spaces recognized isUpper isLower isAlpha c isDigit c isOctDigit c isHexDigit c isAlphaNum = = = = = = = primUnicodeIsUpper primUnicodeIsLower -.Digit conversion operations digitToInt :: Char -> Int digitToInt c | isDigit c = fromEnum c .fromEnum ’0’ | c >= ’a’ && c <= ’f’ = fromEnum c . 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" -.. isDigit. isSpace...’Z’ -..’A’. chr.Used for character name table. isDigit.fromEnum ’a’ + 10 | c >= ’A’ && c <= ’F’ = fromEnum c . intToDigit. readHex) import UnicodePrims -. isLatin1. readOct. isControl. lexLitChar. isUpper. isSpace. isOctDigit.’a’. isControl. isLower. isPrint. readLitChar.and what the Prelude exports Char. isAlpha. ord.. isOctDigit. isLower. import Numeric (readDec. -.19. isHexDigit.fromEnum ’A’ + 10 | otherwise = error "Char. lexDigits.1 Library Char module Char ( isAscii.’z’ isUpper c || isLower c c >= ’0’ && c <= ’9’ c >= ’0’ && c <= ’7’ isDigit c || c >= ’A’ && c <= ’F’ || c >= ’a’ && c <= ’f’ primUnicodeIsAlphaNum -. isHexDigit. isAlphaNum.1.digitToInt: not a digit" . showLitChar. isAlpha. isPrint. -. String ) where import Array -. isUpper. toLower. isLatin1.Source of primitive Unicode functions. LIBRARY CHAR 197 19.Character-testing operations isAscii. digitToInt.

t) <.readDec s] (’o’:s) = [(chr n.ord ’@’).[a]) = match xs ys = (xs.Text functions readLitChar :: ReadS Char readLitChar (’\\’:s) = readEsc s readLitChar (c:s) = [(c.readHex s] s@(c:_) | isUpper c = let table = (’\DEL’.table.intToDigit: not a digit" -.s)] (’ˆ’:c:s) | c >= ’@’ && c <= ’_’ = [(chr (ord c .t) <.198 intToDigit :: Int -> Char intToDigit i | i >= 0 && i <= 9 = | i >= 10 && i <= 15 = | otherwise = CHAPTER 19.s)] (’n’:s) = [(’\n’.s)] (’r’:s) = [(’\r’. "DEL") : assocs asciiTab in case [(c. s)] s@(d:_) | isDigit d = [(chr n.s)] (’\’’:s) = [(’\’’.Case-changing operations toUpper :: Char -> Char toUpper = primUnicodeToUpper toLower :: Char -> Char toLower = primUnicodeToLower -. t) | (n.s)] (’b’:s) = [(’\b’.10) error "Char.s)] readEsc readEsc readEsc readEsc readEsc readEsc readEsc readEsc readEsc readEsc readEsc readEsc readEsc readEsc readEsc readEsc :: ReadS Char (’a’:s) = [(’\a’.ys) readEsc match match (x:xs) (y:ys) | x == y match xs ys . CHARACTER UTILITIES toEnum (fromEnum ’0’ + i) toEnum (fromEnum ’a’ + i .s)] (’t’:s) = [(’\t’. t) | (n. mne) <.s)] (’\\’:s) = [(’\\’.s)] (’f’:s) = [(’\f’.s’) <.readOct s] (’x’:s) = [(chr n. ([].s)] (’"’:s) = [(’"’.t) <. t) | (n.s)] (’v’:s) = [(’\v’.s’) | (c.Character code functions ord :: Char -> Int ord = fromEnum chr chr :: Int -> Char = toEnum -.[match mne s]] of (pr:_) -> [pr] [] -> [] _ = [] :: (Eq a) => [a] -> [a] -> ([a].

199 lexLitChar :: ReadS String lexLitChar (’\\’:s) = map (prefix ’\\’) (lexEsc s) where lexEsc (c:s) | c ‘elem‘ "abfnrtv\\\"’" = [([c]. 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 . "ETB".19. "LF". "ACK".c]. "EM". "RS". s) lexLitChar (c:s) lexLitChar "" = = [([c]. "ENQ". "SUB". "SOH". "ETX". "ESC". "DC2".s)] -. "DC1". lexEsc s@(c:_) | isUpper c = [span isCharName s] lexEsc _ = [] isCharName c = isUpper c || isDigit c prefix c (t.s)] [] . "DC3". "NAK". "DLE". "SP"] s@(c:_) | p c = "\\&" ++ s s = s "EOT". "US". "CR".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] -. "SO".1. "SI".Very crude approximation to \XYZ. "BS". "GS". "FS". "CAN". "DC4".s) = (c:t. "BEL". "SYN". LIBRARY CHAR showLitChar :: Char -> ShowS showLitChar c | c > ’\DEL’ = showChar ’\\’ . cont where cont cont asciiTab = listArray (’\NUL’. "FF".s)] lexEsc (’ˆ’:c:s) | c >= ’@’ && c <= ’_’ = [([’ˆ’. ’ ’) ["NUL". "VT". "HT". "STX".

CHARACTER UTILITIES .200 CHAPTER 19.

201 .

ap. Functor(fmap). liftM3. return. -> 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) . liftM4. liftM. when. (=<<). mapM_. foldM.and what the Prelude exports Monad((>>=). mapAndUnzipM. zipWithM_. mplus). unless. sequence_.202 CHAPTER 20.. sequence. msum. mapM. liftM5. (>>).. ) 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.c)) -> [a] -> m ([b]. -. guard. MONAD UTILITIES Chapter 20 Monad Utilities module Monad ( MonadPlus(mzero. fail). zipWithM.. liftM2. filterM. join.

So. 20. Thus (in the Prelude): sequence :: Monad m => [m a] -> m [a] sequence_ :: Monad m => [m a] -> m () A prefix “m” generalises an existing function to a monadic form. Thus.20. Lists and the Maybe type are instances of MonadPlus.1 Naming conventions The functions in this library use the following naming conventions: A postfix “M” always stands for a function in the Kleisli category: m is added to function results (modulo currying) and nowhere else. for example: sum :: Num a => [a] -> a msum :: MonadPlus m => [m a] -> m a 20.2 Class MonadPlus The MonadPlus class is defined as follows: class Monad m => MonadPlus m where mzero :: m a mplus :: m a -> m a -> m a The class methods mzero and mplus are the zero and plus of the monad.1.       filter :: (a -> Bool) -> [a] -> [a] filterM :: Monad m => (a -> m Bool) -> [a] -> m [a] A postfix “_” changes the result type from (m a) to (m ()). NAMING CONVENTIONS 203 The Monad library defines the MonadPlus class. thus: instance MonadPlus Maybe where mzero = Nothing Nothing ‘mplus‘ ys = ys xs ‘mplus‘ ys = xs instance MonadPlus [] mzero = [] mplus = (++) where . and provides some useful operations on monads. for example.

It is used to remove one level of monadic structure. when debug (putStr "Debugging\n") will output the string "Debugging\n" if the Boolean value debug is True.readFile nm zipWithM_ (\i line -> do putStr (show i).1] [0.. The monadic lifting operators promote a function to a monad.] (lines cts) The foldM function is analogous to foldl. For example..204 CHAPTER 20. .. The zipWithM function generalises zipWith to arbitrary monads. For instance the following function displays a file. and otherwise do nothing. returning the result as a pair of lists. This function is mainly used with complicated data structures or a state-transforming monad. x2. projecting its bound argument into the outer level.1. the liftM operations can be replaced by uses of ap. The when and unless functions provide conditional execution of monadic expressions.f a2 x2 .3] liftM2 (+) (Just 1) Nothing = Nothing In many situations. For example. MONAD UTILITIES 20. Note that foldM works from left-to-right over the list arguments. . putStr ": ".2. foldM f a1 [x1. f am xm If right-to-left evaluation is required. the input list should be reversed.f a1 x1 a3 <.. which promotes function application. The mapAndUnzipM function maps its first argument over a list. listFile :: String -> IO () listFile nm = do cts <.2] = [0. liftM2 (+) [0. prefixing each line with its line number. The function arguments are scanned left to right. except that its result is encapsulated in a monad.3 Functions The join function is the conventional monad join operator. xm ] == do a2 <. putStrLn line) [1.. This could be an issue where (>>) and the “folded function” are not commutative..

. ‘ap‘ xn is equivalent to liftMn f x1 x2 ..20.. xn 205 . FUNCTIONS return f ‘ap‘ x1 ‘ap‘ ..3.

zipWithM_. liftM5. (>>). msum. liftM3..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. mapM. guard. liftM4.4 Library Monad module Monad ( MonadPlus(mzero. [c]) mapAndUnzipM f xs = sequence (map f xs) >>= return . (=<<). unless. ap. join. mapM_. return.The MonadPlus class definition class (Monad m) => MonadPlus m mzero :: m a mplus :: m a -> m a -> m a -..and what the Prelude exports Monad((>>=).Instances of MonadPlus instance MonadPlus Maybe where mzero = Nothing Nothing ‘mplus‘ ys xs ‘mplus‘ ys instance MonadPlus [] mzero = [] mplus = (++) -. zipWithM. MONAD UTILITIES 20. fail). mplus). ) where -.c)) -> [a] -> m ([b].206 CHAPTER 20.. mapAndUnzipM. Functor(fmap). sequence. foldM. -. when. unzip . liftM2. sequence_. liftM.

e.b. b’ <. 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.c.a. return (f a’ b’ c’ d’ e’) } . b’ <.b.d.4. return (f a’ b’) } :: (Monad m) => (a -> b -> c -> d) -> (m a -> m b -> m c -> m d) = \a b c -> do { a’ <. return (if b then (x:ys) else ys) } liftM liftM f liftM2 liftM2 f liftM3 liftM3 f liftM4 liftM4 f liftM5 liftM5 f :: (Monad m) => (a -> b) -> (m a -> m b) = \a -> do { a’ <. return (f a’ b’ c’ d’) } :: (Monad m) => (a -> b -> c -> d -> e -> f) -> (m a -> m b -> m c -> m d -> m e -> m f) = \a b c d e -> do { a’ <. d’ <. b’ <. return (f a’ b’ c’) } :: (Monad m) => (a -> b -> c -> d -> e) -> (m a -> m b -> m c -> m d -> m e) = \a b c d -> do { a’ <.d. return (f a’) } :: (Monad m) => (a -> b -> c) -> (m a -> m b -> m c) = \a b -> do { a’ <. ys <.a.a. b’ <.c.b. e’ <.20. d’ <.a.a. c’ <.p x.c. c’ <.filterM p xs.

MONAD UTILITIES .208 CHAPTER 20.

209 .

getLine. hGetContents. isAlreadyInUseError. hGetPosn. hSetPosn. print. getChar. hPrint. bracket_. hReady.. Ix. stderr :: Handle openFile hClose :: FilePath -> IOMode -> IO Handle :: Handle -> IO () . putChar. hPutChar. instance Eq Handle where . Bounded.. IOError.ReadWriteMode).. isEOF. hIsClosed.WriteMode. hIsEOF. writeFile. instance Show HandlePosn where --data IOMode data BufferMode = = | = -.210 CHAPTER 21. Bounded. ioeGetFileName. ioeGetErrorString. ioError. isAlreadyExistsError. Ord. data HandlePosn = .. Show) NoBuffering | LineBuffering BlockBuffering (Maybe Int) deriving (Eq. try. openFile. Read. Show) stdin.AppendMode. isIllegalOperation. BufferMode(NoBuffering. isPermissionError. appendFile. isFullError. ioeGetHandle.LineBuffering. SeekMode(AbsoluteSeek.. stdin. hIsSeekable. getContents. putStr. -. hSeek.implementation-dependent data SeekMode ReadMode | WriteMode | AppendMode | ReadWriteMode deriving (Eq.. readLn ) where import Ix(Ix) data Handle = . hLookAhead. Enum. hFlush.implementation-dependent -. hIsWritable. hGetLine. readIO. putStrLn. stdout. hPutStrLn. Read. hFileSize.BlockBuffering). hIsOpen. IOMode(ReadMode. hPutStr. instance Eq HandlePosn where . userError. readFile. instance Show Handle where . Enum. hClose. bracket.. isDoesNotExistError. interact.and what the Prelude exports IO.. isUserError.implementation-dependent -. Ord.. HandlePosn. Ix. hSetBuffering.RelativeSeek. hWaitForInput. catch. stdout. hIsReadable. hGetBuffering. stderr. Read.SeekFromEnd). INPUT/OUTPUT Chapter 21 Input/Output module IO ( Handle. hGetChar.. FilePath. Show) AbsoluteSeek | RelativeSeek | SeekFromEnd deriving (Eq..implementation-dependent -.. Ord. isEOFError.

Some related operations on file systems . This library contain more advanced I/O features.211 hFileSize hIsEOF isEOF isEOF hSetBuffering hGetBuffering hFlush hGetPosn hSetPosn hSeek hWaitForInput hReady hReady h hGetChar hGetLine hLookAhead hGetContents hPutChar hPutStr hPutStrLn hPrint hIsOpen hIsClosed hIsReadable hIsWritable hIsSeekable isAlreadyExistsError isDoesNotExistError isAlreadyInUseError isFullError isEOFError isIllegalOperation isPermissionError isUserError ioeGetErrorString ioeGetHandle ioeGetFileName try bracket bracket_ :: :: :: = :: :: :: :: :: :: :: :: = :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: Handle -> IO Integer Handle -> IO Bool IO Bool hIsEOF stdin Handle -> BufferMode -> IO () Handle -> IO BufferMode Handle -> IO () Handle -> IO HandlePosn HandlePosn -> IO () Handle -> SeekMode -> Integer -> IO () Handle -> Int -> IO Bool Handle -> IO Bool hWaitForInput h 0 Handle -> IO Char Handle -> IO String Handle -> IO Char Handle -> IO String Handle -> Char -> IO () Handle -> String -> IO () Handle -> String -> IO () Show a => Handle -> a -> IO () Handle Handle Handle Handle Handle -> -> -> -> -> IO IO IO IO IO Bool Bool Bool Bool Bool IOError IOError IOError IOError IOError IOError IOError IOError -> -> -> -> -> -> -> -> Bool Bool Bool Bool Bool Bool Bool Bool :: IOError -> String :: IOError -> Maybe Handle :: IOError -> Maybe FilePath :: IO a -> IO (Either IOError a) :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c :: IO a -> (a -> IO b) -> IO c -> IO c The monadic I/O system used in Haskell is described by the Haskell language report. Commonly used I/O functions such as print are part of the standard prelude and need not be explicitly imported.

and ioeGetErrorString which returns a string. The try function returns an error in a computation explicitly using the Either type. In this case it should return isIllegalOperation. which is True if its argument is the corresponding kind of error. Additional errors which could be raised by an implementation are listed after the corresponding operation. compute. All these functions return a Bool. Three additional functions are provided to obtain information about an error value. the string is implementation-dependent. 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). an implementation will not be able to distinguish between the possible error causes. In some cases.212 are contained in the Directory library. isPermissionError – the operation failed because the user does not have sufficient operating system privilege to perform that operation. Any computation which returns an IO result may fail with isIllegalOperation. opening the same file twice for writing might give this error). CHAPTER 21. INPUT/OUTPUT 21. This is similar to trycatch-finally in Java. and False otherwise. isIllegalOperation – the operation is not possible. These are ioeGetHandle which returns Just if the error value refers to handle and Nothing otherwise.                 isDoesNotExistError – the operation failed because one of its arguments does not exist. 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 file has been reached. This is an abstract type. ioeGetFileName which returns Just if the error value refers to file .1 I/O Errors Errors of type IOError are used by the I/O monad. the string returned by ioeGetErrorString is the argument that was passed to fail. The bracket function captures a common allocate. which is already being used (for example. isFullError – the operation failed because the device is full. isAlreadyInUseError – the operation failed because one of its arguments is a singleuse resource. for all other errors.   4 ¦ ¢ 7 ¦ ¥   4 ¦ ¢ 7 ¦ ¥ . isUserError – a programmer-defined error value has been raised using fail. and Nothing otherwise.

In some implementations. Each value of this type is a handle: a record used by the Haskell run-time system to manage I/O with file system objects. likewise. ordered files.21. A handle is open when first allocated. A handle has at least the following properties: whether it manages input or output or both. The string produced by showing a handle is system dependent. FILES AND HANDLES 213 21. though an implementation cannot re-use its storage while references remain to it. The first two (stdin and stdout) manage input or output from the Haskell program’s standard input or output channel respectively. yielding a handle which can then be used to operate on the contents of that file. and normally reside on disk. it is writable if it manages only output or both input and output. Most handles will also have a current I/O position indicating where the next input or output operation will occur. a buffer (whose length may be zero). closed or semi-closed. A handle is readable if it manages only input or both input and output. For simplicity. . 21. The third (stderr) manages output to the standard error channel. represented by values of type Handle. although it could in fact be a communication channel. it should include enough information to identify the handle for debugging. These handles are initially open. any non-directory file system object is termed a file. or enabled on a line or block basis. which may be organised in directories (see Directory). Once it is closed it can no longer be used for either input or output. File and directory names are values of type String. no attempt is made to compare the internal state of different handles for equality.2 Files and Handles Haskell interfaces to the external world through an abstract file system.1 Standard Handles Three handles are allocated during program initialisation. Physical files are persistent. Haskell defines operations to read and write characters from and to files. Files can be opened. whose precise meaning is operating system dependent. This file system is a collection of named file system objects. or any other object recognised by the operating system. Handles are in the Show and Eq classes.           whether it is open. whether buffering is disabled. directories may themselves be file system objects and could be entries in other directories. A handle is equal according to == only to itself.2. whether the object is seekable.2.

214

CHAPTER 21. INPUT/OUTPUT

21.2.2 Semi-Closed Handles
The operation hGetContents (Section 21.9.4) puts a handle into an intermediate state, semi-closed. 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 semi-closed. The only exception is hClose. A semi-closed 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 semi-closed handle becomes closed, the contents of the associated list becomes fixed. The contents of this final list is only partially specified: 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 semi-closed are simply discarded.

21.2.3 File locking
Implementations should enforce as far as possible, at least locally to the Haskell process, multiplereader single-writer locking on files. That is, there may either be many handles on the same file which manage input, or just one handle on the file which manages output. If any open or semiclosed handle is managing a file for output, no new handle can be allocated for that file. If any open or semi-closed handle is managing a file for input, new handles can only be allocated if they do not manage output. Whether two files are the same is implementation-dependent, 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 semi-closed handle on the file until the entire contents of the file have been consumed. It follows that an attempt to write to a file (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 file . 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 file does not exist and it is opened for output, it should be created as a new file. If WriteMode and the file already exists, then it should be truncated to zero length. Some operating systems delete empty files, so there is no guarantee that the file will exist following an openFile with WriteMode unless it is subsequently written to successfully. The handle is positioned at the end of the file if is AppendMode, and otherwise at the beginning (in which case its internal I/O position is 0). The initial buffer mode is implementation-dependent. If openFile fails on a file opened for output, the file may still have been created if it did not already exist. Error reporting: the openFile computation may fail with isAlreadyInUseError if the file is already open and cannot be reopened; isDoesNotExistError if the file does not exist; or isPermissionError if the user does not have permission to open the file.

21.3.2 Closing Files
makes handle closed. Before the computation finishes, if is Computation hClose writable its buffer is flushed 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 8-bit bytes (
¥

which is attached to a physical file, hFileSize 0).

returns the size of that file

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 file this means that the current I/O position is equal from to the length of the file. 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: line-buffering, block-buffering or no-buffering. These modes have the following effects. For output, items are written out, or flushed, 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
line-buffering: the entire buffer is flushed whenever a newline is output, the buffer overflows, a hFlush is issued, or the handle is closed. block-buffering: the entire buffer is written out whenever it overflows, a hFlush is issued, or the handle is closed.
                   

no-buffering: output is written immediately, and never stored in the buffer.

An implementation is free to flush the buffer more frequently, but not less frequently, than specified above. The buffer is emptied as soon as it has been written out.
¥

Similarly, input occurs according to the buffer mode for handle

line-buffering: 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.
¥

block-buffering: when the buffer for the buffer.

becomes empty, the next block of data is read into

no-buffering: the next input item is read and returned. The hLookAhead operation (Section 21.9.3) implies that even a no-buffered handle may require a one-character buffer.

For most implementations, physical files will normally be block-buffered and terminals will normally be line-buffered.
¥

If is BlockBuffering , then block-buffering is enabled if possible. The size of the buffer is items if is Just and is otherwise implementation-dependent.
 

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 flushed as for hFlush; is not writable, the contents of the buffer is discarded.

¦

  § © 

  § © 

¦

 

 

¦

¦

2 4

If

is LineBuffering, line-buffering 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 implementation-dependent and may depend on the file 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 unspecified 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 8-bit bytes. If is block- or line-buffered, then seeking to a position which is not in the current buffer will first 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 file.

§

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 file, an I/O position beyond the current end-of-file. 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 specified property, and False otherwise.

21.9 Text Input and Output
Here we define a standard set of input operations for reading characters and strings from text files, 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 specified 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 file has been reached.

21.9.2 Reading Input
¥ ¥

Computation hGetChar

reads a character from the file or channel managed by

Error reporting: the hGetChar computation fails with isEOFError if the end of file has been reached. The hGetLine computation fails with isEOFError if the end of file is encountered when reading the first character of the line. If hGetLine encounters end-of-file 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 file or channel managed by getLine is a shorthand for hGetLine stdin.
¥

. The Prelude’s

7 ¦

7 ¦

7 ¦

¥

§

§

7 ¦

7¥ ¦

¥

7 ¦

7 ¦

7 ¦

7 ¦

¥

.

3 Reading Ahead ¥ Computation hLookAhead returns the next character from handle from the input buffer. ¥ Error reporting: the hLookAhead computation may fail with: isEOFError if the end of file has been reached. Char- 7 ¦ 7 ¦ ¥ .21. 21. hPutStr and hPrint computations may fail with: isFullError if the device is full. or isPermissionError if another system resource limit would be exceeded. ¥ © © ¥ Computation hPutStr ¥ writes the string to the file or channel managed by § . EXAMPLES 219 21. blocking until a character is available. 21.4 Reading The Entire Input 7 ¦ Computation hGetContents of the channel or file managed by ¥ returns the list of characters corresponding to the unread portion .10. 21. Error reporting: the hGetContents computation may fail with: isEOFError if the end of file has been reached.10 Examples Here are some simple examples to illustrate Haskell I/O. 7 ¦ 7 ¦ 7 ¦  7 ¦ ¥ 7 ¦ ¥ 7 ¦ 7 ¦ ¥ without removing it  7 ¦ § .5 Text Output ¥ writes the character to the file or channel managed by Computation hPutChar acters may be buffered if buffering is enabled for .1 Summing Two Numbers This program reads and sums two Integers.9.9. the file or channel managed by given by the shows function to Error reporting: the hPutChar.10. Computation hPrint writes the string representation of and appends a newline. which is made semi-closed.9. 21.

hIsEOF h1 if eof then return () else do c <.openFile f1 ReadMode h2 <.220 import IO CHAPTER 21.f2] <.Providing a type signature avoids reliance on -.the defaulting rule to fix the type of x1.openFile f2 WriteMode copyFile h1 h2 hClose h1 hClose h2 copyFile h1 h2 = do eof <. This program will not allow a file to be copied to itself.hGetChar h1 hPutChar h2 (toUpper c) copyFile h1 h2 An equivalent but much shorter version.readNum putStr "Enter another integer: " x2 <.readNum putStr ("Their sum is " ++ show (x1+x2) ++ "\n") where readNum :: IO Integer -.2 Copying Files A simple program to create a copy of a file. with all lower-case characters translated to upper-case. using string I/O is: . Note that exactly two arguments must be supplied to the program.x2 readNum = readLn 21. This version uses character-level I/O.10.getArgs h1 <. INPUT/OUTPUT main = do hSetBuffering stdout NoBuffering putStr "Enter an integer: " x1 <. import IO import System import Char( toUpper ) main = do [f1.

export list omitted -} where -.11.getArgs s <.f2] <.before rs <.readFile f1 writeFile f2 (map toUpper s) 221 21.actions that IO exports.before rs <.Just provide an implementation of the system-independent -.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 <.try m after x case rs of Right r -> return r Left e -> ioError e . Left) bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c bracket before after m = do x <.21. LIBRARY IO import System import Char( toUpper ) main = do [f1.f return (Right r)) (return . try try f :: IO a -> IO (Either IOError a) = catch (do r <.11 Library IO module IO {.try (m x) after x case rs of Right r -> return r Left e -> ioError e -.

INPUT/OUTPUT .222 CHAPTER 21.

223 .

-> -> -> -> -> 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 . writable. getDirectoryContents. getCurrentDirectory.. DIRECTORY FUNCTIONS Chapter 22 Directory Functions module Directory ( Permissions( Permissions. getPermissions. .. readable... .. doesDirectoryExist. removeDirectory.. getModificationTime ) where import Time ( ClockTime ) data Permissions = Permissions { readable. doesFileExist. setPermissions. searchable :: Bool } instance instance instance instance Eq Ord Read Show Permissions Permissions Permissions Permissions where where where where . renameFile.224 CHAPTER 22. setCurrentDirectory.. renameDirectory. writable. executable. executable. createDirectory.. removeFile. searchable ). .

There is normally at least one absolute path to each file system object. A conformant implementation need not support directory removal in all situations (for instance. it is atomically replaced by the object.” or “. it is removed as if by removeDirectory. Note that. The createDirectory computation may fail with: isPermissionError if the user is not permitted to create the directory. but all such entries are considered to form part of the directory contents. directory etc. ¦ ¦ 7 2 £   ¦ ¤§ ¦ ¤§ 7 ¦ 2 ¦ which is initially empty.” under POSIX). where is Computation removeFile not itself a directory. inaccessible. The implementation Computation removeDirectory may specify additional constraints which must be satisfied before a directory can be removed (for instance. A conformant implementation need not support renaming directories in all situations (for instance. Each file system object is referenced by a path. Some entries may be hidden. all other permissible errors are described below. Error reporting. If the object already exists. All such objects should therefore be treated as if they are files. Error reporting. or isDoesNotExistError if the file/directory does not exist.). removes the directory entry for an existing file . isAlreadyExistsError if the directory already exists. It is not legal for an implementation to partially remove a directory unless the entire directory is removed. Computation renameDirectory changes the name of an existing directory from to . the directory has to be empty. this library does not distinguish between physical files and other non-directory objects. removes an existing directory . in particular. In some operating systems.225 These functions operate on directories in the file system. Entries in sub-directories are not. 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. or have some administrative function (for instance. or isDoesNotExistError if the new directory’s parent does not exist. but the constraints must be documented. it is atomically replaced by the directory. The implementation may specify additional constraints which must be satisfied before a file can be removed (for instance. or may not be in use by other processes).1. Computation renameFile changes the name of an existing file system object from to . it may also be possible to have paths which are relative to the current directory. or as £   ¦   ¦ ¦ 7 7 7 2   2 £   £   ¦ ¦ £   £   ¦ ¦ £   ¦ . renaming to an existing directory. if an implementation does not support an operation it should raise an isIllegalOperation. A directory contains a series of entries. removal of the root directory). The removeDirectory and removeFile computations may fail with: isPermissionError if the user is not permitted to remove the file/directory. the file may not be in use by other processes). Although there may be file system objects other than files and directories. If the directory already exists.. Any Directory operation could raise an isIllegalOperation. each of which is a named reference to a file system object (file. however. “. If the directory is neither the directory nor an alias of the directory. or across different physical devices). as described in Section 21. considered to form part of the directory contents.

getPermissions f setPermissions f (p {readable = True}) The operation doesDirectoryExist returns True if the argument file exists and is a directory. Note that directories may be searchable without being readable. but not all permissions. and getModificationTime may fail with: isPermissionError if the user is not permitted to access the appropriate information. or if either argument to renameFile is a directory. and for files the searchable field will be False. Permissions apply both to files and directories. Error reporting. If the operating system has a notion of current directories. a construct on the following lines must be used. the executable field will be False. or isDoesNotExistError if the file/directory does not exist. get(set)Permissions. and False otherwise. if permission has been given to use them as part of a path. respectively. The getModificationTime operation returns the clock time at which the file/directory was last modified. Error reporting. and False otherwise.226 CHAPTER 22. The operation doesFileExist returns True if the argument file exists and is not a directory. renaming across different physical devices). getPermissions and setPermissions get and set these permissions. doesFile(Directory)Exist. For directories. setCurrentDirectory may fail with: isPermissionError if the user is not permitted to change directory to that specified. setCurrentDirectory the current directory of the calling process to . Note that to change some. ¦ ¤§ ¤§ ¤§ ¤§ ¦ ¦ Computation getDirectoryContents returned list is named relative to the directory returns a list of all entries in . but the constraints must be documented. Error reporting. ¦ ¦ . or isDoesNotExistError if the file/directory ¤§ If the operating system has a notion of current directories. The renameDirectory and renameFile computations may fail with: isPermissionError if the user is not permitted to rename the file/directory. getCurrentDirectory returns an absolute path to the current directory of the calling process. or isDoesNotExistError if the directory does not exist. The Permissions type is used to record whether certain operations are permissible on a file/directory. The getDirectoryContents and getCurrentDirectory computations may fail with: isPermissionError if the user is not permitted to access the directory. DIRECTORY FUNCTIONS may refer to an existing directory. Error reporting. Each entry in the changes . or isDoesNotExistError if the directory does not exist. makeReadable f = do p <. not as an absolute path. A conformant implementation need not support renaming files in all situations (for instance. but not to examine the directory contents.

227 does not exist. or isDoesNotExistError if the file/directory does not exist. . The setPermissions computation may also fail with: isPermissionError if the user is not permitted to change the permission for the specified file or directory.

DIRECTORY FUNCTIONS .228 CHAPTER 22.

Computation getEnv returns the value of the environment variable . the isDoesNotExistError exception is raised. if an implementation does not support an operation it must raise an isIllegalOperation. all other permissible errors are described below. The ExitCode type defines the exit codes that a program can return. some values of may be prohibited (for instance. Computation getProgName returns the name of the program as it was invoked. getArgs. Read. as described in Section 21. If variable is undefined. In particular. in particular. ExitSuccess indicates successful termination.Chapter 23 System Functions module System ( ExitCode(ExitSuccess. Computation getArgs returns a list of the program’s command line arguments (not including the program name). system. and ExitFailure indicates program failure with value . getEnv. Ord. 0 on a POSIX-compliant system). 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. The exact interpretation of is operating-system dependent. getProgName. Any System operation could raise an isIllegalOperation. 229    ¤ ¢   ¦ ¦  2 2 ¤ ¢    ¦  2   ¤ ¢ ¦  2  .1. Note that. exitFailure ) where data ExitCode = ExitSuccess | ExitFailure Int deriving (Eq. exitWith.ExitFailure).

and ExitFailure to mean that the program encountered a problem from which it ). exitWith bypasses the error handling in the I/O monad and cannot be intercepted by catch. it is treated identically to the computation ( >> exitWith ExitSuccess) ‘catch‘ \ _ -> exitFailure 7 ¢ § 0 § § S  ¢   ¦  2 ¦   2 4 Computation system the command . Otherwise. ¦  returns the exit code produced when the operating system processes 4  7 ¢ § 0 § § S  ¢ ¡   ¡ . If a program terminates as a result of calling error or because its value is otherwise determined to be . could not recover. Before the program terminates. any open or semi-closed handles are first closed. if any program terminates without calling exitWith explicitly. but the program should return ExitSuccess to mean normal completion. The value exitFailure is equal to exitWith (ExitFailure where is implementation-dependent.230 CHAPTER 23. returning to the program’s caller. The caller may interpret the return code as it wishes. then it is treated identically to the computation exitFailure. SYSTEM FUNCTIONS ¦ ¦  Computation exitWith terminates the program.

231 .

Implementation-dependent data Month = January | February | March | April | May | June | July | August | September | October | November | December deriving (Eq. tdSec :: Int. Int. instance Eq ClockTime where . addToClockTime. Read. Show) . calendarTimeToString. Read. Ix.May. toUTCTime. tdMin.Tuesday. ctTZ. ctPicosec.Friday.August.October.November. ctHour. Int. Show) data TimeDiff = TimeDiff { tdYear. CalendarTime(CalendarTime. toClockTime. Ord. Ord.232 CHAPTER 24. formatCalendarTime ) where import Ix(Ix) data ClockTime = ..Thursday. ctHour. ctMin. tdYear. Day(Sunday. Integer. diffClockTimes. Ord. tdHour. instance Ord ClockTime where .April.December). ctYDay. Ix. ctSec ctPicosec ctWDay ctYDay ctTZName ctTZ ctIsDST } deriving (Eq.February.Saturday). ctSec. Read. ctMin. DATES AND TIMES Chapter 24 Dates and Times module Time ( ClockTime. tdDay.. Bool data CalendarTime = CalendarTime { ctYear ctMonth ctDay. tdPicosec). Ord. tdMonth. Day. tdSec. Enum. -. ctTZName.June. toCalendarTime. Show) data Day = Sunday | Monday | Tuesday | Wednesday | Thursday | Friday | Saturday deriving (Eq. July. Enum. tdMonth. tdDay..Wednesday..September.. tdHour. Int. ctMonth. Month. ctYear. ctDay. ctIsDST). tdPicosec :: Integer } deriving (Eq. Bounded. Read.March.Monday.. ctWDay. tdMin. Bounded. String. TimeDiff(TimeDiff. Show) :: :: :: :: :: :: :: :: :: Int. Month(January. getClockTime.

including timezone information.233 -. The field is True if Daylight Savings Time would be in effect. modified by the timezone and daylight savings time settings in force at the time of conversion. The TimeDiff type records the difference between two clock times in a user-readable way. The returns difference may be either positive or negative. The expression diffClockTimes the difference between two clock times and as a TimeDiff. Function toCalendarTime converts to a local time. Because of this dependence on the local environment. Function getClockTime returns the current time in its internal representation. toCalendarTime is in the IO monad. 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 Pre-Gregorian dates are inaccurate The field is the name of the time zone. § §   © 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 non-Leap years Variation from UTC in seconds § § ¦   4 ¢ ¦ E   ¡  §  . Clock times may be compared directly or converted to a calendar time CalendarTime for I/O or other manipulations. used for the system’s internal clock time. and False otherwise.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. It follows RFC 1129 in its use of Coordinated Universal Time (UTC). CalendarTime is a user-readable and manipulable representation of the internal ClockTime type. The numeric fields have the following ranges. The expression addToClockTime adds a time difference and a clock time to yield a new clock time. ClockTime is an abstract type.

Enum.June. TimeDiff(TimeDiff. Ord. Enum.. ctMonth. Show) ¢ £    4 ¢ E   ¡  7 § §   ¢ € G § 7   ¢ € ( §  .September. Bounded. .). ctHour.234 § CHAPTER 24. ctMin. ctIsDST). calendarTimeToString. Month(January.. Ord. Show) data Day = Sunday | Monday | Tuesday | Wednesday | Thursday | Friday | Saturday deriving (Eq. tdSec. Day(Sunday. Ix. tdHour. toClockTime converts into the corresponding internal ClockTime ignoring the contents of the .Friday.March. tdPicosec). ctWDay. toClockTime. ctTZ. ctDay. toCalendarTime. instance Eq ClockTime where . instance Ord ClockTime where . ctPicosec. tdMonth.. getClockTime. Bounded. tdMin. ctYear. DATES AND TIMES Function toUTCTime converts into a CalendarTime in standard UTC format. -.August.December). ctTZName. tdYear. tdDay. ctSec.April. Ix. Function calendarTimeToString formats calendar times using local conventions and a formatting string. toUTCTime.Monday. CalendarTime(CalendarTime.November.Implementation-dependent data Month = January | February | March | April | May | June | July | August | September | October | November | December deriving (Eq.Thursday.   t € © S§ 24.May. diffClockTimes.Wednesday. ctYDay.1 Library Time module Time ( ClockTime. and fields. formatCalendarTime ) where import Ix(Ix) import Locale(TimeLocale(. .February. Read.. addToClockTime.Tuesday... July. Read..defaultTimeLocale) import Char ( intToDigit ) data ClockTime = .Saturday).October.

Day. Ord.1. Int. ctMin. String. -> ClockTime -> ClockTime -.. Read. Read. Int. tdPicosec :: Integer } deriving (Eq...Implementation-dependent :: CalendarTime -> String = formatCalendarTime defaultTimeLocale "%c" .. tdHour..Implementation-dependent -> IO CalendarTime -.. ctSec ctPicosec ctWDay ctYDay ctTZName ctTZ ctIsDST } deriving (Eq.Implementation-dependent -> CalendarTime -.. ctHour. Bool data TimeDiff = TimeDiff { tdYear. Ord. Show) 235 :: :: :: :: :: :: :: :: :: Int..24.. tdDay.Implementation-dependent :: CalendarTime -> ClockTime = .Implementation-dependent -> ClockTime -> TimeDiff -. :: ClockTime = . Int. tdSec :: Int. tdMin. -. :: ClockTime = . Integer. -. tdMonth. Month... LIBRARY TIME data CalendarTime = CalendarTime { ctYear ctMonth ctDay. :: ClockTime = .Implementation-dependent :: TimeDiff = . Show) getClockTime getClockTime addToClockTime addToClockTime td ct diffClockTimes diffClockTimes ct1 ct2 toCalendarTime toCalendarTime ct toUTCTime toUTCTime ct toClockTime toClockTime cal calendarTimeToString calendarTimeToString :: IO ClockTime = ..

fromEnum wday) ‘div‘ 7) show (let n = fromEnum wday in if n == 0 then 7 else n) decode ’V’ = let (week.Implementation-dependent show2 ((yday + 7 .if fromEnum wday > 0 then fromEnum wday . 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 ..1 else 6) ‘divMod‘ 7 in show2 (if days >= 4 then .236 CHAPTER 24. -.

if fromEnum wday > 0 then fromEnum wday .1. LIBRARY TIME week+1 else if week == 0 then 53 else week) decode ’W’ = show2 ((yday + 7 . show3 :: Int -> String show2 x = [intToDigit (x ‘quot‘ 10). intToDigit x] else show2 x show3 x = intToDigit (x ‘quot‘ 100) : show2 (x ‘rem‘ 100) 237 .1 else 6) ‘div‘ 7) decode ’w’ = show (fromEnum wday) decode ’X’ = doFmt (timeFmt l) decode ’x’ = doFmt (dateFmt l) decode ’Y’ = show year decode ’y’ = show2 (year ‘rem‘ 100) decode ’Z’ = tzname decode ’%’ = "%" decode c = [c] show2. intToDigit (x ‘rem‘ 10)] show2’ x = if x < 10 then [ ’ ’. show2’.24.

238 CHAPTER 24. DATES AND TIMES .

dateTimeFmt. String). defaultTimeLocale) where data TimeLocale = TimeLocale { wDays :: [(String. String)].Chapter 25 Locale module Locale(TimeLocale(. dateFmt. At present. amPm :: (String.). Show) defaultTimeLocale :: TimeLocale ----full and abbreviated week days full and abbreviated months AM/PM symbols formatting strings The Locale library provides the ability to adapt to local conventions. timeFmt. months :: [(String. 239 . time12Fmt :: String } deriving (Eq. Ord. it supports only time and date information as used by calendarTimeToString from the Time library. String)]..

240

CHAPTER 25. LOCALE

25.1 Library Locale
module Locale(TimeLocale(..), defaultTimeLocale) where data TimeLocale = TimeLocale { wDays :: [(String, String)], months :: [(String, String)], amPm :: (String, String), dateTimeFmt, dateFmt, timeFmt, time12Fmt :: String } deriving (Eq, Ord, Show) ----full and abbreviated week days full and abbreviated months AM/PM symbols formatting strings

defaultTimeLocale :: TimeLocale defaultTimeLocale = TimeLocale { wDays = [("Sunday", "Sun"), ("Monday", "Mon"), ("Tuesday", "Tue"), ("Wednesday", "Wed"), ("Thursday", "Thu"), ("Friday", "Fri"), ("Saturday", "Sat")], months = [("January", ("March", ("May", ("July", ("September", ("November", "Jan"), "Mar"), "May"), "Jul"), "Sep"), "Nov"), ("February", ("April", ("June", ("August", ("October", ("December", "Feb"), "Apr"), "Jun"), "Aug"), "Oct"), "Dec")],

amPm = ("AM", "PM"), dateTimeFmt = "%a %b %e %H:%M:%S %Z %Y", dateFmt = "%m/%d/%y", timeFmt = "%H:%M:%S", time12Fmt = "%I:%M:%S %p" }

Chapter 26

CPU Time
module CPUTime ( getCPUTime, cpuTimePrecision ) where getCPUTime cpuTimePrecision :: IO Integer :: Integer

Computation getCPUTime returns the number of picoseconds of CPU time used by the current program. The precision of this result is given by cpuTimePrecision. This is the smallest measurable difference in CPU time that the implementation can record, and is given as an integral number of picoseconds.

241

242

CHAPTER 26. CPU TIME

243

244

CHAPTER 27. RANDOM NUMBERS

Chapter 27

Random Numbers
module Random ( RandomGen(next, split, genRange), StdGen, mkStdGen, Random( random, randomR, randoms, randomRs, randomIO, randomRIO ), getStdRandom, getStdGen, setStdGen, newStdGen ) where ---------------- The RandomGen class -----------------------class RandomGen genRange :: g next :: g split :: g g where -> (Int, Int) -> (Int, g) -> (g, g)

---------------- A standard instance of RandomGen ----------data StdGen = ... -- Abstract instance RandomGen StdGen where ... instance Read StdGen where ... instance Show StdGen where ... mkStdGen :: Int -> StdGen ---------------- The Random class --------------------------class Random a where randomR :: RandomGen g => (a, a) -> g -> (a, g) random :: RandomGen g => g -> (a, g) randomRs :: RandomGen g => (a, a) -> g -> [a] randoms :: RandomGen g => g -> [a] randomRIO :: (a,a) -> IO a randomIO :: IO a instance instance instance instance instance instance Random Random Random Random Random Random Int Integer Float Double Bool Char where where where where where where ... ... ... ... ... ...

---------------- The global random generator ---------------newStdGen :: IO StdGen setStdGen :: StdGen -> IO () getStdGen :: IO StdGen getStdRandom :: (StdGen -> (a, StdGen)) -> IO a

then . when passing a random number generator down to recursive calls). g) -. It is required that:   The second condition ensures that genRange cannot examine its argument.Default method genRange g = (minBound. For example. the Float instance of Random allows one to generate random values of type Float.27.1. The library is split into two layers: A core random number generator provides a supply of bits. AND THE STDGEN GENERATOR 245 The Random library deals with the common task of pseudo-random number generation. and a new generator. and the StdGen generator The class RandomGen provides a common interface to random number generators.           The class Random provides a way to extract particular values from a random number generator.     – genRange     – If genRange . THE RANDOMGEN CLASS.4] are the only examples we know of). The library makes it possible to generate repeatable results. and hence the value it returns can be determined only by the instance of RandomGen. The split operation allows one to obtain two independent random number generators. .1 The RandomGen class. 27. That in turn allows an implementation to make a single call to genRange to establish a generator’s range. This is very useful in functional programs (for example. without being concerned that the generator returned by (say) next might have a different range to the generator passed to next. g) split :: g -> (g. class RandomGen g where genRange :: g -> (Int. but very little work has been done on statistically robust implementations of split ([1.Int) next :: g -> (Int. or to get different results on each run by using the system-initialised generator.   ¦ ¡    ¡ .maxBound) The genRange operation yields the range of values returned by the generator. or by supplying a seed from some other source. 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). by starting with a specified initial random number generator.

the abstract data type StdGen: data StdGen = . mkStdGen :: Int -> StdGen The StgGen instance of RandomGen has a genRange of at least 30 bits. 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 finite portion of the string.... variantOf g) Here. But now consider these two apparently-independent generators: g1 = snd (split g) g2 = snd (split (fst (split g))) If split genuinely delivers independent generators (as specified)... all we require is that split deliver generators that are (a) not identical and (b) independently robust in the sense just given. by mapping an Int into a generator.246 CHAPTER 27. then g1 and g2 should be independent. instance Read StdGen where .. . instance Show StdGen where . The function mkStdGen provides an alternative way of producing an initial generator. A superficially attractive implementation of split is instance RandomGen MyGen where . distinct arguments should be likely to produce distinct generators. Until more is known about implementations of split. but in fact they are both equal to variantOf g.. In general. split returns g itself and a new generator derived from g. It is required that read (show g) == g. the read instance of StdGen has the following properties: It guarantees to succeed on any string.. of course.. Programmers may. RANDOM NUMBERS The Random library provides one instance of RandomGen. Different argument strings are likely to result in different results. -. split g = (g.Abstract instance RandomGen StdGen where . The Show/Read instances of StdGen provide a primitive way to save the state of a random number generator.. Implementation warning.3]. supply their own instances of RandomGen. In addition. The result of repeatedly using next should be at least as statistically robust as the “Minimal Standard Random Number Generator” described by [2. Implementations of the above form do not meet the specification. Again.

. and returns a random value uniformly distributed in the closed interval . but does not take a range.. g) random :: RandomGen g => g -> (a.. but they may be.   – For bounded types (instances of Bounded. It is unspecified what happens if .. such as Char).  – For fractional types. .. 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 .similar. g) randomRs :: RandomGen g => (a.. . . . depending on the implementation and the interval. the range is (arbitrarily) the range of Int.. produce an infinite list of random values. the Random class allows the programmer to extract random values of a variety of types: class Random a where randomR :: RandomGen g => (a. THE RANDOM CLASS 247 27... – For Integer. a) -> g -> [a] randoms :: RandomGen g => g -> [a] randomRIO :: (a. .2..   The plural versions.g’) = random g randomRs = ... randomRs and randoms. random does the same as randomR. the range is normally the whole type. a) -> g -> (a.2 The Random class With a source of random number supply in hand. and do not return a new generator.Default methods randoms g = x : randoms g’ where (x. For continuous types there is no requirement that the values and are ever produced... randomR takes a range and a random number generator .27.a) -> IO a randomIO :: IO a -. together with a new generator.. .. the range is normally the semi-closed interval    ¦    ¨ § ¨¥   2 7  § ¨¥  £ § ¨¥ 2 7   2 7 § ¨¥ 2 7   .

“Random number generators .       newStdGen applies split to the current global random generator. pp87-88.sbg. It is initialised automatically in some system-dependent fashion.mat. and updates the global generator with the new generator returned by the function. ACM SIGSIM Simulation Digest 28(1). “Distributed random number generation”. 33(1). Comm ACM. global random number generator of type StdGen. by using the time of day. [3] DG Carta.6)) References [1] FW Burton and RL Page.good ones are hard to find”.at/ is a great source of information. [2] SK Park.3 The global random number generator There is a single.3). Oct 1988. and KW Miller. . July 1998. use setStdGen. getStdRandom uses the supplied function to get a value from the current global random generator. To get deterministic behaviour. “Two fast implementations of the minimal standard random number generator”. respectively. or Linux’s kernel random number generator. for example. 2(2):203-212. StdGen)) -> IO a getStdGen and setStdGen get and set the global random number generator. Journal of Functional Programming. RANDOM NUMBERS The IO versions. Jan 1990. pp1192-1201. “Don’t trust parallel Monte Carlo”. and returns the other. setStdGen getStdGen newStdGen getStdRandom :: :: :: :: StdGen -> IO () IO StdGen IO StdGen (StdGen -> (a. implicit.ac.248   CHAPTER 27. use the global random number generator (see Section 27. rollDice gets a random integer between 1 and 6: rollDice :: IO Int rollDice = getStdRandom (randomR (1. held in some global variable maintained by the IO monad. 27. updates it with one of the results. randomRIO and randomIO. For example. [4] P Hellekalek. Comm ACM 31(10). pp8289. The Web site http://random. April 1992.

Albuquerque. Blott. Jones. How to make ad hoc polymorphism less ad hoc. January 1989.L. e [5] J. Englewood Cliffs. Jr. Amsterdam. [4] K-F. Hudak. Reading. In APL ’81 Conference Proceedings. Damas and R. Can programming be liberated from the von Neumann style? A functional style and its algebra of programs. N. A system of constructor classes: overloading and implicit higher-order polymorphism. [9] P.R.B. 249 . J. Paris. October 1999. Yale University. [2] H. In Proceedings of the 16th ACM Symposium on Principles of Programming Languages. Feys. CACM. Principal type schemes for functional programs.Bibliography [1] J. December 1969. and J. Backus. January 1995. Transactions of the American Mathematical Society. 21(8):613–641. Fasel. The Unicode Standard. North-Holland Pub. [7] Mark P. Texas. September 1981. [10] S. Milner.. Version 3. pages 248–256. 5(1). [12] P. The principal type scheme of an object in combinatory logic. August 1978. In Proceedings of the 9th ACM Symposium on Principles of Programming Languages. Fax´ n A static semantics for Haskell Journal of Functional Programming. Combinatory Logic. Wadler and S. Principal values and branch cuts in complex APL. 2000. Prentice-Hall International. Hindley. The Implementation of Functional Programming Languages. A gentle introduction to Haskell. 2002. pages 60–76. [11] Unicode Consortium. [3] L. Technical Report YALEU/DCS/RR-901. Haskell Workshop. Curry and R. [8] Mark P. 1958.0. 146:29–60. January 1982. Journal of Functional Programming. Austin. May 1996. Addison Wesley. New Jersey.M. pages 207–212.. Peyton Jones. Typing Haskell in Haskell. Penfield. MA. San Francisco. Peterson. Co. [6] P. 1987. Jones.

250 BIBLIOGRAPHY .

235 aexp. 82. 55. 104. 110 (. 104. 142 >. 79. 116 $. 55. Ordinary index entries are shown in a roman font. 97. 84. 55. 151. 84. 105 AbsoluteSeek. 88. 30 <. 104. 140 appendFile. 82. 91. 109 @. 119 ANYseq. 129 any.. 177 !!. 141 all.). 105.Index font. 90. 97. 90.. 104. 174. 104. 104. 109 ˆˆ. 106 +. 119 alt. 81. 12 \b. 92. 9. 97. 173. 90. 43. 91. 90. 104. 104.). 104. 104. 20–23. 92. 12 \t. 126 AppendMode. 104. 173. 55. 139 ambiguous type. 153 &&. 55. 104. 109 >>=. 91. 55. 55. 104. 9. 12 \f. see also + pattern ++. Code Index entries that refer to nonterminals in the Haskell syntax are shown in an entities are shown in typewriter font. 55. 91. see operator application approxRational. 175–177 /=. 55. 55. 12 . 81. 177 accumArray. 110 ˜. 119 ANY. 76 accum. 45. 230 ˆ. 110 %. see lambda abstraction \&. 91. 55. 55. 110 /. 115 -. see function application operator. 16. 55. 142 =<<. 19 function. 91. 12 \r. 109 _. 214 application. 173. 110 $!. 93. 105 **. 180. see as-pattern [] (nil). 104. 104. 84. 173. 104. 104. 115. 55. 233. 91. 174. 80 \\. 80 (. see irrefutable pattern abbreviated module. 51. 31. 139 alts. 151. 109 ==. 84. 92. 153 251    § 7 3¢ §§ ¢ ¦ . 104. 91. 142 >>. 104. 187 \. 55. 91. 9. 80 (). 88. 67. 17. 142 :. 55. 175. 55. 12 \v. 79. see trivial type and unit expression *. 142 <=. 81. 177 acos. see also negation . 104. 55. 25. 217 abstract datatype. 62 and. 66 abs. 186. 104. 92. 12 \n. 182 \a. 55. 106 //. 12 \\. 202. 88. 55. !. 91. 155. 25. 55. 80 :+. 176. 55. 105. 156 ::. 142 >=. 129 ap. 206 apat. 106 acosh. 129 any. 106 addToClockTime. see wildcard pattern ||. 139 algebraic datatype. 44.

226 Char (datatype). 232 ClockTime (datatype). 155. 40. 193. 235 calendarTimeToString. 91. 9 comment. 155. 174 Array (module). 173. 221 break. 104. 9. 130 conjugate. 108 atanh. 137 ceiling. 80 Array (datatype). 12. 110 Char (module). 221 bracket_. 197. 177 as-pattern (@). 9 end-of-line. 69. 79 Bounded (class). 18. 174. 11. 106 atype. 176. 156 con. 37 function. 177 bracket. 9. 7 ascLarge. 177 asTypeOf. 12. 105 derived instance. 235 case expression. 106 atan2. 174 derived. 79. 121. 93. 9. 230 catMaybes. 93 comment. 130 coercion. 125. 111 bounds. 173. 67 with an empty where part. 106 asinh. see function binding pattern. 84. 41. 42 class method. 114 atan. 47. 137 cdecls. 129 ascii. 197 array. 115 concatMap. 92. 137 class assertion. 98. 21 conid. 129 compare. 23. 195. 210 CalendarTime (datatype). 198 cis. 156 conop. 110 boolean. 129 ascSymbol. 48. 79. 173. 31. 174. 130 character. 174.252 arithmetic operator. 89. 17. 115 conditional expression. 142 Complex (module). 234 closecom. 38. 156 class. 176 array. 130 ASCII character set. see simple pattern binding body. 93. 25 INDEX catch. 137 BufferMode (datatype). 137 basic input/output. 48 class environment. 118 btype. 10. 47 class. 234 char. 9 nested. 18. 9. 161. 51. 91. 211. 74 cname. 195. 215 closure. 107 changing the directory. 155. 233. 143 instance for Char. 106 assocs. 161. see transparent character set charesc. 38. 47. 136 cntrl. 40. 47. 95 binding. 66. 17. 91. 39. see ASCII character set transparent. 173. 33 ascDigit. 90 arithmetic sequence. 194 cdecl. 129 asin. 130 chr. 140 . 9. 91. 38. 12. 136 Bool (datatype). 211. 12. 129 closing a file. 232. 38. 129 ascSmall. 12 character set ASCII. 232. 49 clock time. see pattern binding simple pattern. 79 literal syntax. 173 accumulated. 140 concat. 9. 92. 41 class declaration.

43 abstract. 81. 37 class. 224 Directory (module). 110 constr. 182. 118 dropWhile. 137 decodeFloat. 224. 112 drop. 180. 186 elems. 151. 41 context. 115.. 182. 41. 197 directories. 118 e. 56. 184. 234 dclass. 232. 225 deleting files. 224 div. 38. 50. 239. 180. 114 Curry. see abstract datatype algebraic. 106 cosh. 11. 26. 108 . 177 encodeFloat. 240 dateTimeFmt. 241 CPUTime (module). 186 elemIndices. 138 decimal. 43. 91. 187 deleteBy. 241 createDirectory. 111 either. 43. 180. 240 delete. 91. 138 constructor class. 182. 91. 119 elemIndex. see data declaration recursive. 235 ctHour. see instance declaration within a class declaration. see newtype declaration dateFmt. 129 data constructor. 55. 163 doesDirectoryExist. 89.INDEX const. 59 cos. 174. 106 divMod. 241 cpuTimePrecision. 48. 10. 9. see default declaration 253 fixity. 145 default declaration. 130 context. 91. 43. 43. 24 within an instance declaration. see data declaration default. 167 Either (datatype). 180. see algebraic datatype declaration. 40 consym. 58 derived instance. 9. see recursive datatype renaming. 225 creating a file. 137 declaration. 55. 47 within a let expression. 137 context reduction. 187 deleteFirstsBy. 81. 93. 213. 138 constrs. 130 decl. 90. see class declaration datatype. 141. 92. 97 doDiv. 138 diffClockTimes. 195. 49 declaration group. 51 defaultTimeLocale. 58 decls. 93. 233. 235 ctIsDST. 27. 51. 235 current directory. 232. 108 default class method. 173. 226 curry. 184. 240 Day (datatype). 106 do expression. 239. 232. vii cycle. 117 dashes. 111 elem. 104. Haskell B. 180. 232. 43 datatype. see import declaration instance. 81. 232. 235 ctMin. 224 doesFileExist. 92. see also instance declaration deriving. 235 digit. 80. 38. 187 deleting directories. 38 constructor expression. 106 cosine. 129 digitToInt. 153 dependency analysis. 92. 239. 225 denominator. 93 CPU time. 224 Double (datatype). 214 ctDay. 43 data declaration. see fixity declaration import.

166 ¡ ¢ ¡  . 91. 43. 180. 82. 92. 91 export. 21. 130 even. 92. 16. 182. 229 exitFailure. 106 enumeration. 86. 91. 4. 229 exitWith. 180. 215 file system. 114. 106 exponent. 112 float. 30. 139 exp. 49. 137 fixity declaration. 215 entity. see type expression unit. 207 find. 4. 111 instance for Double. 108 floatRange. 115 filterM. 51. 93. 19. 19. 162 expts. 159. 139 FFFormat (datatype). 94. 229 EQ. 79 fbind. 177 instance for Char. 54. see class environment type. 158 superclass of RealFloat. 106 instance for Complex. 12 floatDigits. 163 f. 97. 16. see case expression conditional. 229 . 92. 202. 229 ExitFailure. 86. 29 fielddecl. 89. 93. 28 selection. see type environment environment variables. 92. 108 exception handling. 213 file buffering. 48. 99. 81 Eq (class). 104 error. 125 filter. 89. 108 Floating (class). 86. 224 execution time. 17 error. 154 superclass of Integral. 110 Float (datatype). 136 export list. 139 exp. 213 FilePath (type synonym). 180. 24–26. 54 flip. 164 field label. 186 fixity. 138 file. 136 v INDEX expression. see conditional expression let. 88. see let expression simple case. 89. 105 derived instance. 93. see label. 170 enumFrom. 33 floatRadix. 212 False. 229 ExitSuccess. 113 instance for Float. 17. 186 findIndices. 18 fixity. 51. 66 exports.254 end of file. 109. 65 Enum (class). 108 floating literal pattern. 44 construction. 105 enumFromTo. 142 instance for Char. 38. 167 fail. 67. 230 escape. 241 ExitCode (datatype). 105 environment class. 28. 105 enumFromThen. see unit expression expression type-signature. 113 instance for Ratio. 67. 15 case. 105 enumFromThenTo. 81. see simple case expression type. 16. 186 findIndex. 98 executable. 52 expt. 110 superclass of Num. 51. 86. 108 exponentiation. 12. 30. 142 instance for Array. 92. 86. 91. 105 superclass of Ord. 27 update. 139 fexp. 108 floatToDigits. 104 derived instance.

41 functional language. 229 getChar. 181. 107 fromEnum. 91. 59 generalization preorder. 139 gdrhs. 106 fst. 188 GT. 54. 138 gdpat. 116 foldl1. 233. 194 fromRat. 56. 96. 96. 81 gtycon. 181. 109 fromJust. 224. 23 genericDrop. 181. 206 Handle (datatype). 56 function type. 9.INDEX floor. 49. 190 genericSplitAt. 219 getArgs. 157 instance for Ratio. 40. 3 Haskell kernel. 138 gap. 25. 4 hClose. 89. 34 guard. 153 superclass of Floating. 107 flushing a file buffer. 187 groupBy. 162 fromRat’. 116 foldM. 111 functor. 210 HandlePosn (datatype). 106 instance for Complex. 125 getModificationTime. 244. 92. 81 function binding. 217 fmap. 189 genericTake. 109 instance for []. 224 getPermissions. 215 head. 111 instance for Maybe. 202. 91. 181. 105 fromIntegral. 181. 190 genericLength. 181. 108 gcon. 9. 159. 93. 181. 176 foldl. 11. 137 guard. 229 getLine. 162 fromRational. 91. 109. 92. 91. 225 getDirectoryContents. 125 getClockTime. 235 getContents. 90. 140 gconsym. 9. 129 fpat. 40. 125 getCPUTime. 92. 140 Fractional (class). 25. 117 formal semantics. 130 hexit. 184. 3 formatCalendarTime. 181. 129 255 . 87 funlhs. 229 getStdGen. 244. 207 foldr. 248 graphic. 113 instance for Array. 18. 31. 80. vii. 137 generalization. 12. 236 formatRealFloat. 55. 90. 244. 117 foldr1. 248 getStdRandom. 233. 210. 86. 194 fromMaybe. 189 genericReplicate. 225 getEnv. 23. 114 function. 177 instance for IO. 241 getCurrentDirectory. 245 get the contents of a file. 213 Haskell. 183. 96. 140 fpats. 87. 56. 210 handles. 224 getProgName. 38. 189 genericIndex. 18. 18. 106 superclass of RealFrac. 138 gendecl. 94. 115 hexadecimal. vii Functor (class). 18 gd. 31. 189 genRange. 193. 25. 87. 47. 105 fromInteger. 193. 129 group. 130 gcd. 42 generator. 18. 202. 224. 165 formfeed.

49. 197 isAlreadyExistsError. 110 idecl. 69. 38. 217 hiding. 195. 112 Integer (datatype). see also derived instance importing and exporting. 218 hIsSeekable. 126 intersect. 69. 155. 211. 212 ioeGetHandle. 177 init. 211. 183. 98. 212 id. 171. 215 hIsOpen. 218 hGetContents. 212. 91. 171. 212. 172 insert. 81. 194 . 214 irrefutable pattern. 219 hPrint. 211. 211. 33. 197 isControl. 210. 181. 71 with an empty where part. 125. 211. 211. 211. 211. 211. 184. 4. 184. 210 IO (datatype). 106 interact. 211. 211. 212 IOError (datatype). 193. 219 hGetLine. 215 isAscii. 215 isEOFError. 218 hLookAhead. 212 isFullError. 183. 211. 211. 211. 137 idecls. 136 impdecls. 217 hWaitForInput. 195. 116 inits. 57 isAlpha. 89. 211. 218 hGetPosn. 181. 34. 211. 210 input/output examples. 92. 188 inlining. 198 IO. 212 ioError. 187 intersectBy. 197 isIllegalOperation. 69 impspec. 136 index. 210 I/O errors. 169. 9 if-then-else expression. 211. 24. 211. 211. 38. 70 Hindley-Milner type system. 96. 12 integer literal pattern. 49. 195. 221 ioeGetErrorString. 211. 183. 216 hSetPosn. 197 isDigit. 137 identifier. 211. 211. 156 impdecl. 138 instance declaration. 169. 181. 187 intToDigit. 181. 81. 125 IOMode (datatype).256 hFileSize. 212 ioeGetFileName. 211. 219 hPutStr. 216. 218 hIsReadable. 211. 172 indices. 136 import. 163 Integral (class). 189 inst. 219 inRange. 49 Int (datatype). 218 hSeek. 181. 211. 187 intersperse. 211. 211. 210. 219 hPutChar. 211. 219 hPutStrLn. 211. 212 isHexDigit. 181. 211. 173. 212 isJust. 211 hReady. 147 INDEX input/output. 89. see conditional expression imagPart. 197 isDoesNotExistError. 215 isEOF. 66. 218 I/O. 188 insertBy. 33 integerLogBase. 211. 112 integer. 111 IO (module). 212 isAlreadyInUseError. 92. 195. 195. 69. 49. 217 hGetChar. 182. 218 hIsEOF. 195. 215 hFlush. 38. 50. 195. 49. 81. 218 hIsWritable. 217 hSetBuffering. 58 hIsClosed. 174. 136 import declaration. 211. 217 hGetBuffering. 197 isAlphaNum. 214.

198 max. 197 isLower. 234. 41 listArray. 210. 91 logBase. 177 join. 181. 194 isOctDigit. 195. 172 derived instance. 109 match. 155. 202. 40. 19. 195. 119 . 91. 197 isUserError. 84. 7 lexLitChar. 39.INDEX isLatin1. 170 instance for Char. 109 Left. 193. 197 isNothing. 195. 74 liftM. 184. 86. 197 isPermissionError. 159. 129 literal pattern. 176. 176. 207 liftM4. 64 label. 211. 80 list type. 44. 19. 206 mapM. 234 ixmap. 195. 206 Just. 188 mapAccumR. 88. 81 length. 50. 12. 173. 129 lexical structure. 212 iterate. 139 libraries. 44. 195. 50. 65 making directories. 202. 181. 172 Ix (module). 134 Locale (module). 207 liftM5. 207 v 257 liftM2. 177 listToMaybe. 183. 181. 180. 117 Ix (class). 106 logarithm. 92. 188 mapAndUnzipM. 32 literate comments. 143 maximal munch rule. 211. 116 layout. 195. 92 magnitude. 207 linear pattern. 169. 225 map. 197 isSuffixOf. 172. 202. 172 instance for Integer. 9. 27 lambda abstraction. 45. 176. 91. 181. 65 main. see also off-side rule lcm. 212. 142 maxBound. 109 mapMaybe. 171. 173. 188 isPrint. 31. 219 lookup. 140 LT. 194 literal. 169. 202. 81 magnitude. 116 let expression. 24 in do expressions. 23. 174. 118 List (module). 239. 122 lexDigits. 106 lookahead. 173. 40. 104. 194 mapM_. 172 instance for Int. 193. 202. 45. 168 lexeme. 240 locale. 232. 81 kind. 105. 23 lex. 19 large. 197 isSpace. 156 Main (module). 188 isUpper. 31. 127 maximum. 186 list. 31. 56 lines. 181. 13. 40. 115 mapAccumL. 9. 202. 88. 215 isPrefixOf. 129 last. 119 maximumBy. 89. 64 kind inference. 199 . 21. 189 Maybe (datatype). 81. 91. 207 liftM3. 195. 183. 56 linearity. 80 list comprehension. 130. 193. 239 log. 9. 9. 111 v § ¢ £ 7¡ ¡ ¢ ¡  7 . 26 in list comprehensions. 16. 202.

9. 187 null. 32–34. 18 numerator. 153 superclass of Real. 248 newtype declaration. 232. 84. 105 negation. 137 or. 90. 130 octit. 202. 9. 90. 119 Ord (class). 52. 19. 66. see special name namespaces. 193. 65 module. 61 monomorphism restriction. 105. 34. 57 name qualified. 206 Monad (module). 180. 113 octal. 206 instance for []. 113 numericEnumFromThen. 197 numeric type. 18. 9. 46. 245 nonnull. 66. 113 instance for IO. 178 instance for Char. 119 minimumBy. 95 MonadPlus (class). 19 ops. 105 number. 54. 202. 234 moving directories. 129 negate. 156 mkStdGen. 105 ord. 186 nubBy. 54. 106 modid. 88. 91. 198 Ordering (datatype). 89. 104 derived instance. 20 newconstr. 111 instance for Maybe. 111 instance for Ratio. 129 newStdGen. 105 instance for Complex. 81. 157 instance for Ratio. 181. 184. 111 maybeToList. 16. see qualified name special. 202. 140 opencom. 138 newline. 89 literal syntax. 206 mzero. 121. 91. 113 numericEnumFromThenTo. 89. 9. 113 numericEnumFromTo. 104. 5.258 Maybe (module). 111 superclass of MonadPlus. 244. 214 operating system commands. 61 Month (datatype). 129 odd. 13. 244. 51. 26. 11. 55. 136 module. 10. 182. 33. 84. 180. 81 nub. 189 mkPolar. 225 mplus. 168 not. 89. 91. 9. 106 superclass of Real. 194 method. see also layout op. 195. 143 minimum. 206 instance for Maybe. 109 instance for []. 81. 153 Numeric (module). 244. 246 mod. 206 + pattern. 90 numericEnumFrom. 27. see class method min. 88. 19. 225 moving files. 79. 10 ncomment. 11 translation of literals. 206 monomorphic type variable. 91. 19 operator application. 186. 55. 230 operator. 159. 142 minBound. 184. 11. 206 monad. 104. 115. 151. 194 maybe. 136 Monad (class). 110 notElem. 38. 161. 129 openFile. 60. 130. 112 ¢ ¦ . 202. 142 instance for Array. 206 msum. 153 superclass of Fractional. 46 INDEX next. 210. 108 off-side rule. 116 Num (class). 155. 119 Nothing. 193. 202. 214 opening a file. 17. 32.

224 phase. 130 qconop. 247 randomRIO. 54 polymorphism. 125 putStrLn. 43. 105 Prelude implicit import of. 121 principal type. 130 qop. 244. 11. 18. 140 qvarsym. 104. 72 qualifier. 103. 244 random. 110 overloaded functions. 25. 140 qconid. 96. 124 instance for Array. see floating literal pattern integer. 181. 85. 51. 156 polling a handle for input. 245 randomIO.INDEX otherwise. 18. 11. 143 instance for [a]. 217 RandomGen. 218 polymorphic recursion. see integer literal pattern irrefutable. 125 PreludeIO (module). 225 pattern. 3 properFraction. 11. 106 qvar. 96. 229 program structure. 119 program. 92. 38 overloaded pattern. 244. 47 defaults. see constructed pattern floating. 247 Random (module). 53 print. 244. 130 qtycon. 106 quotRem. 9. 151 Ratio (module). see wildcard pattern constructed. 42. 161 Rational (type synonym). 31. 130 qual. 151 Read (class). 103. 11. 247 randomR. 244. 140 pat. 151. 93. 75. 11. 140 path. 183. 23. 103 PreludeBuiltin (module). 125 qcon. 96. 140 qtycls. 30 overloaded constant. 90. 155. see irrefutable pattern linear. 106 polar. 247 randoms. 70. 244. 171. 247 random access files. 130 qvarop. 153. 31. 172 rangeSize. 153 rational numbers. 125 putStr. 75 Prelude (module). 155. 51 partition. 11. 213 pi. 229 program name. see linear pattern + . 96. 130 Random (class). see + pattern refutable. 57 pattern-matching. 140 qvarid. see pattern-matching overloading. 129 v 259 program arguments. 41 quot. 169. 18. 19. 140 qconsym. see refutable pattern pattern binding. 244. 23 quantification. see as-pattern _. 91. 18. 172 Ratio (datatype). see also fixity pred. 247 range. 18. 125 PreludeList (module). 91. 30 @. 139 qualified name. 121 derived instance. 4 pragmas. 103. 147 precedence. 107 putChar. 34 Permissions (datatype). 55. 169. 115 PreludeText (module). 11. 103. 79. 156 physical file. 247 randomRs. 171. 125 product. 91. 187 . 178 ¢ ¦ ¢ ¦ § ¢ £¡ . 151. 103.

122 readSigned. 106 removeDirectory. 122 readable. 106 recursive datatype. 224. 225 renameDirectory. see also operator application SeekFromEnd. 225 renameFile. 139 rhs. 107 RealFloat (class). 225 setPermissions. 92. 225 repeat. 85. 117 scontext. 224. 91. 93. 76 seq. 10. 217 rem. 244. 85. 217 SeekMode (datatype). 10. 92. 94. 105 instance for Ratio. 116 scanr. 86. 104. 217 seeking a file. 10. 85. 88. 226 Show (class). 85. 51. 126 ReadMode. 154 superclass of RealFloat. 121 reads. 214 readFloat. 164 readEsc. 224. 217 semantics formal. 164 readIO. 119 . 159. 90. 110 sequence. 126 readList. 225 removeFile. 109 reverse. 92. 168 readHex. 224. 155. 97. 218 readInt. 162 scanl. 126. 224 section.260 instance for Char. 123 instance for Int. 214 Real (class). 108 RealFrac (class). 121. 123 instance for Integer. 88. 130 reservedop. 108 scaleRat. 16. 224. 159. 225 removing directories. 225 renaming files. 85. 96. 106 superclass of RealFrac. 56. 104. see formal semantics semi-closed handles. 159. 108 realPart. 86. 81 round. 164 readParen. 31. 214 readOct. 198 readLn. 116 scanl1. 137 searchable. 20. 96. 195. 117 reservedid. 91. 164 reading a directory. 92. 33 RelativeSeek. 92. 85. 109 sequence_. 226 reading from a file. 107 instance for Ratio. 109 recip. 225 renaming directories. 117 replicate. 121. 225 removing files. 138 Right. 143 readLitChar. 121 derived instance. 123 instance for Float. 210. 117 scanr1. 143 instance for [a]. 163 readsPrec. 159. 248 setting the directory. 124 v v § ¡ ¢ £¡ ¢ ¡  ¤ ¤ . 156 realToFrac. 143 ReadWriteMode. 91. 122 ReadS (type synonym). 55. 153 superclass of Integral. 140 INDEX scaleFloat. 123 instance for Ratio. 166 . 154 read. 89. 93. 214 separate compilation. 159. 224 readDec. 159. 81. 109 setCurrentDirectory. 46 refutable pattern. 224 setStdGen. 198 readFile. 124 instance for Double. 88. 130 return. 107 roundTo.

159. 91. 105 show. 122 showSigned. 85. 130 synonym. 26. 139 stmts. 164 showGFloat. 80. 127 System (module). 105 simple pattern binding. 143 showLitChar. 122 sign. 123 instance for Float. 121 shows. 159. 246 stdin. 159. 210 instance for Integer. 159. 124 instance for Double. see type signature signdecl. 235 tdMonth. 49 symbol. 92 signature.INDEX instance for Array. 188 space. 213 stmt. 85. 232. 159. 85. 159. 195. 213 standard prelude. 237 show3. 74. 123 instance for Ratio. 178 instance for Char. 154 superclass of Num. 130 subtract. 12. 118 special. 210. 123 instance for Int. 129 tail. 199 showOct. 9. 232. 43. 143 showString. 159. see also Prelude stderr. 117 takeWhile. 122 showEFloat. 188 sortBy. see transparent string string. 114 sort. 85. 129 span. 210. 85. 163 showList. 9. 91. 121 show2. 105 sum. 94. 92. 106 size of file. 106 tangent. 45 strictness flags. 183. 118 sqrt. 159. 115 tails. 80. 137 simpletype. 210. 108 succ. 163 showInt. 232. 244. 129 snd. 235 tdHour. 235 tdMin. 82 String (type synonym). 48. 111 string. 229 system. 91. 181. 57. 106 sine. 121. 79 literal syntax. see type synonym syntax. 163 showIntAtBase. 244. 139 strictness flag. 118 tan. 213 StdGen (datatype). 93 tanh. 235 261 . 53 significand. 184. 91. 121. 108 signum. 164 showFFloat. 41. 181. 119 superclass. 245 splitAt. 183. 9. 106 standard handles. 129. 232. 159. 93 sinh. 163 showParen. 46. 129 split. 123 instance for HandlePosn. 237 show2’. 235 tdPicosec. 122 ShowS (type synonym). 164 showFloat. 229 tab. 181. 188 take. 91. 237 showChar. 86. 163 showsPrec. 62 simpleclass. 45. 9. 232. 86. 91. 9. 215 small. 138 sin. 12 transparent. 164 showHex. 106 tdDay. 213 stdout. 92. 26.

92. 233. see expression typesignature type synonym. 181. 49 value. 240 to12. 67. 81 True. see constructed type function. 187 unionBy. 221 tuple. 130 tycon. 17. 198 topdecl (class). 129 uniLarge. 38. 43 type environment. 105 toUpper. 38. 4. 18. 136 topdecls. 129 uniSymbol. 12 UnicodePrims (module). 236 toCalendarTime. 129 unit datatype. 11. 42 type expression. 181. 98. 51 topdecl (instance). 185. 224 Time (module). 22 uniWhite. 224. 10. 114 unfoldr. 114 unwords. 235 toClockTime. 140 varid. 22. 195. 40. 130 type. 22. 9. 240 TimeDiff (datatype). 80 tuple type. 181. 184. 45. 230 the file system. 197 uniDigit. 45 topdecl. 137 type class. 232. 130 uncurry. see trivial type unit expression. 119 unzip. 235 transpose. see class type constructor. see trivial type tuple. 4 var. see monomorphic type numeric. 40. 232 time of day. 211. 235 terminating a program. 47 topdecl (data). 49 topdecl (newtype). 53 for an expression. 79 truncate. 240 TimeLocale (datatype). 181. 136 toRational. 11. 17. 93. 129 unless. see also datatype recursive. 46 topdecl (type). see numeric type principal. 119 until. 114 undefined. 9. 183. 180. 182. 195. 202. 49. 235 timeFmt. 235 toEnum. 42. 130 varop. 40 type renaming. 120 unzip3. 239. 232 time12Fmt. 41. 181. 11. 42 ambiguous. 9. 233. 234 time. 105 toInteger. 38. 232. 41 tycls. 206 unlines. 46 tyvar. 86. 4. 103. 40. 190 unzip5. 9. 39. 239. 129 union. 187 trigonometric function. 140 . 18. see ambiguous type constructed. 80. 188 Unicode character set. 191 unzip6. 91. 191 unzip7. see tuple type type. see function type list. 107 try. 17.262 tdYear. see principal type INDEX trivial. 181. 120 unzip4. 41. 198 toUTCTime. 125 valdefs. 11. see newtype declaration type signature. 66. 43 topdecl (default). see list type monomorphic. 180. 187 uniSmall. 93. 7. 239. 232. 233. 191 userError. 81. 49. 106 toLower. 9. 93 trivial type.

206 whitechar. 190 zipWith6. 10. 120 zip4. 190 zipWithM. 118 writable. 190 zip5. 190 zipWith. 120 zip3.INDEX vars. 181. 129 when. 190 zip7. 9. 129 wildcard pattern (_). 53. 181. 129 whitespace. 181. 224 writeFile. 202. 190 zip6. 97. 120 zipWith4. 181. 126. 202. 190 zipWith7. 202. 207 263 . 9. 137 varsym. 214 zip. 80. 207 zipWithM_. 120 zipWith3. 214 WriteMode. 181. 9. 181. 185. 9. 31 words. 129 whitestuff. 130 vertab. 181. 38. 185. 190 zipWith5. 181.

Sign up to vote on this title
UsefulNot useful