Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Soar with Haskell

You're reading from  Soar with Haskell

Product type Book
Published in Dec 2023
Publisher Packt
ISBN-13 9781805128458
Pages 418 pages
Edition 1st Edition
Languages
Author (1):
Tom Schrijvers Tom Schrijvers
Profile icon Tom Schrijvers

Table of Contents (23) Chapters

Preface 1. Part 1:Basic Functional Programming
2. Chapter 1: Functions 3. Chapter 2: Algebraic Datatypes 4. Chapter 3: Recursion 5. Chapter 4: Higher-Order Functions 6. Part 2: Haskell-Specific Features
7. Chapter 5: First-Class Functions 8. Chapter 6: Type Classes 9. Chapter 7: Lazy Evaluation 10. Chapter 8: Input/Output 11. Part 3: Functional Design Patterns
12. Chapter 9: Monoids and Foldables 13. Chapter 10: Functors, Applicative Functors, and Traversables 14. Chapter 11: Monads 15. Chapter 12: Monad Transformers 16. Part 4: Practical Programming
17. Chapter 13: Domain-Specific Languages 18. Chapter 14: Parser Combinators 19. Chapter 15: Lenses 20. Chapter 16: Property-Based Testing 21. Index 22. Other Books You May Enjoy

Preface

This book provides an introduction to functional programming in Haskell:

  • Functional Programming (FP) is one of the main programming paradigms, along with imperative programming and object-oriented programming. It uses functions as its core concept of computation – turning input into output in a predictable and context-independent way.While many non-FP languages also offer functions in some form, in FP, language functions truly have first-class status. They are not only computation but also data, which can be ferried around by other (higher-order) functions, dynamically assembled out of simpler functions, stored in data structures, or data containers themselves.
  • Haskell stands out among FP languages in that it unequivocally embraces the FP paradigm. Because it does not make any compromises for imperative programming, Haskell had to come up with entirely new solutions to tackle common programming problems that also turned out to be successful in solving next-level problems. This way, it has become an inspiration for the designers of other programming languages (both FP and non-FP) and libraries in those languages.

Besides being true to the principles of FP, Haskell is also renowned for its sophisticated static type system. This means that Haskell programs are automatically checked for particular kinds of mistakes (known as type errors) before they are run. Moreover, thanks to Haskell’s powerful type inference mechanism, programmers have to write little to no type annotations themselves. Taking all the preceding aspects of FB in Haskell into consideration, the common theme of this book is abstraction. It provides many mechanisms for abstraction and powerful examples of abstractions that allow us to converse and reason about common programming patterns, becoming more effective programmers when we (re)use them.

Who this book is for

This book is for all those who already have some programming experience and want to learn FP in Haskell:

  • If you are familiar with imperative or object-oriented programming, this book introduces you to the wonderful world of FP.
  • If you are already familiar with other FP languages, you will discover the unique Haskell language features, ideas, and programming style.
  • If you have outgrown your current programming language, are ready for a new challenge, or want to fall in love with programming all over again, your journey starts here.

What this book covers

Chapter 1, Functions, explains the core concept of FP – functions. It introduces function definitions and shows how functions are called. This includes an explanation of all the syntactic elements (types, type signature, function body, etc) and their role. Along the way, it also introduces a number of built-in types and functions.

Chapter 2, Algebraic Datatypes, introduces Haskell’s mechanism for user-defined types – Algebraic Datatypes (ADTs). We build up from simple forms of ADTs such as enumerations and records to their full generality, and we learn the different elements of ADT definitions – the type name, the data constructors, and their fields. We see how ADT values are created and how they are taken apart by pattern matching. Finally, we see how ADTs can be parameterized over other types.

Chapter 3, Recursion, presents the functional programming alternative to loops. Recursive datatypes are a natural mechanism to express data structures of arbitrary size, and recursive functions are the way to process these functions. We will focus in particular on structural recursion as a principled use of recursion but also cover alternative recursion patterns.

Chapter 4, Higher-Order Functions, explains how repeated patterns in function definitions can be abstracted over, notably by abstracting over higher-order parameters. Special attention goes to commonly used higher-order library functions such as map, filter, foldr, and foldl.

Chapter 5, First-Class Functions, covers a range of language features and mechanisms that facilitate function-oriented programming, where we program at the level of functions rather than plain values.

Chapter 6, Type Classes, presents Haskell’s unique mechanism for supporting ad-hoc overloading–type classes. It explains what ad-hoc overloading is and how functions give rise to polymorphic type signatures with type class constraints. Then, we will see how predefined type classes can be instantiated for user-defined types and how new user-defined type classes can be created. Finally, we cover several user-defined type classes and their use in standard libraries.

Chapter 7, Lazy Evaluation, reveals Haskell’s unique evaluation mechanism – lazy evaluation. It shows how lazy evaluation works and improves upon both call-by-value and call-by-name. Then, it shows how to use the strategy to your advantage by using lists as iterators that supply their elements on demand. Finally, the chapter also points out a pitfall of the mechanism – the build-up of thunks.

