Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Soar with Haskell
Soar with Haskell

Soar with Haskell: The ultimate beginners' guide to mastering functional programming from the ground up

eBook
$9.99 $36.99
Paperback
$35.99 $45.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Soar with Haskell

Functions

While FP has been around for many decades, its following has only been growing rapidly in recent years. More programmers are picking up functional programming languages or are programming in a functional style in non-functional languages than ever before. At the same time, existing non-functional programming languages are adopting a growing number of FP features and libraries.

In these ongoing developments, Haskell stands out as a reference for all. As a purely FP language, it embodies the ideal of FP. As a trailblazer for new (functional) programming language developments, it sets the bar for other languages to follow in its tracks.

Before diving into practical FP, this chapter gives a brief overview of what FP is and how Haskell fits in. Then, we start with our first Haskell functions. We learn how to define and call functions. This includes an explanation of all the syntactic elements (types, type signature, function body, and so on) and their role. Along the way...

Technical requirements

From the Writing basic functions section onward, you will need a working Haskell environment: the Glasgow Haskell Compiler (GHC) and a code editor (e.g., Visual Studio). We refer to the Haskell website (in particular, the page at https://www.haskell.org/get-started/) for directions on how to set up this environment. The main installer for GHC can be found at https://www.haskell.org/ghcup/.

The code shown in this book can be downloaded from its GitHub repository: https://github.com/PacktPublishing/Soar-with-Haskell.

What is FP?

Before diving into practical Haskell programming, we give a brief overview of FP, its history, and its applications. If you are eager to get your hands dirty, you may want to forge ahead to the next section, then return here at a later occasion when you are ready to put Haskell into context.

Programming with functions

Functional programming (FP) is one of the main programming paradigms next to imperative programming and object-oriented programming.

Declarative programming

What sets FP apart from the other two is that it is a member of the declarative programming family. Sometimes, the principle of declarative programming is summarized by saying that declarative programs state what should happen, not how it should happen. This means that its programs do not explicitly determine the order in which computation steps are executed; it is up to the language implementation. Haskell particularly stands out among other FP languages because it embraces the declarative...

Writing basic functions

In this section, we write our first Haskell functions to get acquainted with Haskell’s syntax and basic elements.

Our first function

Let us start with a simple function for incrementing an integer:

increment :: Int -> Int
increment x = x + 1

This function definition consists of two lines. The first line is the type signature and the second line defines the behavior of the function. 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. Here, Int is of course the type of integers such as -1, 0, and 42.

The second line is an equation that says that increment x (where x is any possible input) is equal to x + 1. We can read such an equation also operationally: given any x input, the increment function returns the result x + 1. Here, x is called a variable; it acts as a placeholder for an actual input to the function. The result x + 1 is called the...

Programming with primitive types

Haskell comes with several built-in primitive types that are used in most programs.

Int and Integer

We have already used the Int type of integers in several examples. It supports four common arithmetic infix operators:

  • (+)addition
  • (-)subtraction
  • (*)multiplication
  • (^)exponentiation

The (-) operator can also be used as a prefix operator to negate a number. Besides these operators, two useful arithmetic functions are as follows:

  1. divinteger division
  2. modmodulo

A common beginner mistake is to use the (/) operator for Int, but it is only defined for floating-point types such as Float and Double.

The Int type only covers a finite range of integers. The Haskell language specification guarantees that this covers at least the integers in the range from -229 to (229-1), but the actual range can be implementation dependent. For example, in GHC 8.10.2...

Putting the type checker to work

Types are very important in Haskell. It is, after all, a statically typed language. This means that programs are (type-)checked before they are run, by a process called the type checker. If the type checker finds that the program violates the typing discipline imposed by the language, then it raises a (type) error and the program will not be executed.

The type checker helps in several ways during the programming process.

Checking function calls

Firstly, when calling a function, it checks that we pass parameters of the appropriate type to that function. For instance, recall that discount has the Int -> Float type:

*Main> discount True
<interactive>:44:10: error:
    • Couldn't match expected type 'Int' with actual type 'Bool'
    • In the first argument of 'discount', namely 'True'
      In the expression...

Combining functions

You can write larger Haskell programs by composing simple functions into more complex ones.

Calling functions from within functions

Functions are composed simply by defining a more complex function in terms of simpler functions. This means that the definition of the complex function calls other functions.

For example, let us write a function to compute the price of a purchase given the price of the purchased item and the quantity at which it is purchased:

price :: Float -> Int -> Float
price ip qty = ip * fromIntegral qty

This is already an example of the principle that a more complex function, price, calls simpler functions. In this case, the simpler functions are two predefined functions: the (*) operator and the fromIntegral function. Recall that the fromIntegral conversion is needed to convert the Int quantity to a Float type before it can be multiplied by the item price.

When our business logic evolves, we can introduce a discounted price...

Summary

This chapter has given us a brief introduction to FP and Haskell. We have written our first basic Haskell functions, used Haskell’s primitive types, and combined individual functions into larger programs. We have also learned about type checking and how it helps us.

In Chapter 2, Algebraic Datatypes, we will learn how to define our own custom datatypes, how to create values of these types with constructors, and how to take those values apart with pattern matching. We will also familiarize ourselves with a powerful abstraction mechanism for types that is used ubiquitously in Haskell: parametric polymorphism.

Questions

  1. What are the key characteristics of the Haskell language?
  2. What is the purpose of parentheses in Haskell?
  3. What is the difference between the Int and Integer types?
  4. How does the type checker help in the programming process?
  5. What are the different ways in which we can define local functions?

Further reading

  • Haskell 98 Language and Libraries: The Revised Report. Simon Peyton Jones et al. December 2002. https://www.haskell.org/onlinereport/
  • A history of Haskell: being lazy with class. Paul Hudak, John Hughes, Simon L. Peyton Jones, Philip Wadler. HOPL 2007: 1-55.

Answers

  1. Haskell is a lazy, purely FP language that is both principled and nimble.
  2. Parentheses are used for overriding or disambiguating the precedence of function and operator applications.
  3. Because the Int type uses a fixed-size representation, it has a bounded range and wraps around when going beyond that range. In contrast, because the size of an Integer value is not fixed, it can be arbitrarily large.
  4. The type checker makes sure that function definitions conform to their type signature and that function calls likewise respect that type signature. It also disambiguates overloaded functions and operators, and can automatically infer type signatures when none are given.
  5. Haskell provides two different syntaxes for this. With letin…, we can define a local function anywhere in an expression. In contrast, a where clause can define a function local to an equation.
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Learn from an expert lecturer and researcher who knows all the ins and outs of Haskell
  • Develop a clear understanding of Haskell, from the basics through to advanced concepts
  • Get to grips with all the key functional programming techniques
  • Purchase of the print or Kindle book includes a free PDF eBook

Description

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.

Who is this book for?

If you are a programmer looking to gain knowledge of Haskell who’s never been properly introduced to functional programming, this book is for you. Basic experience with programming in a non-functional language is a prerequisite. This book also serves as an excellent guide for programmers with limited exposure to Haskell who want to deepen their understanding and foray further into the language.

What you will learn

  • Write pure functions in all their forms – that is basic, recursive, and higher-order functions
  • Model your data using algebraic datatypes
  • Master Haskell's powerful type-class mechanism for ad hoc overloading
  • Find out how Haskell's laziness gets the job done
  • Reconcile Haskell's functional purity with side effects
  • Familiarize yourself with the functor, applicative functor, monad hierarchy
  • Discover how to solve problems with domain-specific languages
  • Find more bugs with Haskell's property-based testing approach

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 22, 2023
Length: 418 pages
Edition : 1st
Language : English
ISBN-13 : 9781805122562
Category :
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Dec 22, 2023
Length: 418 pages
Edition : 1st
Language : English
ISBN-13 : 9781805122562
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 117.97 127.97 10.00 saved
Software Testing Strategies
$41.99
Soar with Haskell
$35.99 $45.99
Causal Inference and Discovery in Python
$39.99
Total $ 117.97 127.97 10.00 saved Stars icon
Banner background image

Table of Contents

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

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.8
(4 Ratings)
5 star 75%
4 star 25%
3 star 0%
2 star 0%
1 star 0%
Balaji Kothandaraman Feb 25, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
“Soar with Haskell” by Tom is a concise yet comprehensive guide that propels readers into the world of Haskell programming. Through clear explanations and practical examples, Tom demystifies Haskell’s concepts, making them accessible to beginners while offering insights for experienced developers. This book serves as an invaluable resource for anyone looking to soar to new heights in functional programming with Haskell.
Amazon Verified review Amazon
Jacob Quam Feb 19, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is a comprehensive and thoughtfully crafted guide to Haskell and functional programming (FP) that stands as an essential resource for both beginners and experienced programmers alike. From the foundational concepts of FP and Haskell's syntax to advanced topics like type classes, monads, and domain-specific languages, the book covers a wide array of subjects necessary for mastering Haskell and functional programming paradigms.The structure of the book is meticulously organized, starting with the basics of functional programming, such as writing basic functions, understanding primitive types, and leveraging the type checker for more robust code. This foundational knowledge is crucial for anyone new to FP and sets the stage for more complex topics.The chapters on algebraic data types, higher-order functions, and recursion are particularly illuminative, offering clear explanations and practical examples that demonstrate the power and elegance of Haskell. The discussion on type classes and monads—topics often considered challenging for newcomers—is handled with care, making these concepts accessible and understandable.One of the book's strengths is its emphasis on practical application, as seen in the sections on input/output, property-based testing, and parser combinators. These chapters not only deepen the reader's understanding of Haskell's capabilities but also equip them with the tools to tackle real-world programming challenges.Moreover, the exploration of Haskell-specific features, such as lazy evaluation and monad transformers, showcases the unique advantages of Haskell and functional programming. These advanced topics are presented in a way that builds on the reader's existing knowledge, ensuring a deeper and more integrated understanding of the material.The inclusion of questions, further reading suggestions, and answers at the end of each chapter reinforces learning and encourages further exploration. Additionally, the book's approach to teaching Haskell through a combination of theoretical explanations and practical examples makes it an invaluable resource for anyone looking to learn or deepen their understanding of Haskell and functional programming.In summary, this book is a testament to the depth and breadth of Haskell as a programming language. Its clear explanations, practical examples, and thoughtful organization make it an indispensable guide for anyone interested in mastering Haskell and functional programming. Whether you're a beginner eager to learn Haskell from the ground up or an experienced programmer looking to deepen your understanding of functional programming concepts, this book is a valuable addition to your programming library.
Amazon Verified review Amazon
Giri Prasath Jan 31, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is shows the world to functional programming. It has cover in depth to haskellIt is a great book for haskell enthusiast's.
Amazon Verified review Amazon
tushar Jan 28, 2024
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
This book stands out for its conciseness and direct approach. It assumes a foundational understanding of imperative or object-oriented programming languages, allowing it to dive straight into the intricacies of Haskell without unnecessary repetition. The pacing is well-balanced, offering a comfortable learning curve without feeling rushed or overly slow.One notable strength is the book's coverage of the features in the latest GHC-9 compiler version, a detail often lacking in other resources. This up-to-date content adds significant value for readers aiming to stay current with Haskell development.The only drawback I encountered was the relatively limited number of problems at the end of each chapter. Despite this minor concern, the overall quality of the book makes it a worthwhile investment for anyone looking to make a smooth transition from imperative to functional programming.In summary, this book provides an excellent bridge for programmers familiar with imperative paradigms, offering a clear path into the fascinating world of Haskell."
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.