Book Image

Soar with Haskell

By : Tom Schrijvers
Book Image

Soar with Haskell

By: Tom Schrijvers

Overview of this book

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.
Table of Contents (23 chapters)
Free Chapter
1
Part 1:Basic Functional Programming
6
Part 2: Haskell-Specific Features
11
Part 3: Functional Design Patterns
16
Part 4: Practical Programming

Recursive datatypes

While the list type is predefined, we can also define our own recursive algebraic datatypes.

Arithmetic expressions

The Expr datatype is a symbolic representation of arithmetic expressions:

data Expr = Lit Int | Add Expr Expr

The recursive datatype Expr has two constructors:

  • The first, Lit, is the base case; it represents a trivial expression that is just an Int constant (aka literal)
  • The second constructor, Add, is a recursive case; an addition is built out of two smaller expressions (also called subexpressions)

For example, we symbolically represent 2 + 5 as Add (Lit 2) (Lit 5).

Of course, a symbolic expression is just data; it does not compute. To actually evaluate expressions, we need to write an evaluation function:

eval :: Expr -> Int
eval (Lit n)     = n
eval (Add e1 e2) = eval e1 + eval e2

This function has a base case that returns the Int value of the literal and a recursive case for Add...