Book Image

Haskell Cookbook

Book Image

Haskell Cookbook

Overview of this book

Haskell is a purely functional language that has the great ability to develop large and difficult, but easily maintainable software. Haskell Cookbook provides recipes that start by illustrating the principles of functional programming in Haskell, and then gradually build up your expertise in creating industrial-strength programs to accomplish any goal. The book covers topics such as Functors, Applicatives, Monads, and Transformers. You will learn various ways to handle state in your application and explore advanced topics such as Generalized Algebraic Data Types, higher kind types, existential types, and type families. The book will discuss the association of lenses with type classes such as Functor, Foldable, and Traversable to help you manage deep data structures. With the help of the wide selection of examples in this book, you will be able to upgrade your Haskell programming skills and develop scalable software idiomatically.
Table of Contents (13 chapters)

Working with folds

In this recipe, we will look at two of the most important high-order functions, called foldr and foldl. These functions carry out the following activities:

  • Abstract iterative process over a collection such as a list
  • Give a way to work with each of the elements within the collection
  • Give a way to summarize elements and combine them with user-supplied values

Depending on the way elements are combined, the functions are called foldr (fold right) or foldl (fold left). Many higher order functions such as map or filter can be expressed in terms of foldr or foldl.

In this recipe, we will write sum and product functions to calculate the sum and product of numbers in the input list respectively. We will also use folds to implement map and filter.

Getting ready

...