Chapter 8, Input/Output, explains Haskell’s unique way of interfacing with the outside world – its I/O mechanism. First, the chapter explains why the existing approach of other languages is problematic due to the lazy evaluation strategy and the language’s purity principle. Then, it presents the Haskell solution using the I/O type and >>=/return operators. Then, it introduces the do notation as a more user-friendly notation for I/O steps. Finally, it covers common I/O operations.

Chapter 9, Monoids and Foldables, introduces the notion of foldables. These are collections that support a similar range of frequently used operations. Along the way, we learn that Haskell has a mechanism to abstract over parts of types, called type constructors, and uses algebraic concepts such as semigroups and monoids to design highly general algorithms.

Chapter 10, Functors, Applicative Functors, and Traversables, leads us further into the hierarchy of type classes for type constructors. We will first consider functors – data structures that can be mapped over. Then, we will move on to applicative functors, which can merge multiple data structures, and finally, we will see traversables as data structures that can be mapped over with side effects.

Chapter 11, Monads, introduces the king of the type constructor hierarchy – monads. We will first cover two well-known examples of monads – the maybe monad for failure and the state monad for state passing. Then, we will generalize from these examples and present the Monad- type class. Finally, we will present a number of additional examples of monads.

Chapter 12, Monad Transformers, shows how the functionality of different monads can be combined into a single monad. The chapter covers the monad transformer mechanism and gives a range of commonly used instances. Then, it shows how applications can abstract over the implementation details of monads and monad transformers, with monad subclasses. Finally, we will see how the same monad transformers can be combined in different ways to achieve different behavior.

Chapter 13, Domain-Specific Languages, documents a powerful problem-solving technique that is appropriate when a range of problems have to be solved within the same problem area – domain-specific languages (DSLs) embedded in Haskell. First, we will see several examples of DSLs that are tailored to different problem areas. Then, we will focus on implementation techniques for DSLs. The most general and flexible approach is deep embedding. It contrasts with shallow embedding, which is a more lightweight and efficient technique.

Chapter 14, Parser Combinators, introduces parser combinators, a lightweight and convenient DSL in Haskell for parsing. It covers what parsing is and where it is used. Then, we will see a basic definition of parser combinators to get a good idea of how they work. From there, we will move on to the industrial-strength Parsec library. Finally, we see how to tackle common parsing problems with parser combinators.

Chapter 15, Lenses, presents an exciting approach to the mundane activity of data access in nested datatypes. First, it demonstrates the basic approach for records that is built into Haskell and identifies its disadvantages. Then, it presents the concept of lenses as a much more convenient alternative for both reading and updating fields. We will show that lenses not only compose trivially to reach deep into data structures but also can be used to seamlessly define virtual fields. Finally, we cover the main lens combinators provided by the well-known lens library.

Chapter 16, Property-Based Testing, covers property-based testing, the powerful testing technique pioneered by Haskell’s QuickCheck library. It explains the advantages of property-based testing over unit testing. Then, it shows how to write properties and examine test outcomes. Then, it shows you how to test your own ADTs by writing generators for them. Finally, shrinking is used to drill counterexamples down to their essence.

To get the most out of this book

Refer to the Haskell website – in particular, the page at https://www.haskell.org/get-started/ – for directions on how to set up your Haskell environment environment. The main installer for GHC can be found at https://www.haskell.org/ghcup/.

Software/hardware covered in the book

Operating system requirements

Glasgow Haskell Compiler (GHC)

Windows, macOS, or Linux

If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

Download the example code files

You can download the example code files for this book from https://github.com/PacktPublishing/Soar-with-Haskell. If there’s an update to the code, it will be updated in the GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “The type signature states that the function has the name increment and, given a value of the Int type as input, produces a result of the Int type.”

A block of code is set as follows:

redSuits :: [Suit]
redSuits = Hearts : Diamonds : []

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

data Expr = Lit Int | Add Expr Expr

Any function call is written as follows:

*Main> renderExpr (Add (Lit 2) (Lit 5))
“2+5”

Bold: Indicates a new term, an important word, or words that you see on screen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “What sets FP apart from the other two is that it is a member of the declarative programming family.”

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, email us at customercare@packtpub.com and mention the book title in the subject of your message.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at copyright@packt.com with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com

Share Your Thoughts

Once you’ve read Soar with Haskell, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere? Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

Follow these simple steps to get the benefits:

  1. Scan the QR code or visit the link below
Download a free PDF copy of this book

https://packt.link/free-ebook/9781805128458

  1. Submit your proof of purchase
  2. That’s it! We’ll send your free PDF and other benefits to your email directly

.

lock icon The rest of the chapter is locked
Next Chapter arrow right
You have been reading a chapter from
Soar with Haskell
Published in: Dec 2023 Publisher: Packt ISBN-13: 9781805128458
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime}