0% found this document useful (0 votes)
8 views55 pages

(Ebook) Thinking With Types: Type-Level Programming in Haskell by Sandy Maguireinstall Download

The document is an overview of various ebooks related to Haskell programming and type-level programming, including titles like 'Thinking with Types' by Sandy Maguire and 'Effective Haskell' by Rebecca Skinner. It provides links to download these ebooks in different formats. Additionally, it includes a detailed table of contents for 'Thinking with Types,' outlining its structure and topics covered.

Uploaded by

jqitjaeta984
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views55 pages

(Ebook) Thinking With Types: Type-Level Programming in Haskell by Sandy Maguireinstall Download

The document is an overview of various ebooks related to Haskell programming and type-level programming, including titles like 'Thinking with Types' by Sandy Maguire and 'Effective Haskell' by Rebecca Skinner. It provides links to download these ebooks in different formats. Additionally, it includes a detailed table of contents for 'Thinking with Types,' outlining its structure and topics covered.

Uploaded by

jqitjaeta984
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

(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

Download more ebook instantly today at https://ebooknice.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

Start reading on any device today!

(Ebook) Thinking with Type by Ellen Lupton ISBN 9781616890223, 1616890223

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

(Ebook) Thinking Functionally With Haskell by Richard Bird ISBN 9781107087200,


9781107452640, 1107087201, 1107452643

https://ebooknice.com/product/thinking-functionally-with-haskell-10508692

ebooknice.com

(Ebook) Typescript Cookbook: Real World Type-Level Programming by Stefan Baumgartner


ISBN 9781098136659, 1098136659

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

(Ebook) Programming in Haskell by Graham Hutton ISBN 9781316626221, 1316626229

https://ebooknice.com/product/programming-in-haskell-22231412

ebooknice.com

(Ebook) Programming in Haskell by Hutton, Graham ISBN 9781316626221, 9781316784099,


1316626229, 1316784096

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

(Ebook) Effective Haskell: Solving Real-World Problems with Strongly Typed


Functional Programming by Rebecca Skinner ISBN 1680509349

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

All rights reserved.

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

III Computing at the Type-Level 95


9 Associated Type Families 97
9.1 Building Types from a Schema . . . . . . . . . . . . . . . . 98
9.2 Generating Associated Terms . . . . . . . . . . . . . . . . . 102
10 First Class Families 107
10.1 Defunctionalization . . . . . . . . . . . . . . . . . . . . . . . 107
10.2 Type-Level Defunctionalization . . . . . . . . . . . . . . . 109
10.3 Working with First Class Families . . . . . . . . . . . . . . 113
10.4 Ad-Hoc Polymorphism . . . . . . . . . . . . . . . . . . . . . 116
CONTENTS vii

11 Extensible Data 119


11.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
11.2 Open Sums . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
11.3 Open Products . . . . . . . . . . . . . . . . . . . . . . . . . . 125
11.4 Overloaded Labels . . . . . . . . . . . . . . . . . . . . . . . . 131
12 Custom Type Errors 133
13 Generics 141
13.1 Generic Representations . . . . . . . . . . . . . . . . . . . . 142
13.2 Deriving Structural Polymorphism . . . . . . . . . . . . . 145
13.3 Using Generic Metadata . . . . . . . . . . . . . . . . . . . . 151
13.4 Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
13.5 Kan Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . 165
14 Indexed Monads 169
14.1 Definition and Necessary Machinery . . . . . . . . . . . . 169
14.2 Linear Allocations . . . . . . . . . . . . . . . . . . . . . . . . 173
15 Dependent Types 181
15.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
15.2 Ad-Hoc Implementation . . . . . . . . . . . . . . . . . . . . 182
15.3 Generalized Machinery . . . . . . . . . . . . . . . . . . . . . 187
15.4 The Singletons Package . . . . . . . . . . . . . . . . . . . . 192
15.5 Dependent Pairs . . . . . . . . . . . . . . . . . . . . . . . . . 195
15.5.1 Structured Logging . . . . . . . . . . . . . . . . . . . 199

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

recommend it to anyone who is better at starting projects than


finishing them.
It sounds cliche, but this book couldn’t have happened without
the overwhelming support of the Haskell community. It’s
particularly telling that every day I learn new things from them
about this marvelous language, even after five years.
Written with love by Sandy Maguire. 2018.
Acknowledgments

This book couldn’t have happened without the support of many,


many fantastic people. I’d like to thank everyone for their support,
their patronage and their enthusiasm. Some of the exceptionally
instrumental people, however, require further accolades. In
particular:
Fintan Halpenny, for his everlasting gusto. My unocial editor,
publicist, and second pair of eyes. The only person I know who’s
actually done all of the exercises.
Irene Papakonstantinou, for her untiring support, who first
encouraged me to publish this book, who bullied me into staying on
schedule, and for putting her money where her mouth was.
Jessie Natasha, for patiently answering my non-stop design
questions. For time and time again oering me her sense of style,
and spending long hours with me helping make the book look as
good as it does.
Anushervon Saidmuradov, whose support for me greatly exceeds
his interest in Haskell.
Furthermore, this book wouldn’t have been possible without the
financial support of Habito, Mirzhan Irkegulov, Michael Koloberdin,
and Chris Double.

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

or any such thing. Rather, this desire comes from a place of


benevolence—a little frustration with the type-checker now is
preferable to a hard-to-find bug making its way into production.
Type-level programming, like anything, is best in moderation. It
comes with its own costs in terms of complexity, and as such should
be wielded with care. While it’s pretty crucial that your financial
application handling billions of dollars a day runs smoothly, it’s a
little less critical if your hobbyist video game draws a single frame of
gameplay incorrectly. In the first case, it’s probably worthwhile to
use whatever tools you have in order to prevent things from going
wrong. In the second, these techniques are likely too heavy-handed.
Style is a notoriously dicult thing to teach—in a very real sense,
style seems to be what’sleft after we’ve extracted from a subject all of
the things we know how to teach. Unfortunately, when to use type-
level programming is largely a matter of style. It’s easy to take the
ball and run with it, but discretion is divine.
When in doubt, err on the side of not doing it at the type-level.
Save these techniques for the cases where it’d be catastrophic to get
things wrong, for the cases where a little type-level stu goes a long
way, and for the cases where it will drastically improve the API. If
your use-case isn’t obviously one of these, it’s a good bet that there
is a cleaner and easier means of doing it with values.
But let’s talk more about types themselves.
As a group, I think it’s fair to say that Haskellers are contrarians.
Mostofus,I’dsuspect,havespentatleastoneeveningtryingtoextol
the virtues of a strong type system to a dynamically typed colleague.
They’ll say things along the lines of “I like Ruby because the types
don’t get in my way.” Though our first instinct, as proponents of
strongly typed systems, might be to forcibly connect our head to the
table, I think this is a criticism worth keeping in mind.
As Haskellers, we certainly have strong opinions about the value
of types. They are useful, and they do carry their weight in gold
when coding, debugging and refactoring. While we can dismiss our
colleague’s complaints with a wave of the hand and the justification
that they’ve never seen a “real” type system before, we are doing
them and ourselves a disservice both. Such a flippant response is to
ignore the spirit of their unhappiness—types often do get in the way.
We’ve just learned to blind ourselves to these shortcomings, rather
than to bite the bullet and entertain that maybe types aren’t always
CONTENTS 3

the solution to every problem.


Simon Peyton-Jones, one of the primary authors of Haskell, is
quick to acknowledge the fact that there are plenty of error-free
programs ruled out by a type system. Consider, for example, the
following program which has a type-error, but never actually
evaluates it:
fst ("no problems", True <> 17)

Because the type error gets ignored lazily by fst, evaluation of


such an expression will happily produce "no problems" at runtime.
Despite the fact that we consider it to be ill-typed, it is in fact,
well-behaved. The usefulness of such an example is admittedly low,
but the point stands; types often do get in the way of perfectly
reasonable programs.
Sometimes such an obstruction comes under the guise of “it’s not
clear what type this thing should have.” One particularly poignant
case of this is C’s printf function:

int printf (const char *format, ...)

If you’ve never before had the pleasure of using printf, it works


like this: it parses the format parameter, and uses its structure to pop
additional arguments o of the call-stack. You see, it’s the shape of
format that decides what parameters should fill in the ... above.
For example, the format string "hello %s" takes an additional
string and interpolates it in place of the %s. Likewise, the specifier %d
describes interpolation of a signed decimal integer.
The following calls to printf are all valid:
• printf("hello %s", "world"), producing “hello world”,

• printf("%d + %d = %s", 1, 2, "three"), producing “1 + 2 =


three”,
• printf("no specifiers"), producing “no specifiers”.

Notice that, as written, it seems impossible to assign a Haskell-


esque type signature to printf. The additional parameters denoted
by its ellipsis are given types by the value of its first parameter—a
string. Such a pattern is common in dynamically typed languages,
and in the case of printf, it’s inarguably useful.
4 CONTENTS

The documentation for printf is quick to mention that the


format string must not be provided by the user—doing so opens up
vulnerabilities in which an attacker can corrupt memory and
gain access to the system. Indeed, this is hugely widespread
problem—and crafting such a string is often the first homework in
any university lecture on software security.
To be clear, the vulnerabilities in printf occur when the format
string’s specifiers do not align with the additional arguments given.
The following, innocuous-looking calls to printf are both malicious.
• printf("%d"), which will probably corrupt the stack,

• printf("%s", 1), which will read an arbitrary amount of


memory.
C’s type system is insuciently expressive to describe printf.
But because printf is such a useful function, this is not a
persuasive-enough reason to exclude it from the language. Thus,
type-checking is eectively turned o for calls to printf so as to
have ones cake and eat it too. However, this opens a hole through
which type errors can make it all the way to runtime—in the form of
undefined behavior and security issues.
My opinion is that preventing security holes is a much more
important aspect of the types, over “null is the billion dollar
mistake” or whichever other arguments are in vogue today. We will
return to the problem of printf in chapter 9.
With very few exceptions, the prevalent attitude of Haskellers
has been to dismiss the usefulness of ill-typed programs. The
alternative is an uncomfortable truth: that our favorite language
can’t do something useful that other languages can.
But all is not lost. Indeed, Haskell is capable of expressing things
as oddly-typed as printf, for those of us willing to put in the eort
to learn how. This book aims to be the comprehensive manual for
getting you from here to there, from a competent Haskell
programmer to one who convinces the compiler to do their work for
them.
Part I

Fundamentals

5
Chapter 1

The Algebra Behind Types

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 () = ()

data Bool = False | True

Void has zero inhabitants, and so it is assigned cardinality 0. The


unit type () has one inhabitant—thus its cardinality is 1. Not to
belabor the point, but Bool has cardinality 2, corresponding to its

7
8 CHAPTER
CHAPTER 1. THE ALGEBRA
ALGEBRA BEHIND TYPES

constructors True and False.


We can write these statements about cardinality more formally:

|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

We sometimes write an isomorphism between types s and t as s ∼


=
t.
If two types have the same cardinality, any one-to-one mapping
between their elements is exactly these to and from funcfunction
tions.
s. But
where does such a mapping come from? Anywhere—it doesn’t really
matter!
matter! Just
Just pick an arbitra
arbitrary
ry orderin
ordering
g on each type—no
type—nott necess
necessaril
arilyy
corresponding to an Ord instance—and then map the first element
under one ordering to the first element under the other. Rinse and
repeat.
For
For exam
examplple,
e, we can
can de
defin
finee a new type
type that
that also
also has
has card
cardin
inal
alit
ityy 2.

data Spin = Up | Down


1.1. ISOMORPHISMS AN
AND CA
CARDINALITIES 9

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:

boolToSpin1 :: Bool -> Spin


boolToSpin1 False = Up
boolToSpin1 True = Down

spinToBool1 :: Spin -> Bool


spinToBool1 Up = False
spinToBool1 Down = True

However, note that there is another isomorphism between Spin


and Bool:

boolToSpin2 :: Bool -> Spin


boolToSpin2 False = Down
boolToSpin2 True = Up

spinToBool2 :: Spin -> Bool


spinToBool2 Up = True
spinToBool2 Down = False

Which of the two isomorphisms should we prefer? Does it matter?


In gene
genera
ral,
l, for
for any
any two
two types
types wiwithth card
cardin
inali
ality
ty n,thereare n! unique
isom
isomororph
phis
isms
ms betw
betwee
een
n them
them.. As farfar as the
the math
math goes
goes,, any
any of thes
thesee is
just as good as any other—and for most purposes, p urposes, knowing that an
isomorphism exists is enou
enoughgh..
An isomorphism between types s and t is a proof that for all
intents and purposes, s and t are the same thing. They might have
dierent instances available, but this is more a statement about
Haskell’s typeclass machinery than it is about the equivalence of s
and t.
Isomorphisms are a particularly powerful concept in the algebra
of types. Throughout this book we shall reason via isomorphism, so
it’s
it’s bes
best to get
get comf
comfor
orta
tabl
blee wi
withth the
the idea
idea now.
now.
10 CHAPTER
CHAPTER 1. THE ALGEBRA
ALGEBRA BEHIND TYPES

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 .

|Either a b| = |a| + |b|


Either

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

We can analyze Deal’s cardina


cardinality
lity;;

|Deal a b| = |a| + |b| + |Bool|


= |a| + |b| + 2

We can also look at the cardinality of Mayb e a. Because


Maybe Because nullar
nullaryy
data constructors are uninteresting to construct—there is only one
Nothing—the
—the card
cardin
inal
ality
ity of Maybe a can
Maybe can be expr
expres
esse
sed
d as foll
follow
ows;
s;

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|

To give an illustration, consider mixed fractions of the form 5 12 .


We can represent these in Haskell via a product type;
1.2. SUM, PRODUCT AND EXPONENTIAL TYPES 11

data MixedFraction a = Fraction


{ mixedBi
mixedBit
t :: Word8
, numerat
numerator
or :: a
, denomin
denominato
ator
r :: a
}

And perform its cardinality analysis as follows:

MixedFraction a| = |Word8| × |a| × |a| = 256 × |a| × |a|


|MixedFraction

An interesting consequence of all of this cardinality stu is that


we find ourselves able to express math
mathem
ematatic
ical
al trut
truths
hs in term typess.
termss of type
For
For exam
exampl
ple,
e, we can
can prov
provee that
that a × 1 = a by showing an isomorphism
between (a, ()) and a.
(a, ())

prodUnitTo :: a -> (a, ()


())
)
prodUnitTo a = (a, ()
())
)

