You are previewing Real World Haskell.
O'Reilly logo
Real World Haskell

Book Description

This easy-to-use, fast-moving tutorial introduces you to functionalprogramming with Haskell. You'll learn how to use Haskell in avariety of practical ways, from short scripts to large anddemanding applications. Real World Haskell takes youthrough the basics of functional programming at a brisk pace, andthen helps you increase your understanding of Haskell in real-worldissues like I/O, performance, dealing with data, concurrency, andmore as you move through each chapter.With this book, you will:

  • Understand the differences between procedural and functionalprogramming

  • Learn the features of Haskell, and how to use it to developuseful programs

  • Interact with filesystems, databases, and network services

  • Write solid code with automated tests, code coverage, and errorhandling

  • Harness the power of multicore systems via concurrent andparallel programming

  • You'll find plenty of hands-on exercises, along with examples ofreal Haskell programs that you can modify, compile, and run.Whether or not you've used a functional language before, if youwant to understand why Haskell is coming into its own as apractical language in so many major organizations, Real WorldHaskell is the best place to start.

    Table of Contents

    1. Real World Haskell
      1. SPECIAL OFFER: Upgrade this ebook with O’Reilly
      2. A Note Regarding Supplemental Files
      3. Preface
        1. Have We Got a Deal for You!
          1. Novelty
          2. Power
          3. Enjoyment
        2. What to Expect from This Book
          1. A Little Bit About You
        3. What to Expect from Haskell
          1. Compared to Traditional Static Languages
          2. Compared to Modern Dynamic Languages
          3. Haskell in Industry and Open Source
          4. Compilation, Debugging, and Performance Analysis
          5. Bundled and Third-Party Libraries
        4. A Brief Sketch of Haskell’s History
          1. Prehistory
          2. Early Antiquity
          3. The Modern Era
        5. Helpful Resources
          1. Reference Material
          2. Applications and Libraries
          3. The Haskell Community
        6. Conventions Used in This Book
        7. Using Code Examples
        8. Safari® Books Online
        9. How to Contact Us
        10. Acknowledgments
          1. Bryan
          2. John
          3. Don
          4. Thank You to Our Reviewers
      4. 1. Getting Started
        1. Your Haskell Environment
        2. Getting Started with ghci, the Interpreter
        3. Basic Interaction: Using ghci as a Calculator
          1. Simple Arithmetic
          2. An Arithmetic Quirk: Writing Negative Numbers
          3. Boolean Logic, Operators, and Value Comparisons
          4. Operator Precedence and Associativity
          5. Undefined Values, and Introducing Variables
          6. Dealing with Precedence and Associativity Rules
        4. Command-Line Editing in ghci
        5. Lists
          1. Operators on Lists
        6. Strings and Characters
        7. First Steps with Types
        8. A Simple Program
      5. 2. Types and Functions
        1. Why Care About Types?
        2. Haskell’s Type System
          1. Strong Types
          2. Static Types
          3. Type Inference
        3. What to Expect from the Type System
        4. Some Common Basic Types
        5. Function Application
        6. Useful Composite Data Types: Lists and Tuples
        7. Functions over Lists and Tuples
          1. Passing an Expression to a Function
        8. Function Types and Purity
        9. Haskell Source Files, and Writing Simple Functions
          1. Just What Is a Variable, Anyway?
          2. Conditional Evaluation
        10. Understanding Evaluation by Example
          1. Lazy Evaluation
          2. A More Involved Example
          3. Recursion
          4. Ending the Recursion
          5. Returning from the Recursion
          6. What Have We Learned?
        11. Polymorphism in Haskell
          1. Reasoning About Polymorphic Functions
          2. Further Reading
        12. The Type of a Function of More Than One Argument
        13. Why the Fuss over Purity?
        14. Conclusion
      6. 3. Defining Types, Streamlining Functions
        1. Defining a New Data Type
          1. Naming Types and Values
        2. Type Synonyms
        3. Algebraic Data Types
          1. Tuples, Algebraic Data Types, and When to Use Each
          2. Analogues to Algebraic Data Types in Other Languages
            1. The structure
            2. The enumeration
            3. The discriminated union
        4. Pattern Matching
          1. Construction and Deconstruction
          2. Further Adventures
          3. Variable Naming in Patterns
          4. The Wild Card Pattern
          5. Exhaustive Patterns and Wild Cards
        5. Record Syntax
        6. Parameterized Types
        7. Recursive Types
        8. Reporting Errors
          1. A More Controlled Approach
        9. Introducing Local Variables
          1. Shadowing
          2. The where Clause
          3. Local Functions, Global Variables
        10. The Offside Rule and Whitespace in an Expression
          1. A Note About Tabs Versus Spaces
          2. The Offside Rule Is Not Mandatory
        11. The case Expression
        12. Common Beginner Mistakes with Patterns
          1. Incorrectly Matching Against a Variable
          2. Incorrectly Trying to Compare for Equality
        13. Conditional Evaluation with Guards
      7. 4. Functional Programming
        1. Thinking in Haskell
        2. A Simple Command-Line Framework
        3. Warming Up: Portably Splitting Lines of Text
          1. A Line-Ending Conversion Program
        4. Infix Functions
        5. Working with Lists
          1. Basic List Manipulation
          2. Safely and Sanely Working with Crashy Functions
          3. Partial and Total Functions
          4. More Simple List Manipulations
          5. Working with Sublists
          6. Searching Lists
          7. Working with Several Lists at Once
          8. Special String-Handling Functions
        6. How to Think About Loops
          1. Explicit Recursion
          2. Transforming Every Piece of Input
          3. Mapping over a List
          4. Selecting Pieces of Input
          5. Computing One Answer over a Collection
          6. The Left Fold
          7. Why Use Folds, Maps, and Filters?
          8. Folding from the Right
          9. Left Folds, Laziness, and Space Leaks
          10. Further Reading
        7. Anonymous (lambda) Functions
        8. Partial Function Application and Currying
          1. Sections
        9. As-patterns
        10. Code Reuse Through Composition
          1. Use Your Head Wisely
        11. Tips for Writing Readable Code
        12. Space Leaks and Strict Evaluation
          1. Avoiding Space Leaks with seq
          2. Learning to Use seq
      8. 5. Writing a Library: Working with JSON Data
        1. A Whirlwind Tour of JSON
        2. Representing JSON Data in Haskell
        3. The Anatomy of a Haskell Module
        4. Compiling Haskell Source
        5. Generating a Haskell Program and Importing Modules
        6. Printing JSON Data
        7. Type Inference Is a Double-Edged Sword
        8. A More General Look at Rendering
        9. Developing Haskell Code Without Going Nuts
        10. Pretty Printing a String
        11. Arrays and Objects, and the Module Header
        12. Writing a Module Header
        13. Fleshing Out the Pretty-Printing Library
          1. Compact Rendering
          2. True Pretty Printing
          3. Following the Pretty Printer
        14. Creating a Package
          1. Writing a Package Description
          2. GHC’s Package Manager
          3. Setting Up, Building, and Installing
        15. Practical Pointers and Further Reading
      9. 6. Using Typeclasses
        1. The Need for Typeclasses
        2. What Are Typeclasses?
        3. Declaring Typeclass Instances
        4. Important Built-in Typeclasses
          1. Show
          2. Read
          3. Serialization with read and show
          4. Numeric Types
          5. Equality, Ordering, and Comparisons
        5. Automatic Derivation
        6. Typeclasses at Work: Making JSON Easier to Use
          1. More Helpful Errors
          2. Making an Instance with a Type Synonym
        7. Living in an Open World
          1. When Do Overlapping Instances Cause Problems?
          2. Relaxing Some Restrictions on Typeclasses
          3. How Does Show Work for Strings?
        8. How to Give a Type a New Identity
          1. Differences Between Data and Newtype Declarations
          2. Summary: The Three Ways of Naming Types
        9. JSON Typeclasses Without Overlapping Instances
        10. The Dreaded Monomorphism Restriction
        11. Conclusion
      10. 7. I/O
        1. Classic I/O in Haskell
          1. Pure Versus I/O
          2. Why Purity Matters
        2. Working with Files and Handles
          1. More on openFile
          2. Closing Handles
          3. Seek and Tell
          4. Standard Input, Output, and Error
          5. Deleting and Renaming Files
          6. Temporary Files
        3. Extended Example: Functional I/O and Temporary Files
        4. Lazy I/O
          1. hGetContents
          2. readFile and writeFile
          3. A Word on Lazy Output
          4. interact
            1. Filters with interact
        5. The IO Monad
          1. Actions
          2. Sequencing
          3. The True Nature of Return
        6. Is Haskell Really Imperative?
        7. Side Effects with Lazy I/O
        8. Buffering
          1. Buffering Modes
          2. Flushing The Buffer
        9. Reading Command-Line Arguments
        10. Environment Variables
      11. 8. Efficient File Processing, Regular Expressions, and Filename Matching
        1. Efficient File Processing
          1. Binary I/O and Qualified Imports
          2. Text I/O
        2. Filename Matching
        3. Regular Expressions in Haskell
          1. The Many Types of Result
        4. More About Regular Expressions
          1. Mixing and Matching String Types
          2. Other Things You Should Know
        5. Translating a glob Pattern into a Regular Expression
        6. An important Aside: Writing Lazy Functions
        7. Making Use of Our Pattern Matcher
        8. Handling Errors Through API Design
        9. Putting Our Code to Work
      12. 9. I/O Case Study: A Library for Searching the Filesystem
        1. The find Command
        2. Starting Simple: Recursively Listing a Directory
          1. Revisiting Anonymous and Named Functions
          2. Why Provide Both mapM and forM?
        3. A Naive Finding Function
        4. Predicates: From Poverty to Riches, While Remaining Pure
        5. Sizing a File Safely
          1. The Acquire-Use-Release Cycle
        6. A Domain-Specific Language for Predicates
          1. Avoiding Boilerplate with Lifting
          2. Gluing Predicates Together
          3. Defining and Using New Operators
        7. Controlling Traversal
        8. Density, Readability, and the Learning Process
        9. Another Way of Looking at Traversal
        10. Useful Coding Guidelines
          1. Common Layout Styles
      13. 10. Code Case Study: Parsing a Binary Data Format
        1. Grayscale Files
        2. Parsing a Raw PGM File
        3. Getting Rid of Boilerplate Code
        4. Implicit State
          1. The Identity Parser
          2. Record Syntax, Updates, and Pattern Matching
          3. A More Interesting Parser
          4. Obtaining and Modifying the Parse State
          5. Reporting Parse Errors
          6. Chaining Parsers Together
        5. Introducing Functors
          1. Constraints on Type Definitions Are Bad
          2. Infix Use of fmap
          3. Flexible Instances
          4. Thinking More About Functors
        6. Writing a Functor Instance for Parse
        7. Using Functors for Parsing
        8. Rewriting Our PGM Parser
        9. Future Directions
      14. 11. Testing and Quality Assurance
        1. QuickCheck: Type-Based Testing
          1. Testing for Properties
          2. Testing Against a Model
        2. Testing Case Study: Specifying a Pretty Printer
          1. Generating Test Data
          2. Testing Document Construction
          3. Using Lists as a Model
          4. Putting It All Together
        3. Measuring Test Coverage with HPC
      15. 12. Barcode Recognition
        1. A Little Bit About Barcodes
          1. EAN-13 Encoding
        2. Introducing Arrays
          1. Arrays and Laziness
          2. Folding over Arrays
          3. Modifying Array Elements
        3. Encoding an EAN-13 Barcode
        4. Constraints on Our Decoder
        5. Divide and Conquer
        6. Turning a Color Image into Something Tractable
          1. Parsing a Color Image
          2. Grayscale Conversion
          3. Grayscale to Binary and Type Safety
        7. What Have We Done to Our Image?
        8. Finding Matching Digits
          1. Run Length Encoding
          2. Scaling Run Lengths, and Finding Approximate Matches
          3. List Comprehensions
          4. Remembering a Match’s Parity
            1. Another kind of laziness, of the keyboarding variety
          5. Chunking a List
          6. Generating a List of Candidate Digits
        9. Life Without Arrays or Hash Tables
          1. A Forest of Solutions
          2. A Brief Introduction to Maps
            1. Type constraints
            2. Partial application awkwardness
            3. Getting started with the API
          3. Further Reading
        10. Turning Digit Soup into an Answer
          1. Solving for Check Digits in Parallel
          2. Completing the Solution Map with the First Digit
          3. Finding the Correct Sequence
        11. Working with Row Data
        12. Pulling It All Together
        13. A Few Comments on Development Style
      16. 13. Data Structures
        1. Association Lists
        2. Maps
        3. Functions Are Data, Too
        4. Extended Example: /etc/passwd
        5. Extended Example: Numeric Types
          1. First Steps
          2. Completed Code
        6. Taking Advantage of Functions as Data
          1. Turning Difference Lists into a Proper Library
          2. Lists, Difference Lists, and Monoids
        7. General-Purpose Sequences
      17. 14. Monads
        1. Revisiting Earlier Code Examples
          1. Maybe Chaining
          2. Implicit State
        2. Looking for Shared Patterns
        3. The Monad Typeclass
        4. And Now, a Jargon Moment
        5. Using a New Monad: Show Your Work!
          1. Information Hiding
          2. Controlled Escape
          3. Leaving a Trace
          4. Using the Logger Monad
        6. Mixing Pure and Monadic Code
        7. Putting a Few Misconceptions to Rest
        8. Building the Logger Monad
          1. Sequential Logging, Not Sequential Evaluation
          2. The Writer Monad
        9. The Maybe Monad
          1. Executing the Maybe Monad
          2. Maybe at Work, and Good API Design
        10. The List Monad
          1. Understanding the List Monad
          2. Putting the List Monad to Work
        11. Desugaring of do Blocks
          1. Monads as a Programmable Semicolon
          2. Why Go Sugar-Free?
        12. The State Monad
          1. Almost a State Monad
          2. Reading and Modifying the State
          3. Will the Real State Monad Please Stand Up?
          4. Using the State Monad: Generating Random Values
          5. A First Attempt at Purity
          6. Random Values in the State Monad
          7. Running the State Monad
          8. What About a Bit More State?
        13. Monads and Functors
          1. Another Way of Looking at Monads
        14. The Monad Laws and Good Coding Style
      18. 15. Programming with Monads
        1. Golfing Practice: Association Lists
        2. Generalized Lifting
        3. Looking for Alternatives
          1. The Name mplus Does Not Imply Addition
          2. Rules for Working with MonadPlus
          3. Failing Safely with MonadPlus
        4. Adventures in Hiding the Plumbing
          1. Supplying Random Numbers
          2. Another Round of Golf
        5. Separating Interface from Implementation
          1. Multiparameter Typeclasses
          2. Functional Dependencies
          3. Rounding Out Our Module
          4. Programming to a Monad’s Interface
        6. The Reader Monad
        7. A Return to Automated Deriving
        8. Hiding the IO Monad
          1. Using a newtype
          2. Designing for Unexpected Uses
          3. Using Typeclasses
          4. Isolation and Testing
          5. The Writer Monad and Lists
          6. Arbitrary I/O Revisited
      19. 16. Using Parsec
        1. First Steps with Parsec: Simple CSV Parsing
        2. The sepBy and endBy Combinators
        3. Choices and Errors
          1. Lookahead
          2. Error Handling
        4. Extended Example: Full CSV Parser
        5. Parsec and MonadPlus
        6. Parsing a URL-Encoded Query String
        7. Supplanting Regular Expressions for Casual Parsing
        8. Parsing Without Variables
        9. Applicative Functors for Parsing
        10. Applicative Parsing by Example
        11. Parsing JSON Data
        12. Parsing a HTTP Request
          1. Backtracking and Its Discontents
          2. Parsing Headers
      20. 17. Interfacing with C: The FFI
        1. Foreign Language Bindings: The Basics
          1. Be Careful of Side Effects
          2. A High-Level Wrapper
        2. Regular Expressions for Haskell: A Binding for PCRE
          1. Simple Tasks: Using the C Preprocessor
          2. Binding Haskell to C with hsc2hs
          3. Adding Type Safety to PCRE
          4. Binding to Constants
          5. Automating the Binding
        3. Passing String Data Between Haskell and C
          1. Typed Pointers
          2. Memory Management: Let the Garbage Collector Do the Work
          3. A High-Level Interface: Marshaling Data
          4. Marshaling ByteStrings
          5. Allocating Local C Data: The Storable Class
          6. Putting It All Together
        4. Matching on Strings
          1. Extracting Information About the Pattern
          2. Pattern Matching with Substrings
          3. The Real Deal: Compiling and Matching Regular Expressions
      21. 18. Monad Transformers
        1. Motivation: Boilerplate Avoidance
        2. A Simple Monad Transformer Example
        3. Common Patterns in Monads and Monad Transformers
        4. Stacking Multiple Monad Transformers
          1. Hiding Our Work
        5. Moving Down the Stack
          1. When Explicit Lifting Is Necessary
        6. Understanding Monad Transformers by Building One
          1. Creating a Monad Transformer
          2. More Typeclass Instances
          3. Replacing the Parse Type with a Monad Stack
        7. Transformer Stacking Order Is Important
        8. Putting Monads and Monad Transformers into Perspective
          1. Interference with Pure Code
          2. Overdetermined Ordering
          3. Runtime Overhead
          4. Unwieldy Interfaces
          5. Pulling It All Together
      22. 19. Error Handling
        1. Error Handling with Data Types
          1. Use of Maybe
            1. Loss and preservation of laziness
            2. Usage of the Maybe monad
          2. Use of Either
            1. Custom data types for errors
            2. Monadic use of Either
        2. Exceptions
          1. First Steps with Exceptions
          2. Laziness and Exception Handling
          3. Using handle
          4. Selective Handling of Exceptions
          5. I/O Exceptions
          6. Throwing Exceptions
          7. Dynamic Exceptions
        3. Error Handling in Monads
          1. A Tiny Parsing Framework
      23. 20. Systems Programming in Haskell
        1. Running External Programs
        2. Directory and File Information
        3. Program Termination
        4. Dates and Times
          1. ClockTime and CalendarTime
            1. Using ClockTime
            2. Using CalendarTime
            3. TimeDiff for ClockTime
          2. File Modification Times
        5. Extended Example: Piping
          1. Using Pipes for Redirection
          2. Better Piping
          3. Final Words on Pipes
      24. 21. Using Databases
        1. Overview of HDBC
        2. Installing HDBC and Drivers
        3. Connecting to Databases
        4. Transactions
        5. Simple Queries
        6. SqlValue
        7. Query Parameters
        8. Prepared Statements
        9. Reading Results
          1. Reading with Statements
          2. Lazy Reading
        10. Database Metadata
        11. Error Handling
      25. 22. Extended Example: Web Client Programming
        1. Basic Types
        2. The Database
        3. The Parser
        4. Downloading
        5. Main Program
      26. 23. GUI Programming with gtk2hs
        1. Installing gtk2hs
        2. Overview of the GTK+ Stack
        3. User Interface Design with Glade
          1. Glade Concepts
        4. Event-Driven Programming
        5. Initializing the GUI
        6. The Add Podcast Window
        7. Long-Running Tasks
        8. Using Cabal
      27. 24. Concurrent and Multicore Programming
        1. Defining Concurrency and Parallelism
        2. Concurrent Programming with Threads
          1. Threads Are Nondeterministic
          2. Hiding Latency
        3. Simple Communication Between Threads
        4. The Main Thread and Waiting for Other Threads
          1. Safely Modifying an MVar
          2. Safe Resource Management: A Good Idea, and Easy Besides
          3. Finding the Status of a Thread
          4. Writing Tighter Code
        5. Communicating over Channels
        6. Useful Things to Know About
          1. MVar and Chan Are Nonstrict
          2. Chan Is Unbounded
        7. Shared-State Concurrency Is Still Hard
          1. Deadlock
          2. Starvation
          3. Is There Any Hope?
        8. Using Multiple Cores with GHC
          1. Runtime Options
          2. Finding the Number of Available Cores from Haskell
          3. Choosing the Right Runtime
        9. Parallel Programming in Haskell
          1. Normal Form and Head Normal Form
          2. Sequential Sorting
          3. Transforming Our Code into Parallel Code
          4. Knowing What to Evaluate in Parallel
          5. What Promises Does par Make?
          6. Running Our Code and Measuring Performance
          7. Tuning for Performance
        10. Parallel Strategies and MapReduce
          1. Separating Algorithm from Evaluation
          2. Separating Algorithm from Strategy
          3. Writing a Simple MapReduce Definition
          4. MapReduce and Strategies
          5. Sizing Work Appropriately
            1. Mitigating the risks of lazy I/O
          6. Efficiently Finding Line-Aligned Chunks
          7. Counting Lines
          8. Finding the Most Popular URLs
          9. Conclusions
      28. 25. Profiling and Optimization
        1. Profiling Haskell Programs
          1. Collecting Runtime Statistics
          2. Time Profiling
          3. Space Profiling
        2. Controlling Evaluation
          1. Strictness and Tail Recursion
          2. Adding Strictness
            1. Normal form reduction
            2. Bang patterns
            3. Strict data types
        3. Understanding Core
        4. Advanced Techniques: Fusion
          1. Tuning the Generated Assembly
          2. Conclusions
      29. 26. Advanced Library Design: Building a Bloom Filter
        1. Introducing the Bloom Filter
        2. Use Cases and Package Layout
        3. Basic Design
          1. Unboxing, Lifting, and Bottom
        4. The ST Monad
        5. Designing an API for Qualified Import
        6. Creating a Mutable Bloom Filter
        7. The Immutable API
        8. Creating a Friendly Interface
          1. Re-Exporting Names for Convenience
          2. Hashing Values
          3. Turning Two Hashes into Many
          4. Implementing the Easy Creation Function
        9. Creating a Cabal Package
          1. Dealing with Different Build Setups
          2. Compilation Options and Interfacing to C
        10. Testing with QuickCheck
          1. Polymorphic Testing
          2. Writing Arbitrary Instances for ByteStrings
          3. Are Suggested Sizes Correct?
        11. Performance Analysis and Tuning
          1. Profile-Driven Performance Tuning
      30. 27. Sockets and Syslog
        1. Basic Networking
        2. Communicating with UDP
          1. UDP Client Example: syslog
          2. UDP Syslog Server
        3. Communicating with TCP
          1. Handling Multiple TCP Streams
          2. TCP Syslog Server
          3. TCP Syslog Client
      31. 28. Software Transactional Memory
        1. The Basics
        2. Some Simple Examples
        3. STM and Safety
        4. Retrying a Transaction
          1. What Happens When We Retry?
        5. Choosing Between Alternatives
          1. Using Higher Order Code with Transactions
        6. I/O and STM
        7. Communication Between Threads
        8. A Concurrent Web Link Checker
          1. Checking a Link
          2. Worker Threads
          3. Finding Links
          4. Command-Line Parsing
          5. Pattern Guards
        9. Practical Aspects of STM
          1. Getting Comfortable with Giving Up Control
          2. Using Invariants
      32. A. Installing GHC and Haskell Libraries
        1. Installing GHC
          1. Windows
          2. Mac OS X
            1. Alternatives
          3. Ubuntu and Debian Linux
          4. Fedora Linux
          5. FreeBSD
        2. Installing Haskell Software
          1. Automated Download and Installation with cabal
            1. Installing cabal
            2. Updating cabal’s package list
            3. Installing a library or program
          2. Building Packages by Hand
      33. B. Characters, Strings, and Escaping Rules
        1. Writing Character and String Literals
        2. International Language Support
        3. Escaping Text
          1. Single-Character Escape Codes
          2. Multiline String Literals
          3. ASCII Control Codes
          4. Control-with-Character Escapes
          5. Numeric Escapes
          6. The Zero-Width Escape Sequence
      34. Index
      35. About the Authors
      36. Colophon
      37. SPECIAL OFFER: Upgrade this ebook with O’Reilly