45,59 €
Save time and build fast, functional, and concurrent application using Haskell
This book is targeted at readers who wish to learn the Haskell language. If you are a beginner, Haskell Cookbook will get you started. If you are experienced, it will expand your knowledge base. A basic knowledge of programming will be helpful.
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.
The book follows a recipe-based approach. Each recipe addresses specific problems and issues. The recipes provide discussions and insights to explain these problems.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 393
Veröffentlichungsjahr: 2017
BIRMINGHAM - MUMBAI
Copyright © 2017 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, and its dealers and distributors will be held liable for any damages caused or alleged to be 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.
First published: September 2017
Production reference: 1210917
ISBN 978-1-78646-135-3
www.packtpub.com
Author
Yogesh Sajanikar
Copy Editor
Karuna Narayanan
Reviewer
Fabian Linzberger
Project Coordinator
Prajakta Naik
Commissioning Editor
Aaron Lazar
Proofreader
Safis Editing
Acquisition Editor
Karan Sadawana
Indexer
Francy Puthiry
ContentDevelopmentEditor
Siddhi Chavan
Graphics
Abhinash Sahu
Technical Editor
Supriya Thabe
Production Coordinator
Nilesh Mohite
Yogesh Sajanikar has received his bachelor's degree in Mechanical Engineering from Shivaji University, India, along with a gold medal and a master's degree in Production Engineering from the Indian Institute of Technology, Bombay, India.
Yogesh has an experience of more than 20 years, and he has extensively worked with Product Lifecycle Management (PLM) and Computer Aided Design (CAD) software development firms, and architected solutions for domains such as Construction and Shipping Domain.
Having hooked on to functional programming, he moved into the Finance domain and worked as an enterprise architect; he has also worked with Scala/F# and Haskell. Currently, he is working as a CTO for a startup. He has also started local Haskell meetups and has been an active participant in meetups and functional conferences.
Yogesh believes in the open source movement, and believes in giving back to the open source community.
Fabian Linzberger is a functional programming enthusiast and practitioner. He discovered Haskell in 2010 and it has been his favorite programming language ever since. You can find some of his code (some of it in Haskell) on GitHub (https://github.com/lefant/) or visit his personal homepage and check out his blog (https://e.lefant.net/).
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review. If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Preface
What this book covers
What you need for this book
Who this book is for
Sections
Getting ready
How to do it…
How it works…
There's more…
See also
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
Foundations of Haskell
Introduction
Getting started with Haskell
How to do it...
How it works…
Dissecting Hello World
There's more…
Working with data types
How to do it…
How it works...
There's more…
Working with pure functions and user-defined data types
Getting ready
How to do it...
How it works...
Source formatting
Working with list functions
Getting ready
How to do it...
How it works...
List creation
Enumerated list
Head and tail of a list
Operations on a list
Indexed access
Checking whether an element is present
Pattern matching on list
List concatenation
Strings are lists
There's more…
Getting Functional
Introduction
Working with recursive functions
Getting ready
How to do it...
How it works...
There's more...
Reversing a list - Recursive worker function pattern
Getting ready
How to do it...
How it works...
There's more...
Creating maps and filters
Getting ready
How to do it...
How it works...
Map function
Filter function
There's more...
Working with laziness and recursion
Getting ready
How to do it...
How it works...
Working with folds
Getting ready
How to do it...
How it works...
There's more...
Sorting a list
Getting ready
How to do it...
How it works...
There's more...
Implementing merge sort
Getting ready
How to do it...
How it works...
Implementing Eratosthenes Sieve
Getting ready
How to do it...
How it works...
There's more...
Defining Data
Introduction
Defining a product type
Getting ready
How to do it...
How it works...
Defining a sum type
Getting ready
How to do it...
How it works...
Defining a binary tree and traversing it
Getting ready
How to do it...
How it works...
Defining data with functions
Getting ready
How to do it...
How it works...
Using Maybe
Getting ready
How to do it...
How it works...
Using Either
Getting ready
How to do it...
How it works...
Working with type classes
Getting ready
How to do it...
How it works...
Working with Monoid
Getting ready
How to do it...
How it works...
Working with Functors, Applicatives, and Monads
Introduction
Working with Functors
How to do it...
How it works...
Binary tree as Functor
How to do it...
How it works...
Working with Applicatives
How to do it...
How it works...
Binary tree as Applicative
How to do it...
How it works...
Working with monad
How to do it...
How it works...
There's more...
List as monad
How to do it...
How it works...
Working with IO monad
How to do it...
How it works...
Writing INI parser
How to do it...
How it works...
Errors and exception handling
How to do it...
How it works...
More about Monads
Introduction
Writing a State Monad
How to do it...
How it works...
Computing a fibonacci number with State Monad
How to do it...
How it works...
Writing a State Monad transformer
How to do it...
How it works...
Working with the Reader monad transformer
How to do it...
How it works...
Working with the Writer monad transformer
Getting ready
How to do it...
How it works...
Combining monad transformers
How to do it...
How it works...
Working with Common Containers and Strings
Introduction
Working with sets
How to do it...
How it works...
Shopping cart as a set
How to do it...
How it works...
Working with maps
How to do it...
How it works...
Log analysis with map
How to do it...
How it works...
Working with vector
How to do it...
How it works...
Working with text and bytestring
How to do it...
How it works...
Creating and testing a priority queue
Getting ready
How to do it...
How it works...
Working with Foldable and Traversable
How to do it...
How it works...
Working with Relational and NoSQL Databases
Introduction
Working with Persistent
How to do it...
How it works...
Managing migrations
How to do it...
How it works...
Creating custom data types
How to do it...
How it works...
Using Esqueleto to do advanced SQL queries
How to do it...
How it works...
Using hedis to work with redis (key-value, list and hash)
Getting ready...
How to do it...
How it works...
Using hashsets and sorted sets in redis to create a Trie
Getting ready
How to do it...
How it works...
Working with HTML and Templates
Introduction
Using blaze to create an HTML template
How to do it...
How it works...
Using blaze to reverse engineer an HTML page
How to do it...
How it works...
Use blaze-html with Bootstrap to create HTML template
How to do it...
How it works...
Using heist as a template engine
How to do it...
How it works...
Working with splice in Heist
How to do it...
How it works...
Working with Snap Framework
Introduction
Getting started with Snap
How to do it...
How it works...
Routing in Snap
How to do it...
How it works...
Serving static contents in Snap
How to do it...
How it works...
Form handling in Snap
How to do it...
How it works...
Creating and composing snaplets
How to do it...
How it works...
Session handling in Snap
How to do it...
How it works...
Authentication in Snap
How to do it...
How it works...
File upload with Snap
How to do it...
How it works...
Working with Advanced Haskell
Introduction
Working with existentially quantified type
How to do it...
How it works...
Working with Rank-N type
How to do it...
How it works...
Working with type family
How to do it...
How it works...
Working with GADTs
How to do it...
How it works...
Working with Lens and Prism
Introduction
Creating lenses
How to do it...
How it works...
Working with lenses
How to do it...
How it works...
Working with Traversal
How to do it...
How it works...
Working with Iso
How to do it...
How it works...
Working with Prism
How to do it...
How it works...
Working with predefined lenses
Getting ready
How to do it...
How it works...
Concurrent and Distributed Programming in Haskell
Introduction
Working with IORef
How to do it...
How it works...
Working with MVar
How to do it...
How it works...
Working with STM
How it works...
How it works...
Working with strategies
How to do it...
How it works...
Working with monad-par
How to do it...
How it works...
Working with Cloud Haskell
Getting ready
How to do it...
How it works...
Using Cloud Haskell to start master and slave nodes
How to do it...
How it works...
Using closure to communicate between nodes
How to do it...
How it works...
Functional programming has been gaining lot of momentum recently. We are seeing different paradigms of functional programming creeping into imperative languages such as C++, C#, and Python. There are languages such as Scala that try to offer best of both worlds, that is, object-oriented programming and functional programming.
As Haskell is a pure and non-strict language, and strictly separates pureness from effect-full computations, it really stands out among these languages. Its strong theoretical basis, such as an elaborate type system, combined with concise and expressive syntax, gives Haskell a unique flavor. It really helps in programming declaratively by specifying what rather than how! In this book, we will focus on practical aspects of the language.Haskell Cookbook is meant for programmers who have a programming background. Most of the readers should be acquainted with an imperative language, such as Java/Python or C++.
This cookbook can be logically divided into two parts, the first five chapters serve as building blocks for programming in Haskell. These chapters cover syntactical and semantic details of the language by describing how to use and define functions and data types. In these chapters, we also cover type classes and the Functor, Applicative, and Monads concepts. The last seven chapters will introduce you to the practical aspects of usage of Haskell and its rich set of libraries. These chapters will take you through containers in Haskell and backend development (developing with database) to frontend development (web framework). The last three chapters focus on advanced concepts, such as doing parallel and distributed programming in Haskell.
Each recipe is self-sufficient, and, wherever possible, the recipe will try to build a concept (such as Monad) from scratch, before moving on to a recipe that will use the concept from the existing library. This is especially true in the first five chapters. Use this book to dive into Haskell and Functional Programming in general. Start building small toy programs by using recipes, and move on to bigger programs to create your own web application or a distributed system. Even if you are not planning to use Haskell in your day-to-day work, I can assure you that it will change the way you look at programming, even when programming with other languages.
This book is not possible without encouragements from my family and the constant pursuance and perseverance of the staff at Packt. These people believed in me even when I was delayed or transgressed.
Chapter 1, Foundations of Haskell, introduces you to Haskell and helps you setup the environment for Haskell using the stack as a tool. In this chapter, you will write your first Haskell program, and then analyze its parts.
Chapter 2, Getting Functional, warms you up to Haskell by introducing recursion, maps, filters, and folds. It ends up by implementing a prime sieve.
Chapter 3, Defining Data, explores the rich data types that Haskell provides. You will be exposed to product and sum types. This chapter further introduces standard type classes in Haskell.
Chapter 4, Working with Functors, Applicatives, and Monads, dives deeper into Haskell by exploring the rich type classes and their instances. The recipes in this chapter allow the reader to build their own monad, and introduces IO monad.
Chapter 5, More about Monads, builds on the previous chapter by further creating and using monad transformers, and finally building a parser with Attoparsec.
Chapter 6, Working with Common Containers and Strings, looks at common containers and introduces Foldable and Traversals. In this chapter, you will also cook your own container and test it using Quickcheck. This chapter also looks at an alternate representation of String, that is, Text and ByteString.
Chapter 7, Working with Relational and NoSQL Databases, uses the Haskell based model declaration template and queries using persistent library. We will also use redis to work with NoSQL databases.
Chapter 8, Working with HTML and Templates, works with the Heist template framework along with the Blaze HTML library to create composable HTML documents.
Chapter 9, Working with Snap Framework, explores various web application development aspects, such as routing, templating, authentication, and sessions using the Snap Framework.
Chapter 10, Working with Advanced Haskell, introduces you to advanced concepts such as Existentially Quantified Type, Rank-N-Type, type family, and GADT.
Chapter 11, Working with Lens and Prism, explores the lens library to look at the concept of Lens and Prism. This chapter explains the concept of lens by building one itself. The rest of the chapter explains rich features of the Lens library.
Chapter 12, Concurrent and Distributed Programming in Haskell, introduces the building blocks of concurrent programming, such as IORef, MVar, and STM. The later part introduces Cloud Haskell to create distributed applications.
You will need a fairly recent operating system, such as Windows, Linux, or Mac OS.
You should set up the stack tool from
https://www.haskellstack.org/
. Use the Stack setup to download GHC (Haskell Compiler) on your machine. Stack is an extremely useful tool to work with different versions of GHC and packages.
You will need a good editor. Vi and Emacs have very good support for Haskell. Eclipse and Sublime also have support for Haskell.
This book is targeted at readers who wish to learn the Haskell language. If you are a beginner, Haskell Cookbook will get you started. If you are experienced, it will expand your knowledge base. A basic knowledge of programming will be helpful.
In this book, you will find several headings that appear frequently (Getting ready, How to do it, How it works, There's more, and See also).
To give clear instructions on how to complete a recipe, we use these sections as follows:
This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.
This section contains the steps required to follow the recipe.
This section usually consists of a detailed explanation of what happened in the previous section.
This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.
This section provides helpful links to other useful information for the recipe.
Feedback from our readers is always welcome. Let us know what you think about this book--what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the
SUPPORT
tab at the top.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on
Code Download
.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/HaskellCookbook. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books--maybe a mistake in the text or the code--we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at [email protected] with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
In this chapter, we will cover the following recipes:
Getting started with Haskell
Working with data types
Working with pure functions and user-defined data types
Working with list functions
In this recipe, we will work with Glasgow Haskell Compiler (GHC) and its interpreter GHCi. Then, we will write our first Haskell program and run it in the interpreter.
This recipe demonstrated the usage of Stack to create a new project, build it, set up the corresponding GHC version, build the project, and run it. The recipe also demonstrated the use of the Haskell command prompt, aka GHCi, to load and edit the file. GHCi also allows us to run the program in the command prompt.
The recipe also shows the familiar Hello World! program and how to write it. The program can be interpreted in the following way.
If you visit the Stack website at https://www.stackage.org/, you will notice that Stack publishes nightly packages and Long Term Support (LTS) packages. While creating a new project, Stack downloads the latest LTS package list. It is also possible to provide the name of the LTS package explicitly by providing stack new –resolver lts-9.2.
In the project directory, you will notice two files:
<project>.yaml
<project>.cabal
The YAML file is created by Stack to specify various things, including LTS version, external packages, and so on. The .cabal file is the main project file for the Haskell package. The cabal is the tool that Stack uses internally to build, package, and so on. However, there are several advantages of using Stack as Stack also supports pre-built packages and manages cabal well. Furthermore, Stack also supports the Docker environment.
In this recipe, we will work with basic data types in Haskell. We will also define our own data types.
We have seen four basic types Int, Double, Char, and Float. More information about these types is given in the following table:
Type
Description
Remarks
Int
Fixed precision integer type
Range [-9223372036854775808 to
9223372036854775807] for 64-bit Int.
Float
Single precision (
32
-bit) floating point number
Double
Double precision (
64
-bit) floating point number
Char
Character
Bool
Boolean values
True
or
False
In previous sections of this recipe, when we ran the command :info Bool, at GHCi prompt, Haskell also showed various instances of information. It shows more about the behavior of the type. For example, instance Eq Bool means that the type Bool is an instance of some type class Eq. In Haskell, type class should be read as a type that is associated with some behavior (or function). Here, the Eq type class is used in Haskell for showing equality.
You can get more information about type classes by exploring :info Eq. GHCi will tell you which types have instances of the Eq type class. GHCi will also tell you which are the methods defined for Eq.
In this recipe, we will work with pure functions and define simple user-defined data types. We will represent a quadratic equation and its solution using user-defined data types. We will then define pure functions to find a solution to the quadratic equation.
Create a new project
quadratic
using the following command:
stack new quadratic
Change into the project folder.
Delete
src/Lib.hs
and create a new file
src/Quadratic.hs
to represent the quadratic equation and its solution.
Open the
quadratic.cabal
file, and in the section library, replace
Lib
by
Quadratic
in the tag
exposed-modules
:
library
hs-source-dirs: src
exposed-modules: Quadratic
build-depends: base >= 4.7 && < 5
default-language: Haskell2010