prodUnitFrom :: (a, ()
())
) -> a
prodUnitFrom (a, ()
())
) = a

Here, we can think of the unit type as being a monoidal identity


for product types—in the sense that “sticking it in doesn’t change
anything.” Because a × 1 = a , we can pair with as many unit types as
we want.
Likewise, Void acts
acts as a mono
monoididal
al unit
nit for sum
sum type
types.
s. To con
convinc
vincee
ourselves of this, the trivial statement a + 0 = a can be witnessed as
an isomorph
isomorphism
ism between
between Eith
Either Void and a.
er a Void

sumUnitTo :: Either a Void -> a


sumUnitTo (Left a) = a
sumUnitTo (Right v) = absur
absurd
d v · · · · · · · · · · · · · · · · 1

sumUnitFrom :: a -> Either a Void


sumUnitFrom = Left
Another Random Document on
Scribd Without Any Related Topics
earnest of whatever is mild and genial in the better half of the year.
All the workmen rested at midday, and I went to enjoy my half-hour
alone on a mossy knoll in the neighboring wood, which commands
through the trees a wide prospect of the bay and the opposite shore.
There was not a wrinkle on the water, nor a cloud in the sky, and the
branches were as moveless in the calm as if they had been traced on
canvas. From a wooded promontory that stretched half way across
the frith, there ascended a thin column of smoke. It rose straight as
the line of a plummet for more than a thousand yards, and then, on
reaching a thinner stratum of air, spread out equally on every side,
like the foliage of a stately tree. Ben Nevis rose to the west, white
with the yet unwasted snows of winter, and as sharply defined in the
clear atmosphere, as if all its sunny slopes and blue retiring hollows
had been chiselled in marble. A line of snow ran along the opposite
hills; all above was white, and all below was purple. They reminded
me of the pretty French story, in which an old artist is described as
tasking the ingenuity of his future son-in-law, by giving him, as a
subject for his pencil, a flower-piece composed of only white flowers,
of which the one half were to bear their proper color, the other half
a deep purple hue, and yet all be perfectly natural; and how the
young man resolved the riddle, and gained his mistress, by
introducing a transparent purple vase into the picture, and making
the light pass through it on the flowers that were drooping over the
edge. I returned to the quarry, convinced that a very exquisite
pleasure may be a very cheap one, and that the busiest
employments may afford leisure enough to enjoy it.
The gunpowder had loosened a large mass in one of the inferior
strata, and our first employment, on resuming our labors, was to
raise it from its bed. I assisted the other workmen in placing it on
edge, and was much struck by the appearance of the platform on
which it had rested. The entire surface was ridged and furrowed like
a bank of sand that had been left by the tide an hour before. I could
trace every bend and curvature, every cross hollow and counter
ridge of the corresponding phenomena; for the resemblance was no
half resemblance—it was the thing itself; and I had observed it a
hundred and a hundred times, when sailing my little schooner in the
shallows left by the ebb. But what had become of the waves that
had thus fretted the solid rock, or of what element had they been
composed? I felt as completely at fault as Robinson Crusoe did on
his discovering the print of the man's foot on the sand. The evening
furnished me with still further cause of wonder. We raised another
block in a different part of the quarry, and found that the area of a
circular depression in the stratum below was broken and flawed in
every direction, as if it had been the bottom of a pool recently dried
up, which had shrunk and split in the hardening. Several large
stones came rolling clown from the diluvium in the course of the
afternoon. They were of different qualities from the Sandstone
below, and from one another; and, what was more wonderful still,
they were all rounded and water-worn, as if they had been tossed
about in the sea, or the bed of a river, for hundreds of years. There
could not, surely, be a more conclusive proof that the bank which
had enclosed them so long could not have been created on the rock
on which it rested. No workman ever manufactures a half-worn
article, and the stones were all half-worn! And if not the bank, why
then the sandstone underneath? I was lost in conjecture, and found
I had food enough for thought that evening, without once thinking
of the unhappiness of a life of labor.
The immense masses of diluvium which we had to clear away
rendered the working of the quarry laborious and expensive, and all
the party quitted it in a few days, to make trial of another that
seemed to promise better. The one we left is situated, as I have
said, on the southern shore of an inland bay—the Bay of Cromarty;
the one to which we removed has been opened in a lofty wall of
cliffs that overhangs the northern shore of the Moray Frith. I soon
found I was to be no loser by the change. Not the united labors of a
thousand men for more than a thousand years could have furnished
a better section of the geology of the district than this range of cliffs.
It may be regarded as a sort of chance dissection on the earth's
crust. We see in one place the primary rock, with its veins of granite
and quartz, its dizzy precipices of gneiss, and its huge masses of
hornblende; we find the secondary rock in another, with its beds of
sandstone and shale, its spars, its clays, and its nodular limestones.
We discover the still little known but highly interesting fossils of the
Old Red Sandstone in one deposition; we find the beautifully
preserved shells and lignites of the Lias in another. There are the
remains of two several creations at once before us. The shore, too,
is heaped with rolled fragments of almost every variety of rock,—
basalts, ironstones, hypersthenes, porphyries, bituminous shales,
and micaceous schists. In short, the young geologist, had he all
Europe before him, could hardly choose for himself a better field. I
had, however, no one to tell me so at the time, for geology had not
yet travelled so far north; and so, without guide or vocabulary, I had
to grope my way as I best might, and find out all its wonders for
myself. But so slow T was the process, and so much was I a seeker
in the dark, that the facts contained in these few sentences were the
patient gatherings of years.
In the course of the first day's employment, I picked up a
nodular mass of blue limestone, and laid it open by a stroke of the
hammer. Wonderful to relate, it contained inside a beautifully
finished piece of sculpture—one of the volutes apparently of an Ionic
capital; and not the far-famed walnut of the fairy tale, had I broken
the shell and found the little dog lying within, could have surprised
me more. Was there another such curiosity in the whole world? I
broke open a few other nodules of similar appearance,—for they lay
pretty thickly on the shore,—and found that there might. In one of
these there were what seemed to be the scales of fishes, and the
impressions of a few minute bivalves, prettily striated; in the centre
of another there was actually a piece of decayed wood. Of all
Nature's riddles these seemed to me to be at once the most
interesting, and the most difficult to expound. I treasured them
carefully up, and was told by one of the workmen to whom I showed
them, that there was a part of the shore about two miles farther to
the west, where curiously shaped stones, somewhat like the heads
of boarding-pikes, were occasionally picked up; and that in his
father's days the country people called them thunderbolts, and
deemed them of sovereign efficacy in curing bewitched cattle. Our
employer, on quitting the quarry for the building on which we were
to be engaged, gave all the workmen a half-holiday. I employed it in
visiting the place where the thunderbolts had fallen so thickly, and
found it a richer scene of wonder than I could have fancied in even
my dreams.
What first attracted my notice was a detached group of low lying
skerries, wholly different in form and color from the sandstone cliffs
above, or the primary rocks a little farther to the west. I found them
composed of thin strata of limestone, alternating with thicker beds of
a black slaty substance, which, as I ascertained in the course of the
evening, burns with a powerful flame, and emits a strong bituminous
odor. The layers into which the beds readily separate are hardly an
eighth part of an inch in thickness, and yet on every layer there are
the impressions of thousands and tens of thousands of the various
fossils peculiar to the Lias. We may turn over these wonderful leaves
one after one, like the leaves of a herbarium, and find the pictorial
records of a former creation in every page. Scallops, and gryphites,
and ammonites, of almost every variety peculiar to the formation,
and at least some eight or ten varieties of belemnite; twigs of wood,
leaves of plants, cones of an extinct species of pine, bits of charcoal,
and the scales of fishes; and, as if to render their pictorial
appearance more striking, though the leaves of this interesting
volume are of a deep black, most of the impressions are of a chalky
whiteness. I was lost in admiration and astonishment, and found my
very imagination paralyzed by an assemblage of wonders, that
seemed to outrival, in the fantastic and the extravagant, even its
wildest conceptions. I passed on from ledge to ledge, like the
traveller of the tale through the city of statues, and at length found
one of the supposed aerolites I had come in quest of, firmly
imbedded in a mass of shale. But I had skill enough to determine
that it was other than what it had been deemed. A very near
relative, who had been a sailor in his time on almost every ocean,
and had visited almost every quarter of the globe, had brought
home one of these meteoric stones with him from the coast of Java.
It was of a cylindrical shape and vitreous texture, and it seemed to
have parted in the middle when in a half-molten state, and to have
united again, somewhat awry, ere it had cooled enough to have lost
the adhesive quality. But there was nothing organic in its structure,
whereas the stone I had now found was organized very curiously
indeed. It was of a conical form and filamentary texture, the
filaments radiating in straight lines from the centre to the
circumference. Finely-marked veins like white threads ran
transversely through these in its upper half to the point, while the
space below was occupied by an internal cone, formed of plates that
lay parallel to the base, and which, like watch-glasses, were concave
on the under side, and convex on the upper. I learned in time to call
this stone a belemnite, and became acquainted with enough of its
history to know that it once formed part of a variety of cuttle-fish,
long since extinct.
My first year of labor came to a close, and I found that the
amount of my happiness had not been less than in the last of my
boyhood. My knowledge, too, had increased in more than the ratio
of former seasons; and as I had acquired the skill of at least the
common mechanic, I had fitted myself for independence. The
additional experience of twenty years has not shown me that there
is any necessary connection between a life of toil and a life of
wretchedness; and when I have found good men anticipating a
better and a happier time than either the present or the past, the
conviction that in every period of the world's history the great bulk
of mankind must pass their days in labor, has not in the least
inclined me to scepticism.
My curiosity, once fully awakened, remained awake, and my
opportunities of gratifying it have been tolerably ample. I have been
an explorer of caves and ravines—a loiterer along sea-shores—a
climber among rocks—a laborer in quarries. My profession was a
wandering one. I remember passing direct, on one occasion, from
the wild western coast of Ross-shire, where the Old Red Sandstone
leans at a high angle against the prevailing Quartz Rock of the
district, to where, on the southern skirts of Mid-Lothian, the
Mountain Limestone rises amid the coal. I have resided one season
on a raised beach of the Moray Frith. I have spent the season
immediately following amid the ancient granites and contorted
schists of the central Highlands. In the north I have laid open by
thousands the shells and lignites of the Oolite; in the south I have
disinterred from their matrices of stone or of shale the huge reeds
and tree ferns of the Carboniferous period. I have been taught by
experience, too, how necessary an acquaintance with geology of
both extremes of the kingdom is to the right understanding of the
formations of either. In the north, there occurs a vast gap in the
scale. The Lias leans unconformably against the Old Red Sandstone;
there is no Mountain Limestone, no Coal Measures, none of the New
Red Marls or Sandstones, Under or Upper. There are at least three
entire systems omitted. But the upper portion of the scale is well
nigh complete. In one locality we may pass from the Lower to the
Upper Lias, in another from the Inferior to the Great Oolite, and
onward to the Oxford Clay and the Coral Rag. We may explore, in a
third locality, beds identical in their organisms with the Wealden of
Sussex. In a fourth we find the flints and fossils of the Chalk. The
lower part of the scale is also well nigh complete. The Old Red
Sandstone is amply developed in Moray, Caithness, and Ross; and
the Grauwacke, in its more ancient unfossiliferous type, rather
extensively in Banffshire. But to acquaint one's self with the three
missing formations,—to complete one's knowledge of the entire
scale by filling up the hiatus,—it is necessary to remove to the south.
The geology of the Lothians is the geology of at least two thirds of
the gap, and perhaps a little more;—the geology of Arran wants, it is
supposed, only the Upper New lied Sandstone to fill it entirely.
One important truth I would fain press on the attention of my
lowlier readers. There are few professions, however humble, that do
not present their peculiar advantages of observation; there are none,
I repeat, in which the exercise of the faculties does not lead to
enjoyment. I advise the stone-mason, for instance, to acquaint
himself with Geology. Much of his time must be spent amid the rocks
and quarries of widely separated localities. The bridge or harbor is
no sooner completed in one district, than he has to remove to where
the gentleman's seat, or farm-steading is to be erected in another;
and so, in the course of a few years, he may pass over the whole
geological scale, even when restricted to Scotland, from the
Grauwacke of the Lammermuirs, to the Wealden of Moray, or the
Chalk-flints of Banffshire and Aberdeen; and this, too, with
opportunities of observation, at every stage, which can be shared
with him by only the gentleman of fortune, who devotes his whole
time to the study. Nay, in some respects, his advantages are superior
to those of the amateur himself. The latter must often pronounce a
formation unfossiliferous when, after the examination of at most a
few days, he discovers in it nothing organic; and it will be found that
half the mistakes of geologists have arisen from conclusions thus
hastily formed. But the working-man, whose employments have to
be carried on in the same formation for months, perhaps years,
together, enjoys better opportunities for arriving at just decisions.
There are, besides, a thousand varieties of accident which lead to
discovery—floods, storms, landslips, tides of unusual height, ebbs of
extraordinary fall: and the man who plies his labor at all seasons in
the open air has by much the best, chance of profiting by these.
There are formations which yield their organisms slowly to the
discoverer, and the proofs which establish their place in the
geological scale more tardily still. I was acquainted with the Old Red
Sandstone of Ross and Cromarty for nearly ten years ere I had
ascertained that it is richly fossiliferous—a discovery which, in
exploring this formation in those localities, some of our first
geologists had failed to anticipate. I was acquainted with it for nearly
ten years more ere I could assign to its fossils their exact place in
the scale.
In the following chapters I shall confine my observations chiefly
to this system and its organisms. To none of the others, perhaps,
excepting the Lias of the north of Scotland, have I devoted an equal
degree of attention; nor is there a formation among them which, up
to the present time, has remained so much a terra incognita to the
geologist. The space on both sides has been carefully explored to its
upper and lower boundary; the space between has been suffered to
remain well nigh a chasm. Should my facts regarding it—facts
constituting the slow gatherings of years—serve as stepping-stones
laid across, until such time as geologists of greater skill, and more
extended research, shall have bridged over the gap, I shall have
completed half my design. Should the working-man be encouraged
by my modicum of success to improve his opportunities of
observation, I shall have accomplished the whole of it. It cannot be
too extensively known, that nature is vast and knowledge limited;
and that no individual, however humble in place or acquirement,
need despair of adding to the general fund.
CHAPTER II.
The Old Red Sandstone.—Till very lately its Existence as a distinct Formation
disputed.—Still little known.—Its great Importance in the Geological Scale.—
Illustration.—The North of Scotland girdled by an immense Belt of Old Red
Sandstone.—Line of the Girdle along the Coast.—Marks of vast Denudation.—
Its Extent partially indicated by Hills on the Western Coast of Ross-shire.—The
System of Great Depth in the North of Scotland.—Difficulties in the way of
estimating the Thickness of Deposits.—Peculiar Formation of Hill.—Illustrated
by Ben Nevis.—Caution to the Geological Critic.—Lower Old Red Sandstone
immensely developed in Caithness.—Sketch of the Geology of that County.—Its
strange Group of Fossils.—Their present place of Sepulture.—Their ancient
Habitat.—Agassiz.—Amazing Progress of Fossil Ichthyology during the last few
Years.—Its Nomenclature.—Learned Names repel unlearned Readers.—Not a
great deal in them.

