(Ebook) Thinking With Types: Type-Level Programming in Haskell by Sandy Maguireinstall Download
(Ebook) Thinking With Types: Type-Level Programming in Haskell by Sandy Maguireinstall Download
https://ebooknice.com/product/thinking-with-types-type-level-
programming-in-haskell-7427574
https://ebooknice.com/product/thinking-with-type-43890808
ebooknice.com
(Ebook) Get Programming with Haskell by Will Kurt ISBN 9781617293764, 1617293768
https://ebooknice.com/product/get-programming-with-haskell-43035710
ebooknice.com
https://ebooknice.com/product/thinking-functionally-with-haskell-10508692
ebooknice.com
https://ebooknice.com/product/typescript-cookbook-real-world-type-level-
programming-53028982
ebooknice.com
(Ebook) Programming in Haskell by Graham Hutton ISBN 9781316626221, 1316626229
https://ebooknice.com/product/programming-in-haskell-5688130
ebooknice.com
https://ebooknice.com/product/programming-in-haskell-22231412
ebooknice.com
https://ebooknice.com/product/programming-in-haskell-11790552
ebooknice.com
(Ebook) Haskell: The Ultimate Beginner's Guide to Learn Haskell Programming Step by
Step by Claudia Alves
https://ebooknice.com/product/haskell-the-ultimate-beginner-s-guide-to-learn-
haskell-programming-step-by-step-11622862
ebooknice.com
https://ebooknice.com/product/effective-haskell-solving-real-world-problems-
with-strongly-typed-functional-programming-52387858
ebooknice.com
Thin
Thinki
king
ng wi
with
th Ty
Type
pess
Sandy
Sandy Maguire
Maguire
Copy
Copyrig
right
ht ©201
©2018,
8, Sand
Sandyy Magu
Maguire
ire
First
First Edition
Edition
When people say
“but most business logic bugs
aren’t type errors,”
I just want to show them
how to make bugs
into type errors.
MATT PARSONS
Contents
Preface ix
Acknowledgments xi
Introduction 1
I Fundamentals 5
1 The Algebra Behind Types 7
1.1 Isomorphisms and Cardinalities . . . . . . . . . . . . . . . 7
1.2 Sum, Product and Exponential Types . . . . . . . . . . . . 10
1.3 Example: Tic-Tac-Toe . . . . . . . . . . . . . . . . . . . . . 13
1.4 The Curry–Howard Isomorphism . . . . . . . . . . . . . . 15
1.5 Canonical Representations . . . . . . . . . . . . . . . . . . 16
2 Terms, Types and Kinds 19
2.1 The Kind System . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.1.1 The Kind of “Types” . . . . . . . . . . . . . . . . . . 20
2.1.2 Arrow Kinds . . . . . . . . . . . . . . . . . . . . . . . 20
2.1.3 Constraint Kinds . . . . . . . . . . . . . . . . . . . . 21
2.2 Data Kinds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.3 Promotion of Built-In Types . . . . . . . . . . . . . . . . . 25
2.3.1 Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.3.2 Natural Numbers . . . . . . . . . . . . . . . . . . . . 27
2.3.3 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
2.3.4 Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
2.4 Type-Level Functions . . . . . . . . . . . . . . . . . . . . . 30
3 Variance 35
v
vi CONTENTS
II Lifting Restrictions 41
4 Working with Types 43
4.1 Type Scoping . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
4.2 Type Applications . . . . . . . . . . . . . . . . . . . . . . . . 45
4.3 Ambiguous Types and Non-Injectivity . . . . . . . . . . . 47
5 Constraints and GADTs 51
5.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
5.2 GADTs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
5.3 Heterogeneous Lists . . . . . . . . . . . . . . . . . . . . . . 55
6 Rank-N Types 61
6.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
6.2 Ranks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
6.3 The Nitty Gritty Details . . . . . . . . . . . . . . . . . . . . . 65
6.4 The Continuation Monad . . . . . . . . . . . . . . . . . . . 66
7 Existential Types 71
7.1 Existential Types and Eliminators . . . . . . . . . . . . . . 71
7.1.1 Dynamic Types . . . . . . . . . . . . . . . . . . . . . 74
7.1.2 Generalized Constraint Kinded Existentials . . . . 76
7.2 Scoping Information with Existentials . . . . . . . . . . . 79
8 Roles 85
8.1 Coercions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
8.2 Roles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
IV Appendices 203
Glossary 205
Solutions 211
Bibliography 233
About the Author 235
viii CONTENTS
Preface
Thinking with Types started, as so many of my projects do,
accidentally. I was unemployed, bored, and starting to get tired of
answering the same questions over and over again in Haskell
chat-rooms. And so I started a quick document, jotting down a
bunch of type-level programming topics I thought it’d be fun to
write blog posts about.
This document rather quickly turned into an outline of what those
blog posts might look like, but as I was about to tease it apart into
separate files I stopped myself. Why not turn it into a book instead?
I approached some friends to see if anyone was interested in
writing it with me. A few nibbles, but nobody had time they wanted
to dedicate to such a thing. My excitement subsequently burned out,
and the idea lay dormant on the back-burner for a few months.
But I was still unemployed, and I was still bored, and I found
myself slowly fleshing out chapters regardless. My enthusiasm for
writing a book had died down, but I still felt the urge to write. A
friend caught me writing one day, and dared me to publish what I
had. I acquiesced.
And so on July 8th, 2018, I posted a 37 page document to reddit,
gauging if there was any interest from the community in such a book.
To my continual surprise, there was. The response was about 100x
bigger than I was expecting. Kind words and letters of support rolled
in, many of whom promised to pay me in order to continue writing
it.
That was enough for me. I put together a Patreon, started selling
early access to the book, and was o to the races. The promise was
to publish weekly updates, which—combined with not wanting to
commit fraud—kept me extremely motivated to get this book
finished. It’s a powerful technique to stay focused, and I’d strongly
ix
x CONTENTS
xi
xii CONTENTS
Introduction
Type-level programming is an uncommon calling. While most
programmers are concerned with getting more of their code to
compile, we type-level programmers are trying our best to prevent
code from compiling.
Strictly speaking, the job of types is twinfold—they prevent
(wrong) things from compiling, and in doing so, they help guide us
towards more elegant solutions. For example, if there are ten
solutions to a problem, and nine of them be poorly-typed, then we
need not look very hard for the right answer.
But make no mistake—this book is primarily about reducing the
circumstances under which a program compiles. If you’re a beginner
Haskell programmer who feels like GHC argues with you too often,
who often finds type errors inscrutable, then this book is probably
not for you. Not yet.
So whom is this book for? The target audience I’ve been trying to
write for are intermediate-to-proficient with the language. They’re
capable of solving real problems in Haskell, and doing it without too
much hassle. They need not have strong opinions on ExceptT vs
throwing exceptions in IO , nor do they need to know how to inspect
generated Core to find performance bottlenecks.
But the target reader should have a healthy sense of unease
about the programs they write. They should look at their comments
saying “don’t call this function with n = 5 because it will crash,”
and wonder if there’s some way to teach the compiler about that.
The reader should nervously eyeball their calls to error that they’re
convinced can’t possibly happen, but are required to make the
type-checker happy.
In short, the reader should be looking for opportunities to make
less code compile. This is not out of a sense of masochism, anarchy,
1
2 CONTENTS
Fundamentals
5
Chapter 1
1.1
1.1 Is
Isom
omor
orph
phis
isms
ms and
and Ca
Card
rdin
inal
alit
itie
iess
One of functio
functional
nal program
programmin ming’s
g’s killer
killer featur
features
es is pattern
pattern matchin
matching,g,
as made possible by algebraic data types . But this this term
term isn’t
isn’t just
just a
catchy title for things that we can pattern match on. As their name
sugge
uggessts,
ts, ther
theree is in fact
fact an algebra behind algebraic data types.
Being comfortable understanding and manipulating this algebra
is a mighty superpower—it allows us to analyze types, find more
convenient forms for them, and determine which operations (eg.
type
typecla
class
sses
es)) are
are poss
possibl
iblee to imple
impleme
ment nt..
To start, we can associate each type with its cardinality—the
numb
number er of inha
inhabit
bitan
ants
ts it has,
has, ignori
ignoring ng bottom
bottoms.s. Cons
Consid
ider
er the
followi
following
ng simple
simple type definiti
definitionsons::
data Void
data () = ()
7
8 CHAPTER
CHAPTER 1. THE ALGEBRA
ALGEBRA BEHIND TYPES
|Void| = 0
|()| = 1
|Bool| = 2
Any two types that have the same cardinality will always be
isomorphic
isomorphic to one another. An isomorphism between types s and t is
defin
de fined
ed as a pair
pair of fun
functio
ction
ns to and from:
to :: s -> t
from :: t -> s
such that composing either after the other gets you back where
you started. In other words, such that:
to . from = id
from . to = id
By the
the argu
argume
ment nt abov
above,
e, we shou
should
ld expe
expect
ct Spin to be isom
isomor
orph
phic
ic to
Bool. Ind
Indee
eedd it is:
is:
1.2
1.2 Sum,
Sum, Pr
Prod
oduc
uctt and
and Ex
Exp
ponen
onenti
tial
al Type
Typess
In the language of cardinalities, sum types correspond to addition.
The
The cano
canoni
nica
call exam
examplplee of thes
thesee is Eith er a b, which is either an a or a
Either
b. As a resul
result,
t, the
the cardi
cardina
nalit
lityy (reme
(rememb mber,
er, the
the numb
number
er of inha
inhabit
bitan
ants
ts))
of Eith er a b is the
Either the card
cardininal
alit
ityy of a plus
plus the
the card
cardin
inal
alit
ityy of b .
As you might expect, this is why such things are called sum types.
The intu
intuiti
ition
on behin
behind d addi
adding
ng gene
genera
raliz
lizes
es to any
any data
dataty
type
pe with
with
multiple constructors—the cardinality of a type is always the sum
of the
the card
cardin
inal
aliti
ities
es of its
its const
constru
ructo
ctors
rs..
data Deal a b
= This a
| That b
| TheO
TheOther
ther Bool
Maybe a| = 1 + |a|
|Maybe
Dual to sum types are the so-called product types. Again, we will
loo
look at thethe canonica ical example first—tht—thee pair type
type (a,
(a, b).
Analogously, the
t he cardinality of a product type is the product of their
cardinalities.
|(a,
(a, b)| = |a| × |b|
prodUnitFrom :: (a, ()
())
) -> a
prodUnitFrom (a, ()
())
) = a
"ARTESIAN WELL.
"The greatest of these interesting works yet existing in Aberdeen has just been
successfully completed at the tape-works of Messrs. Milne, Low, and Co.,
Woolmanhill. The bore is 8 inches in diameter, and 250 feet 9 inches deep. It
required nearly eleven months' working to complete the excavation.
"In its progress, the following strata were cut through in succession:—
6 feet vegetable mould.
18 " gray or bluish clay.
20 " sand and shingle, enclosing rolled stones of various sizes.
6 " light blue clay.
3 " rough sand and shingle.
115 " Old Red Sandstone conglomerate, composed of red clay, quartz, mica,
and rolled stones.
74 " alternating strata of compact, fine-grained Red Sandstone, varying in
thickness from 1 to 7 feet, and clay, varying from 6 inches to 12 feet
thick.
8 " 9 inches, mica-slate formation, the first two feet of which were chiefly a
hard, brown quartzose substance, containing iron, manganese, and
carbonate of lime.
250 feet, 9 inches.
"The temperature of the water at the bottom of the well, when completed, was
found to be within a fraction of 50° Fahrenheit, and the average temperature of
the locality, deduced from twenty-three years' observation, by the late George
limes, F. R. S., is 47° 1: hence, nearly 3 degrees of increase appear as the effects
of central heat. The supply of water obtained is excellent in quality, and sufficient
in quantity for all the purposes of the works. Such an opportunity of investigating
the geology of the locality can but rarely occur; and, in the present instance, the
proprietor and managers afforded every facility to scientific inquirers for
conducting examinations. To make the bearings of the case clear and simple, the
following is quoted from Mr. Miller's work on the Old Red Sandstone. [The writer
here quotes the above passage, and then proceeds.] Mr. Miller will be glad to
learn, that though the convulsions of nature have shattered the 'frame' along the
shores of Aberdeenshire, yet the fragments are not lost, as will be seen from the
section above described; they are here reposing in situ under the accumulated
debris of uncounted ages—chiefly the 'boulder clay,' and sedimentary deposits of
the Dee and Don, during a period when they mingled their waters in the basin in
which Aberdeen now stands. The primary rocks—the settings—our granites, of
matchless beauty stand out in bold relief a mile or two westward from the sea-
coast. Within this year or two, the 'Old Red' has been discovered at Devanha,
Union Grove, Huntly Street, Glenburnie, Balgownie, and various other localities to
the northward. Hence it may reasonably be inferred, that our fragment of the
'frame' envelops the primary rocks under our city, and along the coast for a
considerable distance between the Dee and the Buchaness."—Aberdeen
Constitutional.
The western bar has also its breaches towards the south; but it
stretches, almost without interruption, for about a hundred miles,
from the near neighborhood of Cape Wrath to the southern
extremity of Applecross; and though greatly disturbed and overflown
by the traps of the inner Hebrides, it can be traced by occasional
patches on towards the southern bar. It appears on the northern
shore of Loch Alsh, on the eastern shore of Loch Eichart, on the
southern shore of Loch Eil, on the coast and islands near Oban, and
on the east coast of Arran. Detached hills and island-like patches of
the same formation occur in several parts of the interior, far within
the frame or girdle. It caps some of the higher summits in
Sutherlandshire; it forms an oasis of sandstone among the primary
districts of Strathspey; it rises on the northern shores of Loch Ness
in an immense mass of conglomerate, based on a small-grained, red
granite, to a height of about three thousand feet over the level; and
on the north-western coast of Ross-shire it forms three immense
insulated hills, of at least no lower altitude, that rest unconformably
on a base of gneiss.
There appear every where in connection with these patches and
eminences, and with the surrounding girdle, marks of vast
denudation. I have often stood fronting the three Ross-shire hills[E]
at sunset in the finer summer evenings, when the clear light threw
the shadows of their gigantic, cone-like forms far over the lower
tract, and lighted up the lines of their horizontal strata, till they
showed like courses of masonry in a pyramid. They seem at such
times as if colored by the geologist, to distinguish them from the
surrounding tract, and from the base on which they rest as on a
common pedestal. The prevailing gneiss of the district reflects a
cold, bluish hue, here and there speckled with white, where the
weathered and lichened crags of intermingled quartz rock jut out on
the hill-sides from among the heath. The three huge pyramids, on
the contrary, from the deep red of the stone, seem flaming in purple.
There spreads all around a wild and desolate landscape of broken
and shattered hills, separated by deep and gloomy ravines, that
seem the rents and fissures of a planet in ruins, and that speak
distinctly of a period of convulsion, when upheaving fires from the
abyss, and ocean currents above, had contended in sublime
antagonism, the one slowly elevating the entire tract, the other
grinding it down and sweeping it away. I entertain little doubt that,
when this loftier portion of Scotland, including the entire Highlands,
first presented its broad back over the waves, the upper surface
consisted exclusively, from the one extremity to the other—from
Benlomond to the Maidenpaps of Caithness—of a continuous tract of
Old Red Sandstone; though, ere the land finally emerged, the ocean
currents of ages had swept it away, all except in the lower and last-
raised borders, and in the detached localities, where it still remains,
as in the pyramidal hills of western Ross-shire, to show the amazing
depth to which it had once overlaid the inferior rocks. The Old Red
Sandstone of Morvheim, in Caithness, overlooks all the primary hills
of the district, from an elevation of three thousand five hundred feet.
[E] Suil Veinn, Coul Beg, and Coul More.
The depth of the system, on both the eastern and western coasts
of Scotland, is amazingly great—how great, I shall not venture to
say. There are no calculations more doubtful than those of the
geologist. The hill just instanced (Morvheim) is apparently composed
from top to bottom of what in Scotland forms the lowest member of
the system—a coarse conglomerate; and yet I have nowhere
observed this inferior member, when I succeeded in finding a section
of it directly vertical, more than a hundred yards in thickness—less
than one tenth the height of the hill. It would be well nigh as unsafe
to infer that the three thousand five hundred feet of altitude formed
the real thickness of the conglomerate, as to infer that the thickness
of the lead which covers the dome of St. Paul's is equal to the height
of the dome. It is always perilous to estimate the depth of a deposit
by the height of a hill that seems externally composed of it, unless,
indeed, like the pyramidal hills of Ross-shire, it be unequivocally a
hill dug out by denudation, as the sculptor digs his eminences out of
the mass. In most of our hills, the upheaving agency has been
actively at work, and the space within is occupied by an immense
nucleus of inferior rock, around which the upper formation is
wrapped like a caul, just as the vegetable mould or the diluvium
wraps up this superior covering in turn. One of our best known
Scottish mountains—the gigantic Ben Nevis—furnishes an admirable
illustration of this latter construction of hill. It is composed of three
zones or rings of rock, the one rising over and out of the other, like
the cases of an opera-glass drawn out. The lower zone is composed
of gneiss and mica-slate, the middle zone of granite, the terminating
zone of porphyry. The elevating power appears to have acted in the
centre, as in the well-known case of Jorullo, in the neighborhood of
the city of Mexico, where a level tract four square miles in extent
rose, about the middle of the last century, into a high dome of more
than double the height of Arthur's Seat.[F] In the formation of our
Scottish mountain, the gneiss and mica-slate of the district seem to
have been upheaved, during the first period of Plutonic action in the
locality, into a rounded hill of moderate altitude, but of huge base.
The upheaving power continued to operate—the gneiss and mica-
slate gave way a-top—and out of this lower dome there arose a
higher dome of granite, which, in an after and terminating period of
the internal activity, gave way in turn to yet a third and last dome of
porphyry. Now, had the elevating forces ceased to operate just ere
the gneiss and mica-slate had given way, we would have known
nothing of the interior nucleus of granite—had they ceased just ere
the granite had given way, we would have known nothing of the yet
deeper nucleus of porphyry; and yet the granite and the porphyry
would assuredly have been there. Nor could any application of the
measuring rule to the side of the hill have ascertained the thickness
of its outer covering—the gneiss and the mica schist. The geologists
of the school of Werner used to illustrate what we may term the
anatomy of the earth, as seen through the spectacles of their
system, by an onion and its coats: they represented the globe as a
central nucleus, encircled by concentric coverings, each covering
constituting a geological formation. The onion, through the
introduction of a better school, has become obsolete as an
illustration; but to restore it again, though for another purpose, we
have merely to cut it through the middle, and turn downwards the
planes formed by the knife. It then represents, with its coats, hills
such as we describe—hills such as Ben Nevis, ere the granite had
perforated the gneiss, or the porphyry broken through the granite.
[F] It is rarely that the geologist catches a hill in the act of forming, and hence
the interest of this well-attested instance. From the period of the discovery of
America to the middle of the last century, the plains of Jorullo had undergone no
change of surface, and the seat of the present hill was covered by plantations of
indigo and sugar-cane, when, in June, 1759, hollow sounds were heard, and a
succession of earthquakes continued for sixty days, to the great consternation of
the inhabitants. After the cessation of these, and in a period of tranquillity, on the
28th and 29th of September, a horrible subterranean noise was again heard, and a
tract four square miles in extent rose up in the shape of a dome or bladder, to the
height of sixteen hundred and seventy feet above the original level of the plain.
The affrighted Indians fled to the mountains; and from thence looking down on
the phenomenon, saw flames issuing from the earth for miles around the newly-
elevated hill, and the softened surface rising and falling like that of an agitated
sea, and opening into numerous rents and fissures. Two brooks which had
watered the plantations precipitated themselves into the burning chasms. The
scene of this singular event was visited by Humboldt about the beginning of the
present century. At that period, the volcanic agencies had become comparatively
quiescent; the hill, however, retained its original altitude; a number of smaller hills
had sprung up around it; and the traveller found the waters of the engulfed
rivulets escaping at a high temperature from caverns charged with sulphureous
vapors and carbonic acid gas. There wore inhabitants of the country living at the
time who were more than twenty years older than the hill of Jorullo, and who had
witnessed its rise.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebooknice.com