Soar with Haskell - Tom Schrijvers - E-Book

Soar with Haskell E-Book

Tom Schrijvers

0,0
29,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

With software systems reaching new levels of complexity and programmers aiming for the highest productivity levels, software developers and language designers are turning toward functional programming because of its powerful and mature abstraction mechanisms. This book will help you tap into this approach with Haskell, the programming language that has been leading the way in pure functional programming for over three decades.
The book begins by helping you get to grips with basic functions and algebraic datatypes, and gradually adds abstraction mechanisms and other powerful language features. Next, you’ll explore recursion, formulate higher-order functions as reusable templates, and get the job done with laziness. As you advance, you’ll learn how Haskell reconciliates its purity with the practical need for side effects and comes out stronger with a rich hierarchy of abstractions, such as functors, applicative functors, and monads. Finally, you’ll understand how all these elements are combined in the design and implementation of custom domain-specific languages for tackling practical problems such as parsing, as well as the revolutionary functional technique of property-based testing.
By the end of this book, you’ll have mastered the key concepts of functional programming and be able to develop idiomatic Haskell solutions.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 584

Veröffentlichungsjahr: 2023

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Soar with Haskell

The ultimate beginners’ guide to mastering functional programming from the ground up

Tom Schrijvers

BIRMINGHAM—MUMBAI

Soar with Haskell

Copyright © 2023 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Kunal Sawant

Publishing Product Manager: Teny Thomas

Book Project Manager: Manisha Singh

Senior Editor: Nisha Cleetus

Technical Editor: Jubit Pincy

Copy Editor: Safis Editing

Proofreader: Safis Editing

Indexer: Hemanigini Bari

Production Designer: Shankar Kalbhor

Business Development Executive: Kriti Sharma

Developer Relations Marketing Executive: Shrinidhi Manoharan

First published: December 2023

Production reference: 1141223

Published by

Packt Publishing Ltd.

Grosvenor House

11 St Paul’s Square

Birmingham

B3 1RB, UK

ISBN 978-1-80512-845-8

www.packtpub.com

To my wife, Annemie, for her enduring support.

– Tom Schrijvers

Contributors

About the author

Tom Schrijvers has been a professor of computer science at KU Leuven in Belgium since 2014, and previously from 2011 until 2014 at Ghent University in Belgium. He has over 20 years of research experience in programming languages and has co-authored more than 100 scientific papers. Much of his research focuses on functional programming and the Haskell programming language in particular; he has made many contributions to the language, its ecosystem, and applications, and chaired academic events such as the Haskell Symposium. At the same time, he has more than a decade of teaching experience (including functional programming with Haskell) and received several teaching awards.

I would like to thank the Haskell community who have created and fostered this amazing language. They have been a major inspiration. Of course, I am grateful to the Packt team who have followed the development of this book every step of the way. Many thanks also to Alexander Granin for his uplifting technical feedback. Finally, I am indebted to my employer, KU Leuven, who granted me a six-month sabbatical leave. That gave me the opportunity to write the first 10 chapters in the welcoming environment of Kellogg College in Oxford.

About the reviewer

Alexander Granin, a functional programming expert, is renowned for his fundamental books Functional Design and Architecture and Pragmatic Type-Level Design. With over 15 years of experience spanning C++, Haskell, C#, and Python, he’s evolved from developer to software architect. As an accomplished international speaker, he delivered many talks on software design and functional programming. Alexander’s methodology, functional declarative design, provides a pragmatic knowledge of design patterns, principles, and best practices, useful for building applications with functional languages. His mission is to empower developers with practical insights and build a comprehensive software engineering discipline for Function Point (FP).

Table of Contents

Preface

Part 1: Basic Functional Programming

1

Functions

Technical requirements

What is FP?

Programming with functions

Brief history of FP

Haskell

Other contemporary FP languages

Prominent application areas

Writing basic functions

Our first function

A two-parameter function

Custom operators

Programming with primitive types

Int and Integer

Float and Double

Booleans

Char and String

Converting between primitive types

Putting the type checker to work

Checking function calls

Checking function definitions

Disambiguating overloaded functions

Inferring types

Combining functions

Calling functions from within functions

Naming intermediate results

Local function definitions

Summary

Questions

Further reading

Answers

2

Algebraic Datatypes

Enumerations

A game of rock-paper-scissors

Don’t-care patterns

Booleans revisited

Records

People

Named fields

Nested records

Full-blown algebraic datatypes

Shapes

Cards

Showing cards

Parametric polymorphism

The identity function

The constant function

Parametric ADTs

Tuples

Type synonyms

Maybe

Either

The unit type

Summary

Questions

Answers

3

Recursion

Standard libraries

Lists

List syntax

List syntax desugared

Predefined list functions

List comprehensions

Strings revisited

Custom list processing

Recursive datatypes

Arithmetic expressions

Parametric recursive datatypes

Structural recursion

Structural recursion on lists

Structural recursion on other algebraic datatypes

Variants on structural recursion

Primitive recursion

Recursion on integers

Additional parameters

Varying parameters and the worker/wrapper structure

Accumulation

Recursion on nested datatypes

Mutual recursion

Simultaneous recursion on multiple structures

Combining variations

Non-structural recursion

Non-termination

Unbounded search

Summary

Questions

Answers

4

Higher-Order Functions

Abstracting over functions

Dropping a prefix

Sorting in ascending and descending order

An abstraction for structural recursion

Folding lists

Folds for other algebraic datatypes

Variations on structural recursion

Common HOFs

Taking instead of dropping

Mapping

Filtering

Any and all

Folding from the left

Scanning left and right