"The Old Red Sandstone," says a Scottish geologist, in a digest of


some recent geological discoveries, which appeared a short time ago
in an Edinburgh newspaper, "has been hitherto considered as
remarkably barren of fossils." The remark is expressive of a pretty
general opinion among geologists of even the present time, and I
quote it on this account. Only a few years have gone by since men
of no low standing in the science disputed the very existence of this
formation—system rather, for it contains at least three distinct
formations; and but for the influence of one accomplished geologist,
the celebrated author of the Silurian System, it would have been
probably degraded from its place in the scale altogether. "You must
inevitably give up the Old Red Sandstone," said an ingenious
foreigner to Mr. Murchison, when on a visit to England about four
years ago, and whose celebrity among his own countrymen rested
chiefly on his researches in the more ancient formations,—"you must
inevitably give up the Old Red Sandstone: it is a mere local deposit,
a doubtful accumulation huddled up in a corner, and has no type or
representative abroad." "I would willingly give it up if nature would,"
was the reply; "but it assuredly exists, and I cannot." In a recently
published tabular exhibition of the geological scale by a continental
geologist, I could not distinguish this system at all. There are some
of our British geologists, too, who still regard it as a sort of
debatable tract, entitled to no independent status. They find, in what
they deem its upper beds, the fossils of the Coal Measures, and the
lower graduating apparently into the Silurian System; and regard the
whole as a sort of common, which should be divided as proprietors
used to divide commons in Scotland half a century ago, by giving a
portion to each of the bordering territories. Even the better informed
geologists, who assign to it its proper place as an independent
formation, furnished with its own organisms, contrive to say all they
know regarding it in a very few paragraphs. Lyell, in the first edition
of his admirable elementary work, published only two years ago,
devotes more than thirty pages to his description of the Coal
Measures, and but two and a half to his notice of the Old Red
Sandstone.[C]
[C] As the succinct notice of this distinguished geologist may serve as a sort of
pocket map to the reader in indicating the position of the system, its three great
deposits, and its extent, I take the liberty of transferring it entire.
"OLD RED SANDSTONE.
"It was stated that the Carboniferous formation was surmounted by one called
the 'New lied Sandstone,' and underlaid by another called the Old Red, which last
was formerly merged in the Carboniferous System, but is now found to be
distinguishable by its fossils. The Old Red Sandstone is of enormous thickness in
Herefordshire, Worcestershire, Shropshire, and South Wales, where it is seen to
crop out beneath the Coal Measures, and to repose on the Silurian Rocks. In that
region, its thickness has been estimated by Mr. Murchison at no less than ten
thousand feet. It consists there of—
"1st. A quartzose conglomerate, passing downwards into chocolate-red and
green sandstone and marl.
"2d. Cornstone and marl, (red and green argillaceous spotted marls, with
irregular courses of impure concretionary limestone, provincially called Cornstone,
mottled red and green; remains of fishes.)
"3d. Tilestone, (finely laminated hard reddish or green micaceous or quartzose
sandstones, which split into tiles; remains of mollusca and fishes.)
"I have already observed that fossils are rare in marls and sandstones in which
the red oxide of iron prevails. In the Cornstone, however, of the counties above
mentioned, fishes of the genera Cephalaspis and Onchus have been discovered. In
the Tilestone, also, Ichthyodorulites of the genus Onchus have been obtained, and
a species of Dipterus, with mollusca of the genera Avicula, Area, Cucullæa,
Terebratula, Lingula, Turbo, Trochus, Turritella, Bellerophon, Orthoceras, and
others.
"By consulting geological maps, the reader will perceive that, from Wales to the
north of Scotland, the Old Red Sandstone appears in patches, and often in large
tracts. Many fishes have been found in it at Caithness, and various organic
remains in the northern part of Fifeshire, where it crops out from beneath the Coal
formation, and spreads into the adjoining northern half of Forfarshire; forming,
together with trap, the Sidlaw Hills and valley of Strathmore. A large belt of this
formation skirts the northern borders of the Grampians, from the sea-coast at
Stonehaven and the Frith of Tay to the opposite western coast of the Frith of
Clyde. In Forfarshire, where, as in Herefordshire, it is many thousand feet thick, it
may be divided into three principal masses—1st. Red and mottled marls,
cornstone, and sandstone; 2d. Conglomerate, often of vast thickness; 3d.
Tilestones, and paving-stone, highly micaceous, and containing a slight admixture
of carbonate of lime. In the uppermost of these divisions, but chiefly in the lowest,
the remains of fish have been found, of the genus named by M. Agassiz
Cephalaspis, or buckler-headed, from the extraordinary shield which covers the
head, and which, has often been mistaken for that of a trilobite of the division
Asaphus. A gigantic species of fish, of the genus Holoptychius, has also been
found by Dr. Fleming in the Old Red Sandstone of Fifeshire."—Lyell's Elements, pp.
452-4.

It will be found, however, that this hitherto neglected system


yields in importance to none of the others, whether we take into
account its amazing depth, the great extent to which it is developed
both at home and abroad, the interesting links which it furnishes in
the zoölogical scale, or the vast period of time which it represents.
There are localities in which the depth of the Old Red Sandstone
fully equals the elevation of Mount Ætna over the level of the sea,
and in which it contains three distinct groups of organic remains, the
one rising in beautiful progression over the other. Let the reader
imagine a digest of English history, complete from the times of the
invasion of Julius Cæsar to the reign of that Harold who was slain at
Hastings, and from the times of Edward III. down to the present
day, but bearing no record of the Williams, the Henrys, the Edwards,
the John, Stephen, and Richard, that reigned during the omitted
period, or of the striking and important events by which their several
reigns were distinguished. A chronicle thus mutilated and incomplete
would be no unapt representation of a geological history of the earth
in which the period of the Upper Silurian would be connected with
that of the Mountain Limestone, or of the limestone of Burdie House,
and the period of the Old Red Sandstone omitted.
The eastern and western coasts of Scotland, which lie to the
north of the Friths of Forth and Clyde, together with the southern
flank of the Grampians and the northern coast of Sutherland and
Caithness, appear to have been girdled at some early period by
immense continuous beds of Old Red Sandstone. At a still earlier
time, the girdle seems to have formed an entire mantle, which
covered the enclosed tract from side to side. The interior is
composed of what, after the elder geologists, I shall term primary
rocks—porphyries, granites, gneisses, and micaceous schists; and
this central nucleus, as it now exists, seems set in a sandstone
frame. The southern bar of the frame is still entire: it stretches along
the Grampians from Stonehaven to the Frith of Clyde. The northern
bar is also well nigh entire: it runs unbroken along the whole
northern coast of Caithness, and studs, in three several localities,
the northern coast of Sutherland, leaving breaches of no very
considerable extent between. On the east, there are considerable
gaps, as along the shores of Aberdeenshire.[D] The sandstone,
however, appears at Gamrie, in the county of Banff, in a line parallel
to the coast, and, after another interruption, follows the coast of the
Moray Frith far into the interior of the great Caledonian valley, and
then running northward along the shores of Cromarty, Ross, and
Sutherland, joins, after another brief interruption, the northern bar
at Caithness.
[D] The progress of discovery has shown, since this passage was written, that
these gaps are not quite so considerable as I had supposed. The following
paragraph, which appeared in July, 1843, in an Aberdeen paper, bears directly on
the point, and is worthy of being preserved:—