Writing compact code with HOF

Standard deviation

Odds and evens

All you can buy

Summary

Questions

Answers

Part 2: Haskell-Specific Features

5

First-Class Functions

Anonymous functions

Anonymous function syntax

Anonymous function use

Multi-parameter anonymous functions

Pattern matching without equations

Currying and partial application

One parameter is enough

Partial application

Operator sections

Flipping function parameters

Eta reduction

Basic eta reduction

Eta reduction with partial application

Eta reduction of two-parameter functions

Irreducible cases

Function composition

Basic function composition

Pipelines

Functions as data structures

Evaluation with many variables

Association list

Functional environments

Summary

Questions

Answers

6

Type Classes

Ad hoc polymorphism

What is ad hoc polymorphism?

Type classes

Type class constraints are contagious

Type class instances

Type class instantiation

Default implementations and minimal complete definitions

Instances for composite values

Equality of functions

Recursive instances

Deriving structural instances

Semantic equality instances

Lawful instances

Common type classes

Ord

Show

Read

Bounded and Enum

Numeric type classes

Library uses of type classes

List membership functions

The Map library

Custom type class example

Text boxes

Box combinators

Boxable things

Summary

Questions

Further reading

Answers

7

Lazy Evaluation

Evaluation strategies

Beta reduction

Evaluation

Evaluation strategies

Call by Value

Call by Name

Call by Need

Sharing

Thunks

Bottom

Structured data

Programming with lazy evaluation

Streaming

Infinite lists

Corecursive programs

Lazy memory leaks

The leaking accumulator

Strictness annotations

Increased laziness

Summary

Questions

Answers

8

Input/Output

Technical requirements

Haskell versus I/O – a thought experiment

Lazy evaluation versus I/O

Pure functions versus I/O

The IO approach

Describing I/O

Performing I/O

Composing I/O

Mixing I/O and control flow

The do notation

Imperative Style

Common syntax errors

A more flexible layout

Library functions by example

Summing numbers

Guessing game

Summary

Questions

Further reading

Answers

Part 3: Functional Design Patterns

9

Monoids and Foldables

Semigroups and monoids

Semigroups

Monoids

Kinds and type constructors

Proper types

Type constructors

Type constructor parameters

Foldables

The Foldable type class

Listable collections

Aggregation into a monoid

Deriving the Foldable instance

Standard library instances

Case study – Sortedness

Sorted lists

An attempt with structural recursion

A richer approach with structural recursion

The Sortedness monoid

Summary

Questions

Further reading

Answers

10

Functors, Applicative Functors, and Traversables

Functors

The functor laws

Functor instances

Applicative functors

A family of zip functions

The Applicative type class

The applicative law

Applicative functors and effects

Failing computations with Maybe

Erroneous computations with Either

Implicitly parameterized computations with functions

Analyzing computations with the Const functor

Logging computations with tuples

Stateful computations with State

Nondeterministic computations with lists

No effect

Compositions

Traversables

The Traversable class

Instances

The traversable laws

Case study – word count

Summary

Questions

Further reading

Answers

11

Monads

Failing with Maybe

State-passing

The monad type class

Monads vs applicative functors

The monad laws

The do notation

More monads

The Identity monad

The Error (aka Exception) monad

The Reader (aka environment) monad

The Writer monad

The list (aka nondeterminism) monad

Summary

Questions

Answers

12

Monad Transformers

Combining monadic effects

Logging revisited

A custom monad

Changed requirements

Changes to the custom monad

Monad transformers

The Reader transformer

The MonadTrans type class

The Reader monad revisited

Other monad transformers

The StateT and WriterT transformers

The MaybeT and ExceptT transformers

The ListT transformer

Monad subclasses

The MonadReader type class

More Monad subclasses

Monad transformer gotchas

Effect interaction

Multiple copies

Summary

Questions

Further reading

Answers

Part 4: Practical Programming

13

Domain-Specific Languages

A DSL for formatting

Overview

Data format example

A DSL for financial contracts

Compositional contracts

Zero-coupon bonds

Contract combinators

Interpreting contracts

Implementing DSLs

Running example

Deep embedding

Shallow embedding

The best of both worlds

Summary

Questions

Further reading

Answers

14

Parser Combinators

Parsing

What is parsing?

How to get a parser

Parser combinators

A parser for sums

Parsers under the hood

The Parsec library

Different types of parsers

Parsec particulars

Parsing challenges – expressions revisited

Summary

Questions

Further reading

Answers

15

Lenses

Technical requirements

Records and deep access

Lenses and their composition

Basic lenses

Lens composition

Change of representation

Lens operators

Generating boilerplate

Polymorphic lenses

Programmatic data access

Virtual fields

Side effects

Advanced lenses

Getters and setters

Traversals

Prisms

Summary

Questions

Further reading

Answers

16

Property-Based Testing

Unit testing versus property-based testing

Unit testing

Property-based testing

Generators

Arbitrary

Generators

Custom generators

Shrinking

Shrinking in action

User-defined shrinking

Test properties – a case study

System under test

Properties

Shrinking

Summary

Questions

Further reading

Answers

Index

Other Books You May Enjoy

Part 1:Basic Functional Programming

This part introduces you to the Haskell programming language. You will get an overview of the basic functional programming language features. In particular, you will start with the key concepts and functions, expanding into the data processed by functions (algebraic datatypes), the way to write loops with functions (recursion), and functions taking other functions as input (higher-order functions).

This part has the following chapters:

Chapter 1, FunctionsChapter 2, Algebraic DatatypesChapter 3, RecursionChapter 4, Higher-Order Functions