"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.

If it be thus unsafe, however, to calculate on the depth of


deposits by the altitude of hills, it is quite as unsafe for the geologist,
who has studied a formation in one district, to set himself to criticise
the calculations of a brother geologist by whom it has been studied
in a different and widely-separated district. A deposit in one locality
may be found to possess many times the thickness of the same
deposit in another. There are exposed, beside the Northern and
Southern Sutors of Cromarty, two nearly vertical sections of the
coarse conglomerate bed, which forms, as I have said, in the north
of Scotland, the base of the Old Red System, and which rises to so
great an elevation in the mountain of Morvheim. The sections are
little more than a mile apart; and yet, while the thickness of this bed
in the one does not exceed one hundred feet, that of the same bed
in the other somewhat exceeds two hundred feet. More striking still
—under the Northern Sutor, the entire Geology of Caithness, with all
its vast beds, and all its numerous fossils, from the granitic rock of
the Ord hill, the southern boundary of the county, to the uppermost
sandstones of Dunnet-head, its extreme northern corner, is exhibited
in a vertical section not more than three hundred yards in extent.
And yet so enormous is the depth of the deposit in Caithness, that it
has been deemed by a very superior geologist to represent three
entire formations—the Old Red System, by its unfossiliferous,
arenaceous, and conglomerate beds; the Carboniferous System, by
its dark-colored middle schists, abounding in bitumen and
ichthyolites; and the New Red Sandstone, by the mottled marls and
mouldering sandstones that overlie the whole.[G] A slight sketch of
the Geology of Caithness may not be deemed uninteresting. This
county includes, in the state of greatest development any where yet
known, that fossiliferous portion of the Old Red Sandstone which I
purpose first to describe, and which will yet come to be generally
regarded as an independent formation, as unequivocally
characterized by its organic remains as the formations either above
or below it.
[G] Dr. Hibbert, whose researches among the limestones of Burdie House have
been of such importance to Geology, was of this opinion. I find it also expressed in
the admirable geological appendix affixed by the Messrs. Anderson to their Guide
to the Highlands and Islands of Scotland. "No beds of real coal," say these
gentlemen, "have been discovered in Caithness; and it would thus appear that the
middle schistose system of the county, containing the fossil fish, is in geological
character and position intermediate between the Old and New Red Sandstone
formations, but not identical with the Carboniferous Limestone, or the true Coal
Measures, although probably occupying the place of one or other of them."—p.
198.

The county of Sutherland stretches across the island from the


German to the Atlantic Ocean, and presents, throughout its entire
extent,—except where a narrow strip of the Oolitic formation runs
along its eastern coast, and a broken belt of Old Red Sandstone tips
its capes and promontories on the west,—a broken and tumultuous
sea of primary hills. Scarce any of our other Scottish counties are so
exclusively Highland, nor are there any of them in which the
precipices are more abrupt, the valleys more deep, the rivers more
rapid, or the mountains piled into more fantastic groups and masses.
The traveller passes into Caithness, and finds himself surrounded by
scenery of an aspect so entirely dissimilar, that no examination of
the rocks is necessary to convince him of a geological difference of
structure. An elevated and uneven plain spreads around and before
him, league beyond league, in tame and unvaried uniformity,—its
many hollows darkened by morasses, over which the intervening
eminences rise in the form rather of low moory swellings, than of
hills,—its coasts walled round by cliffs of gigantic altitude, that
elevate the district at one huge stride from the level of the sea, and
skirted by vast stacks and columns of rock, that stand out like the
advanced pickets of the land amid the ceaseless turmoil of the
breakers. The district, as shown on the map, presents nearly a
triangular form—the Pentland Frith and the German Ocean
describing two of its sides, while the base is formed by the line of
boundary which separates it from the county of Sutherland.
Now, in a geological point of view, this angle may be regarded as
a vast pyramid, rising perpendicularly from the basis furnished by
the primary rocks of the latter county, and presenting newer beds
and strata as we ascend, until we reach the apex. The line from
south to north in the angle—from Morvheim to Dunnet-head—
corresponds to the line of ascent from the top to the bottom of the
pyramid. The first bed, reckoning from the base upwards,—the
ground tier of the masonry, if I may so speak,—is the great
conglomerate. It runs along the line of boundary from sea to sea,—
from the Ord of Caithness on the east, to Portskerry on the north;
and rises, as it approaches the primary hills of Sutherland, into a
lofty mountain chain of bold and serrated outline, which attains its
greatest elevation in the hill of Morvheim. This great conglomerate
bed, the base of the system, is represented in the Cromarty section,
under the Northern Sutor, by a bed two hundred and fifteen feet in
thickness. The second tier of masonry in the pyramid, and which
also runs in a nearly parallel line from sea to sea, is composed
mostly of a coarse red and yellowish sandstone, with here and there
beds of pebbles enclosed, and here and there deposits of green
earth and red marl. It has its representative in the Cromarty section,
in a bed of red and yellow arenaceous stone, one hundred and
fourteen feet six inches in thickness. These two inferior beds possess
but one character,—they are composed of the same materials, with
merely this difference, that the rocks which have been broken into
pebbles for the construction of the one, have been ground into sand
for the composition of the other. Directly over them, the middle
portion of the pyramid is occupied by an enormous deposit of dark-
colored bituminous schist, slightly micaceous, calcareous, or semi-
calcareous,—here and there interlaced with veins of carbonate of
lime,—here and there compact and highly siliceous,—and bearing in
many places a mineralogical character difficult to be distinguished
from that at one time deemed peculiar to the harder grauwacke
schists. The Caithness flagstones, so extensively employed in paving
the footways of our larger towns, are furnished by this immense
middle tier or belt, and represent its general appearance. From its
lowest to its highest beds it is charged with fossil fish and obscure
vegetable impressions; and we find it represented in the Cromarty
section by alternating bands of sandstones, stratified clays, and
bituminous and nodular limestones, which form altogether a bed
three hundred and fifty-five feet in thickness; nor does this bed lack
its organisms, animal and vegetable, generically identical with those
of Caithness. The apex of the pyramid is formed of red mouldering
sandstones and mottled marls, which exhibit their uppermost strata
high over the eddies of the Pentland Frith, in the huge precipices of
Dunnet-head, and which are partially represented in the Cromarty
section by an unfossiliferous sandstone bed of unascertained
thickness; but which can be traced for about eighty feet from the
upper limestones and stratified clays of the middle member, until lost
in overlying beds of sand and shingle.
I am particular, at the risk, I am afraid, of being tedious, in thus
describing the Geology of this northern county, and of the Cromarty
section, which represents and elucidates it. They illustrate more than
the formations of two insulated districts: they represent also a vast
period of time in the history of the globe. The pyramid, with its three
huge bars, its foundations of granitic rock, its base of red
conglomerate, its central band of dark-colored schist, and its lighter
tinted apex of sandstone, is inscribed from bottom to top, like an
Egyptian obelisk, with a historical record. The upper and lower
sections treat of tempests and currents—the middle is "written
within and without" with wonderful narratives of animal life; and yet
the whole, taken together, comprises but an earlier portion of that
chronicle of existences and events furnished by the Old Red
Sandstone. It is, however, with this earlier portion that my
acquaintance is most minute.
My first statement regarding it must be much the reverse of the
borrowed one with which this chapter begins. The fossils are
remarkably numerous, and in a state of high preservation. I have a
hundred solid proofs by which to establish the truth of the assertion,
within less than a yard of me. Half my closet walls are covered with
the peculiar fossils of the Lower Old Red Sandstone; and certainly a
stranger assemblage of forms have rarely been grouped together;—
creatures whose very type is lost, fantastic and uncouth, and which
puzzle the naturalist to assign them even their class;—boat-like
animals, furnished with oars and a rudder;—fish plated over, like the
tortoise, above and below, with a strong armor of bone, and
furnished with but one solitary rudder-like fin; other fish less
equivocal in their form, but with the membranes of their fins thickly
covered with scales;—creatures bristling over with thorns; others
glistening in an enamelled coat, as if beautifully japanned—the tail,
in every instance among the less equivocal shapes, formed not
equally, as in existing fish, on each side the central vertebral column,
but chiefly on the lower side—the column sending out its diminished
vertebræ to the extreme termination of the fin. All the forms testify
of a remote antiquity—of a period whose "fashions have passed
away." The figures on a Chinese vase or an Egyptian obelisk are
scarce more unlike what now exists in nature, than the fossils of the
Lower Old Red Sandstone.
Geology, of all the sciences, addresses itself most powerfully to
the imagination, and hence one main cause of the interest which it
excites. Ere setting ourselves minutely to examine the peculiarities of
these creatures, it would be perhaps well that the reader should
attempt realizing the place of their existence, and relatively the time
—not of course with regard to dates and eras, for the geologist has
none to reckon by, but with respect to formations. They were the
denizens of the same portion of the globe which we ourselves
inhabit, regarded not as a tract of country, but as a piece of ocean
crossed by the same geographical lines of latitude and longitude.
Their present place of sepulture in some localities, had there been
no denudation, would have been raised high over the tops of our
loftiest hills—at least a hundred feet over the conglomerates which
form the summit of Morvheim, and more than a thousand feet over
the snow-capped Ben Wyvis. Geology has still greater wonders. I
have seen belemnites of the Oolite—comparatively a modern
formation—which had been dug out of the sides of the Himalaya
mountains, seventeen thousand feet over the level of the sea. But
let us strive to carry our minds back, not to the place of sepulture of
these creatures, high in the rocks,—though that I shall afterwards
attempt minutely to describe,—but to the place in which they lived,
long ere the sauroid fishes of Burdie House had begun to exist, or
the corallines of the mountain limestone had spread out their
multitudinous arms in a sea gradually shallowing, and out of which
the land had already partially emerged.
A continuous ocean spreads over the space now occupied by the
British islands: in the tract covered by the green fields and brown
moors of our own country, the bottom, for a hundred yards
downwards, is composed of the debris of rolled pebbles and coarse
sand intermingled, long since consolidated into the lower member of
the Old Red Sandstone; the upper surface is composed of banks of
sand, mud, and clay; and the sea, swarming with animal life, flows
over all. My present object is to describe the inhabitants of that sea.
Of these, the greater part yet discovered have been named by
Agassiz, the highest authority as an ichthyologist in Europe or the
world, and in whom the scarcely more celebrated Cuvier recognized
a naturalist in every respect worthy to succeed him. The comparative
amount of the labors of these two great men in fossil ichthyology,
and the amazing acceleration which has taken place within the last
few years in the progress of geological science, are illustrated
together, and that very strikingly, by the following interesting fact—a
fact derived directly from Agassiz himself, and which must be new to
the great bulk of my readers. When Cuvier closed his researches in
this department, he had named and described, for the guidance of
the geologist, ninety-two distinct species of fossil fish; nor was it
then known that the entire geological scale, from the Upper Tertiary
to the Grauwacke inclusive, contained more. Agassiz commenced his
labors; and, in a period of time little exceeding fourteen years, he
has raised the number of species from ninety-two to sixteen
hundred. And this number, great as it is, is receiving accessions
almost every day. In his late visit to Scotland, he found eleven new
species, and one new genus, in the collection of Lady Gumming of
Altyre, all from the upper beds of that lower member of the Old Red
Sandstone represented by the dark-colored schists and inferior
sandstones of Caithness. He found forty-two new species more in a
single collection in Ireland, furnished by the Mountain Limestone of
Armagh.
Some of my humbler readers may possibly be repelled by his
names; they are, like all names in science, unfamiliar in their respect
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

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.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebooknice.com

You might also like