Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (4 votes)
111 views

Programming Language Concepts Peter Sestoft 2024 Scribd Download

Programming

Uploaded by

ydojkayalr
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (4 votes)
111 views

Programming Language Concepts Peter Sestoft 2024 Scribd Download

Programming

Uploaded by

ydojkayalr
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

Download the full version of the textbook now at textbookfull.

com

Programming Language Concepts Peter Sestoft

https://textbookfull.com/product/programming-
language-concepts-peter-sestoft/

Explore and download more textbook at https://textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Java Precisely third edition The MIT Press Peter Sestoft

https://textbookfull.com/product/java-precisely-third-edition-the-mit-
press-peter-sestoft/

textbookfull.com

The Language of Surrealism Peter Stockwell

https://textbookfull.com/product/the-language-of-surrealism-peter-
stockwell/

textbookfull.com

Programming PHP 4th Edition Peter Macintyre

https://textbookfull.com/product/programming-php-4th-edition-peter-
macintyre/

textbookfull.com

Emerging Research in Computing, Information, Communication


and Applications: ERCICA 2018, Volume 1 N. R. Shetty

https://textbookfull.com/product/emerging-research-in-computing-
information-communication-and-applications-ercica-2018-volume-1-n-r-
shetty/
textbookfull.com
Internet Science 4th International Conference INSCI 2017
Thessaloniki Greece November 22 24 2017 Proceedings 1st
Edition Ioannis Kompatsiaris Et Al. (Eds.)
https://textbookfull.com/product/internet-science-4th-international-
conference-insci-2017-thessaloniki-greece-
november-22-24-2017-proceedings-1st-edition-ioannis-kompatsiaris-et-
al-eds/
textbookfull.com

3D Cell Culture Methods and Protocols Methods in Molecular


Biology 2764 2nd Edition Zuzana Sumbalova Koledova

https://textbookfull.com/product/3d-cell-culture-methods-and-
protocols-methods-in-molecular-biology-2764-2nd-edition-zuzana-
sumbalova-koledova/
textbookfull.com

Brain Computer Interfaces 2 Technology and Applications


1st Edition Maureen Clerc

https://textbookfull.com/product/brain-computer-
interfaces-2-technology-and-applications-1st-edition-maureen-clerc/

textbookfull.com

Diagnostic Molecular Biology Chang-Hui Shen

https://textbookfull.com/product/diagnostic-molecular-biology-chang-
hui-shen/

textbookfull.com

Alessandro Torlonia: The Pope’s Banker 1st Edition Daniela


Felisini (Auth.)

https://textbookfull.com/product/alessandro-torlonia-the-popes-
banker-1st-edition-daniela-felisini-auth/

textbookfull.com
Environmental Public Policy Making Exposed: A Guide for
Decision Makers and Interested Citizens Cynthia H. Stahl

https://textbookfull.com/product/environmental-public-policy-making-
exposed-a-guide-for-decision-makers-and-interested-citizens-cynthia-h-
stahl/
textbookfull.com
Undergraduate Topics in Computer Science

Peter Sestoft

Programming
Language
Concepts
Second Edition
Undergraduate Topics in Computer Science

Series editor
Ian Mackie

Advisory Board
Samson Abramsky, University of Oxford, Oxford, UK
Karin Breitman, Pontifical Catholic University of Rio de Janeiro, Rio de Janeiro, Brazil
Chris Hankin, Imperial College London, London, UK
Dexter C. Kozen, Cornell University, Ithaca, USA
Andrew Pitts, University of Cambridge, Cambridge, UK
Hanne Riis Nielson, Technical University of Denmark, Kongens Lyngby, Denmark
Steven S. Skiena, Stony Brook University, Stony Brook, USA
Iain Stewart, University of Durham, Durham, UK
Undergraduate Topics in Computer Science (UTiCS) delivers high-quality instruc-
tional content for undergraduates studying in all areas of computing and information
science. From core foundational and theoretical material to final-year topics and
applications, UTiCS books take a fresh, concise, and modern approach and are ideal
for self-study or for a one- or two-semester course. The texts are all authored by
established experts in their fields, reviewed by an international advisory board, and
contain numerous examples and problems. Many include fully worked solutions.

More information about this series at http://www.springer.com/series/7592


Peter Sestoft

Programming Language
Concepts
Second Edition

With a chapter by Niels Hallenberg

123
Peter Sestoft
IT University of Copenhagen, Computer
Science Department
Copenhagen
Denmark

ISSN 1863-7310 ISSN 2197-1781 (electronic)


Undergraduate Topics in Computer Science
ISBN 978-3-319-60788-7 ISBN 978-3-319-60789-4 (eBook)
DOI 10.1007/978-3-319-60789-4
Library of Congress Control Number: 2017949164

1st edition: © Springer-Verlag London 2012


2nd edition: © Springer International Publishing AG 2017
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part
of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations,
recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission
or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar
methodology now known or hereafter developed.
The use of general descriptive names, registered names, trademarks, service marks, etc. in this
publication does not imply, even in the absence of a specific statement, that such names are exempt from
the relevant protective laws and regulations and therefore free for general use.
The publisher, the authors and the editors are safe to assume that the advice and information in this
book are believed to be true and accurate at the date of publication. Neither the publisher nor the
authors or the editors give a warranty, express or implied, with respect to the material contained herein or
for any errors or omissions that may have been made. The publisher remains neutral with regard to
jurisdictional claims in published maps and institutional affiliations.

Printed on acid-free paper

This Springer imprint is published by Springer Nature


The registered company is Springer International Publishing AG
The registered company address is: Gewerbestrasse 11, 6330 Cham, Switzerland
Preface

This book takes an operational approach to programming language concepts,


studying those concepts in interpreters and compilers for some toy languages, and
pointing out their relations to real-world programming languages.

What is Covered

Topics covered include abstract and concrete syntax; functional and imperative
programming languages; interpretation, type checking, and compilation; peep-hole
optimizations; abstract machines, automatic memory management and garbage
collection; the Java Virtual Machine and Microsoft’s .NET Common Language
Runtime; and real machine code for the x86 architecture.
Some effort is made throughout to put programming language concepts into their
historical context, and to show how the concepts surface in languages that the
students are assumed to know already; primarily Java or C#.
We do not cover regular expressions and parser construction in much detail. For
this purpose, we refer to Torben Mogensen’s textbook; see Chap. 3 and its references.
Apart from various updates, this second edition adds a synthesis chapter, con-
tributed by Niels Hallenberg, that presents a compiler from a small functional
language called micro-SML to an abstract machine; and a chapter that presents a
compiler from a C subset called micro-C to real x86 machine code.

Why Virtual Machines?

The book’s emphasis is on virtual stack machines and their intermediate languages,
often known as bytecode. Virtual machines are machine-like enough to make the
central purpose and concepts of compilation and code generation clear, yet they are
much simpler than present-day microprocessors such as Intel i7 and similar.

v
vi Preface

Full understanding of performance issues in real microprocessors, with deep


pipelines, register renaming, out-of-order execution, branch prediction, translation
lookaside buffers and so on, requires a very detailed study of their architecture,
usually not conveyed by compiler textbooks anyway. Certainly, a mere under-
standing of the instruction set, such as x86, conveys little information about
whether code will be fast or not.
The widely used object-oriented languages Java and C# are rather far removed
from the real hardware, and are most conveniently explained in terms of their
virtual machines: the Java Virtual Machine and Microsoft’s Common Language
Infrastructure. Understanding the workings and implementation of these virtual
machines sheds light on efficiency issues, design decisions, and inherent limitations
in Java and C#. To understand memory organization of classic imperative lan-
guages, we also study a small subset of C with arrays, pointer arithmetics, and
recursive functions. We present a compiler from micro-C to an abstract machine,
and this smoothly leads to a simple compiler for real x86 hardware.

Why F#?

We use the functional language F# as presentation language throughout, to illustrate


programming language concepts, by implementing interpreters and compilers for
toy languages. The idea behind this is twofold.
First, F# belongs to the ML family of languages and is ideal for implementing
interpreters and compilers because it has datatypes and pattern matching and is
strongly typed. This leads to a brevity and clarity of examples that cannot be
matched by languages without these features.
Secondly, the active use of a functional language is an attempt to add a new
dimension to students’ world view, to broaden their imagination. The prevalent
single-inheritance class-based object-oriented programming languages (namely,
Java and C#) are very useful and versatile languages. But they have come to
dominate computer science education to a degree where students may become
unable to imagine other programming tools, especially to use a completely different
paradigm. Knowledge of a functional language will make the student a better
designer and programmer, whether in Java, C# or C, and will prepare him or her to
adapt to the programming languages of the future.
For instance, the so-called generic types and methods appeared in Java and C# in
2004, but have been part of other languages, most notably ML, since 1978.
Similarly, garbage collection has been used in functional languages since Lisp in
1960, but entered mainstream use more than 30 years later, with Java. Finally,
functional programming features were added to C# in 2010 and to Java in 2014.
Appendix A gives a brief introduction to those parts of F# used in this book.
Students who do not know F# should learn those parts during the first-third of this
course, using the appendix or a textbook such as Hansen and Rischel or a reference
such as Syme et al.; see Appendix A and its references.
Preface vii

Supporting Material

There are practical exercises at the end of each chapter. Moreover, the book is
accompanied by complete implementations in F# of lexer and parser specifications,
abstract syntaxes, interpreters, compilers, and runtime systems (abstract machines,
in Java and C) for a range of toy languages. This material, and lecture slides in PDF,
are available separately from the book’s homepage: http://www.itu.dk/people/
sestoft/plc/.

Acknowledgements

This book originated as lecture notes for courses held at the IT University of
Copenhagen, Denmark. I would like to thank Andrzej Wasowski, Ken Friis Larsen,
Hannes Mehnert, David Raymond Christiansen and past students, in particular
Niels Kokholm, Mikkel Bundgaard, and Ahmad Salim Al-Sibahi, who pointed out
mistakes and made suggestions on examples and presentation in earlier drafts. Niels
Kokholm wrote an early version of the machine code generating micro-C compiler
presented in Chap. 14. Thanks to Luca Boasso, Mikkel Riise Lund, and Paul
Jurczak for pointing out misprints and unclarities in the first edition. I owe a lasting
debt to Neil D. Jones and Mads Tofte who influenced my own view of program-
ming languages and the presentation of programming language concepts.
Niels Hallenberg deserves a special thanks for contributing all of Chap. 13 to this
second edition.

Copenhagen, Denmark Peter Sestoft


Contents

1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1 Files for This Chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Meta Language and Object Language . . . . . . . . . . . . . . . . . . . 1
1.3 A Simple Language of Expressions . . . . . . . . . . . . . . . . . . . . 2
1.3.1 Expressions Without Variables . . . . . . . . . . . . . . . . . 2
1.3.2 Expressions with Variables . . . . . . . . . . . . . . . . . . . . 3
1.4 Syntax and Semantics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.5 Representing Expressions by Objects . . . . . . . . . . . . . . . . . . . 6
1.6 The History of Programming Languages . . . . . . . . . . . . . . . . . 8
1.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2 Interpreters and Compilers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.1 Files for This Chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.2 Interpreters and Compilers . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.3 Scope and Bound and Free Variables . . . . . . . . . . . . . . . . . . . 14
2.3.1 Expressions with Let-Bindings and Static Scope . . . . . 15
2.3.2 Closed Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.3.3 The Set of Free Variables . . . . . . . . . . . . . . . . . . . . . 17
2.3.4 Substitution: Replacing Variables by Expressions . . . . 17
2.4 Integer Addresses Instead of Names . . . . . . . . . . . . . . . . . . . . 20
2.5 Stack Machines for Expression Evaluation . . . . . . . . . . . . . . . 22
2.6 Postscript, a Stack-Based Language . . . . . . . . . . . . . . . . . . . . 23
2.7 Compiling Expressions to Stack Machine Code . . . . . . . . . . . 25
2.8 Implementing an Abstract Machine in Java . . . . . . . . . . . . . . . 26
2.9 History and Literature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
2.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3 From Concrete Syntax to Abstract Syntax . . . . . . . . . . . . . . . . . . . 31
3.1 Preparatory Reading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.2 Lexers, Parsers, and Generators . . . . . . . . . . . . . . . . . . . . . . . 32

ix
x Contents

3.3 Regular Expressions in Lexer Specifications . . . . . . . . . . . . . . 33


3.4 Grammars in Parser Specifications . . . . . . . . . . . . . . . . . . . . . 34
3.5 Working with F# Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.6 Using fslex and fsyacc . . . . . . . . . . . . . . . . . . . . . . . . . . 36
3.6.1 Installing and Using fslex and fsyacc . . . . . . . . . 37
3.6.2 Parser Specification for Expressions . . . . . . . . . . . . . . 37
3.6.3 Lexer Specification for Expressions . . . . . . . . . . . . . . 38
3.6.4 The ExprPar.fsyacc.output File Generated
by fsyacc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
3.6.5 Exercising the Parser Automaton . . . . . . . . . . . . . . . . 44
3.6.6 Shift/Reduce Conflicts . . . . . . . . . . . . . . . . . . . . . . . 45
3.7 Lexer and Parser Specification Examples . . . . . . . . . . . . . . . . 47
3.7.1 A Small Functional Language . . . . . . . . . . . . . . . . . . 47
3.7.2 Lexer and Parser Specifications for Micro-SQL . . . . . 48
3.8 A Handwritten Recursive Descent Parser . . . . . . . . . . . . . . . . 48
3.9 JavaCC: Lexer-, Parser-, and Tree Generator . . . . . . . . . . . . . 50
3.10 History and Literature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
3.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
4 A First-Order Functional Language . . . . . . . . . . . . . . . . . . . . . . . . 59
4.1 Files for This Chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
4.2 Examples and Abstract Syntax . . . . . . . . . . . . . . . . . . . . . . . . 60
4.3 Run-Time Values: Integers and Closures . . . . . . . . . . . . . . . . 61
4.4 A Simple Environment Implementation . . . . . . . . . . . . . . . . . 62
4.5 Evaluating the Functional Language . . . . . . . . . . . . . . . . . . . . 62
4.6 Evaluation Rules for Micro-ML . . . . . . . . . . . . . . . . . . . . . . . 64
4.7 Static Scope and Dynamic Scope . . . . . . . . . . . . . . . . . . . . . . 66
4.8 Type-Checking an Explicitly Typed Language . . . . . . . . . . . . 68
4.9 Type Rules for Monomorphic Types . . . . . . . . . . . . . . . . . . . 70
4.10 Static Typing and Dynamic Typing . . . . . . . . . . . . . . . . . . . . 72
4.10.1 Dynamic Typing in Java
and C# Array Assignment . . . . . . . . . ............ 73
4.10.2 Dynamic Typing in Non-generic
Collection Classes . . . . . . . . . . . . . . . . . . . . . . . . . . 74
4.11 History and Literature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
4.12 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
5 Higher-Order Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
5.1 Files for This Chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
5.2 Higher-Order Functions in F# . . . . . . . . . . . . . . . . . . . . . . . . 81
5.3 Higher-Order Functions in the Mainstream . . . . . . . . . . . . . . . 82
5.3.1 Higher-Order Functions in Java 5 . . . . . . . . . . . . . . . 82
5.3.2 Higher-Order Functions in Java 8 . . . . . . . . . . . . . . . 84
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
Contents xi

5.3.3 Higher-Order Functions in C# . . . . . . . . . . . . . . . . . . 85


5.3.4 Google MapReduce . . . . . . . . . . . . . . . . . . . . . . . . . 86
5.4 A Higher-Order Functional Language . . . . . . . . . . . . . . . . . . . 86
5.5 Eager and Lazy Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . 87
5.6 The Lambda Calculus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
5.7 History and Literature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
5.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
6 Polymorphic Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
6.1 Files for This Chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
6.2 ML-Style Polymorphic Types . . . . . . . . . . . . . . . . . . . . . . . . 97
6.2.1 Informal Explanation of ML Type Inference . . . . . . . 98
6.2.2 Which Type Parameters May Be Generalized . . . . . . . 100
6.3 Type Rules for Polymorphic Types . . . . . . . . . . . . . . . . . . . . 101
6.4 Implementing ML Type Inference . . . . . . . . . . . . . . . . . . . . . 103
6.4.1 Type Equation Solving by Unification . . . . . . . . . . . . 106
6.4.2 The Union-Find Algorithm . . . . . . . . . . . . . . . . . . . . 106
6.4.3 The Complexity of ML-Style Type Inference . . . . . . . 107
6.5 Generic Types in Java and C# . . . . . . . . . . . . . . . . . . . . . . . . 108
6.6 Co-Variance and Contra-Variance . . . . . . . . . . . . . . . . . . . . . 110
6.6.1 Java Wildcards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
6.6.2 C# Variance Declarations . . . . . . . . . . . . . . . . . . . . . 112
6.6.3 The Variance Mechanisms of Java and C# . . . . . . . . . 113
6.7 History and Literature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
6.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
7 Imperative Languages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
7.1 Files for This Chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
7.2 A Naive Imperative Language . . . . . . . . . . . . . . . . . . . . . . . . 120
7.3 Environment and Store . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
7.4 Parameter Passing Mechanisms . . . . . . . . . . . . . . . . . . . . . . . 122
7.5 The C Programming Language . . . . . . . . . . . . . . . . . . . . . . . 124
7.5.1 Integers, Pointers and Arrays in C . . . . . . . . . . . . . . . 124
7.5.2 Type Declarations in C . . . . . . . . . . . . . . . . . . . . . . . 126
7.6 The Micro-C Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
7.6.1 Interpreting Micro-C . . . . . . . . . . . . . . . . . . . . . . . . . 129
7.6.2 Example Programs in Micro-C . . . . . . . . . . . . . . . . . 129
7.6.3 Lexer Specification for Micro-C . . . . . . . . . . . . . . . . 130
7.6.4 Parser Specification for Micro-C . . . . . . . . . . . . . . . . 132
7.7 Notes on Strachey’s Fundamental Concepts . . . . . . . . . . . . . . 134
7.8 History and Literature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
7.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
xii Contents

8 Compiling Micro-C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141


8.1 Files for This Chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
8.2 An Abstract Stack Machine . . . . . . . . . . . . . . . . . . . . . . . . . . 142
8.2.1 The State of the Abstract Machine . . . . . . . . . . . . . . . 142
8.2.2 The Abstract Machine Instruction Set . . . . . . . . . . . . 143
8.2.3 The Symbolic Machine Code . . . . . . . . . . . . . . . . . . 145
8.2.4 The Abstract Machine Implemented in Java . . . . . . . . 145
8.2.5 The Abstract Machine Implemented in C . . . . . . . . . . 147
8.3 The Structure of the Stack at Run-Time . . . . . . . . . . . . . . . . . 147
8.4 Compiling Micro-C to Abstract Machine Code . . . . . . . . . . . . 148
8.5 Compilation Schemes for Micro-C . . . . . . . . . . . . . . . . . . . . . 149
8.6 Compilation of Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
8.7 Compilation of Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . 153
8.8 Compilation of Access Expressions . . . . . . . . . . . . . . . . . . . . 154
8.9 Compilation to Real Machine Code . . . . . . . . . . . . . . . . . . . . 155
8.10 History and Literature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
8.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
9 Real-World Abstract Machines . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
9.1 Files for This Chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
9.2 An Overview of Abstract Machines . . . . . . . . . . . . . . . . . . . . 161
9.3 The Java Virtual Machine (JVM) . . . . . . . . . . . . . . . . . . . . . . 163
9.3.1 The JVM Run-Time State . . . . . . . . . . . . . . . . . . . . . 163
9.3.2 The JVM Bytecode . . . . . . . . . . . . . . . . . . . . . . . . . . 165
9.3.3 The Contents of JVM Class Files . . . . . . . . . . . . . . . 165
9.3.4 Bytecode Verification . . . . . . . . . . . . . . . . . . . . . . . . 169
9.4 The Common Language Infrastructure (CLI) . . . . . . . . . . . . . 169
9.5 Generic Types in CLI and JVM . . . . . . . . . . . . . . . . . . . . . . . 172
9.5.1 A Generic Class in Bytecode . . . . . . . . . . . . . . . . . . . 173
9.5.2 Consequences for Java . . . . . . . . . . . . . . . . . . . . . . . 174
9.6 Decompilers for Java and C# . . . . . . . . . . . . . . . . . . . . . . . . . 175
9.7 Just-in-Time Compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
9.8 History and Literature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
9.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
10 Garbage Collection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
10.1 Files for This Chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
10.2 Predictable Lifetime and Stack Allocation . . . . . . . . . . . . . . . . 183
10.3 Unpredictable Lifetime and Heap Allocation . . . . . . . . . . . . . . 184
10.4 Allocation in a Heap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
10.5 Garbage Collection Techniques . . . . . . . . . . . . . . . . . . . . . . . 186
10.5.1 The Heap and the Freelist . . . . . . . . . . . . . . . . . . . . . 187
10.5.2 Garbage Collection by Reference Counting . . . . . . . . 187
Contents xiii

10.5.3 Mark-Sweep Collection . . . . . . . . . . . . . . . . . . . . . . . 188


10.5.4 Two-Space Stop-and-Copy Collection . . . . . . . . . . . . 189
10.5.5 Generational Garbage Collection . . . . . . . . . . . . . . . . 191
10.5.6 Conservative Garbage Collection . . . . . . . . . . . . . . . . 192
10.5.7 Garbage Collectors Used in Existing Systems . . . . . . 192
10.6 Programming with a Garbage Collector . . . . . . . . . . . . . . . . . 193
10.6.1 Memory Leaks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
10.6.2 Finalizers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
10.6.3 Calling the Garbage Collector . . . . . . . . . . . . . . . . . . 194
10.7 Implementing a Garbage Collector in C . . . . . . . . . . . . . . . . . 195
10.7.1 The List-C Language . . . . . . . . . . . . . . . . . . . . . . . . 195
10.7.2 The List-C Machine . . . . . . . . . . . . . . . . . . . . . . . . . 198
10.7.3 Distinguishing References from Integers . . . . . . . . . . 198
10.7.4 Memory Structures in the Garbage Collector . . . . . . . 199
10.7.5 Actions of the Garbage Collector . . . . . . . . . . . . . . . . 200
10.8 History and Literature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
10.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
11 Continuations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
11.1 Files for This Chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
11.2 Tail-Calls and Tail-Recursive Functions . . . . . . . . . . . . . . . . . 210
11.2.1 A Recursive but Not Tail-Recursive Function . . . . . . 210
11.2.2 A Tail-Recursive Function . . . . . . . . . . . . . . . . . . . . 210
11.2.3 Which Calls Are Tail Calls? . . . . . . . . . . . . . . . . . . . 212
11.3 Continuations and Continuation-Passing Style . . . . . . . . . . . . . 212
11.3.1 Writing a Function in Continuation-Passing Style . . . . 213
11.3.2 Continuations and Accumulating Parameters . . . . . . . 214
11.3.3 The CPS Transformation . . . . . . . . . . . . . . . . . . . . . . 214
11.4 Interpreters in Continuation-Passing Style . . . . . . . . . . . . . . . . 215
11.4.1 A Continuation-Based Functional Interpreter . . . . . . . 215
11.4.2 Tail Position and Continuation-Based Interpreters . . . . 217
11.4.3 A Continuation-Based Imperative Interpreter . . . . . . . 217
11.5 The Frame Stack and Continuations . . . . . . . . . . . . . . . . . . . . 219
11.6 Exception Handling in a Stack Machine . . . . . . . . . . . . . . . . . 220
11.7 Continuations and Tail Calls . . . . . . . . . . . . . . . . . . . . . . . . . 221
11.8 Callcc: Call with Current Continuation . . . . . . . . . . . . . . . . . . 223
11.9 Continuations and Backtracking . . . . . . . . . . . . . . . . . . . . . . . 224
11.9.1 Expressions in Icon . . . . . . . . . . . . . . . . . . . . . . . . . 224
11.9.2 Using Continuations to Implement Backtracking . . . . 225
11.10 History and Literature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
11.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
xiv Contents

12 A Locally Optimizing Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . 233


12.1 Files for This Chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
12.2 Generating Optimized Code Backwards . . . . . . . . . . . . . . . . . 233
12.3 Backwards Compilation Functions . . . . . . . . . . . . . . . . . . . . . 234
12.3.1 Optimizing Expression Code While Generating It . . . . 236
12.3.2 The Old Compilation of Jumps . . . . . . . . . . . . . . . . . 238
12.3.3 Optimizing a Jump While Generating It . . . . . . . . . . . 238
12.3.4 Optimizing Logical Expression Code . . . . . . . . . . . . . 240
12.3.5 Eliminating Dead Code . . . . . . . . . . . . . . . . . . . . . . . 242
12.3.6 Optimizing Tail Calls . . . . . . . . . . . . . . . . . . . . . . . . 242
12.3.7 Remaining Deficiencies of the Generated Code . . . . . 245
12.4 Other Optimizations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
12.5 A Command Line Compiler for Micro-C . . . . . . . . . . . . . . . . 247
12.6 History and Literature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
12.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
13 Compiling Micro-SML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
13.1 Files for This Chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
13.2 Grammar for Micro-SML . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
13.2.1 Example Programs . . . . . . . . . . . . . . . . . . . . . . . . . . 255
13.2.2 Abstract Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
13.2.3 Prettyprinting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
13.2.4 Tail Calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
13.2.5 Free Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
13.3 Type Inference for Micro-SML . . . . . . . . . . . . . . . . . . . . . . . 259
13.3.1 Type Inference Implementation . . . . . . . . . . . . . . . . . 261
13.3.2 Annotated Type Information . . . . . . . . . . . . . . . . . . . 263
13.4 Interpreting Micro-SML . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
13.4.1 Continuations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
13.4.2 Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
13.4.3 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
13.4.4 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
13.5 Compiling Micro-SML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
13.5.1 Extensions to Abstract Machine Instruction Set . . . . . 269
13.5.2 Compilation of Primitive Micro-SML Expressions . . . 272
13.5.3 Compilation of Variable Access . . . . . . . . . . . . . . . . 273
13.5.4 Compilation of Value Declarations . . . . . . . . . . . . . . 274
13.5.5 Compilation of Let Expressions and Functions . . . . . . 277
13.5.6 Compilation of Exceptions . . . . . . . . . . . . . . . . . . . . 278
13.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
Contents xv

14 Real Machine Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283


14.1 Files for This Chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
14.2 The x86 Processor Family . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
14.2.1 Evolution of the x86 Processor Family . . . . . . . . . . . 284
14.2.2 Registers of the x86 Architecture . . . . . . . . . . . . . . . . 285
14.2.3 The x86 Instruction Set . . . . . . . . . . . . . . . . . . . . . . . 287
14.2.4 The x86 Stack Layout . . . . . . . . . . . . . . . . . . . . . . . . 288
14.2.5 An Assembly Code Example . . . . . . . . . . . . . . . . . . . 288
14.3 Compiling Micro-C to x86 Code . . . . . . . . . . . . . . . . . . . . . . 290
14.3.1 Compilation Strategy . . . . . . . . . . . . . . . . . . . . . . . . 291
14.3.2 Representing x86 Machine Code in the Compiler . . . . 292
14.3.3 Stack Layout for Micro-C x86 Code . . . . . . . . . . . . . 293
14.4 The micro-C x86 Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . 295
14.5 Compilation Schemes for Micro-C . . . . . . . . . . . . . . . . . . . . . 296
14.6 Compilation of Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
14.7 Compilation of Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . 297
14.8 Compilation of Access Expressions . . . . . . . . . . . . . . . . . . . . 300
14.9 Choosing Target Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
14.10 Improving the Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
14.11 History and Literature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
14.12 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
Appendix A: Crash Course in F# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
Chapter 1
Introduction

This chapter introduces the approach taken and the plan followed in this book. We
show how to represent arithmetic expressions and other program fragments as data
structures in F# as well as Java, and how to compute with such program fragments.
We also introduce various basic concepts of programming languages.

1.1 Files for This Chapter

File Contents
Intro/Intro1.fs simple expressions without variables, in F#
Intro/Intro2.fs simple expressions with variables, in F#
Intro/SimpleExpr.java simple expressions with variables, in Java

1.2 Meta Language and Object Language

In linguistics and mathematics, an object language is a language we study (such


as C++ or Latin) and the meta language is the language in which we conduct our
discussions (such as Danish or English). Throughout this book we shall use the F#
language as the meta language. We could use Java or C#, but that would be more
cumbersome because of the lack of pattern matching.
F# is a strict, strongly typed functional programming language in the ML family.
Appendix A presents the basic concepts of F#: value, variable, binding, type, tuple,

© Springer International Publishing AG 2017 1


P. Sestoft, Programming Language Concepts, Undergraduate Topics
in Computer Science, DOI 10.1007/978-3-319-60789-4_1
2 1 Introduction

function, recursion, list, pattern matching, and datatype. Several books give a more
detailed introduction, including Hansen and Rischel [1] and Syme et al. [6].
It is convenient to run F# interactive sessions inside Microsoft Visual Studio (under
MS Windows), or executing fsharpi interactive sessions using Mono (under Linux
and MacOS X); see Appendix A.

1.3 A Simple Language of Expressions

As an example object language we start by studying a simple language of expressions,


with constants, variables (of integer type), let-bindings, nested scope, and operators;
see files Intro1.fs and Intro2.fs.

1.3.1 Expressions Without Variables

First, let us consider expressions consisting only of integer constants and two-
argument (dyadic) operators such as (+) and (*). We represent an expression as a
term of an F# datatype expr, where integer constants are represented by constructor
CstI, and operator applications are represented by constructor Prim:
type expr =
| CstI of int
| Prim of string * expr * expr

A value of type expr is an abstract syntax tree that represents an expression. Here
are some example expressions and their representations as expr values:

Expression Representation in type expr


17 CstI 17
3−4 Prim("-", CstI 3, CstI 4)
7 · 9 + 10 Prim("+", Prim("*", CstI 7, CstI 9), CstI 10)

An expression in this representation can be evaluated to an integer by a function


eval : expr -> int that uses pattern matching to distinguish the various
forms of expression. Note that to evaluate e1 + e2 , it must first evaluate e1 and e2 to
obtain two integers and then add those integers, so the evaluation function must call
itself recursively:
1.3 A Simple Language of Expressions 3

let rec eval (e : expr) : int =


match e with
| CstI i -> i
| Prim("+", e1, e2) -> eval e1 + eval e2
| Prim("*", e1, e2) -> eval e1 * eval e2
| Prim("-", e1, e2) -> eval e1 - eval e2
| Prim _ -> failwith "unknown primitive";;

The eval function is an interpreter for “programs” in the expression language. It


looks rather boring, as it implements the expression language constructs directly by
similar F# constructs. However, we might change it to interpret the operator (-) as
cut-off subtraction, whose result is never negative. Then we get a “language” with
the same expressions but a very different meaning. For instance, 3 − 4 now evaluates
to zero:
let rec evalm (e : expr) : int =
match e with
| CstI i -> i
| Prim("+", e1, e2) -> evalm e1 + evalm e2
| Prim("*", e1, e2) -> evalm e1 * evalm e2
| Prim("-", e1, e2) ->
let res = evalm e1 - evalm e2
if res < 0 then 0 else res
| Prim _ -> failwith "unknown primitive";;

1.3.2 Expressions with Variables

Now, let us extend our expression language with variables such as x and y. First, we
add a new constructor Var to the syntax:
type expr =
| CstI of int
| Var of string
| Prim of string * expr * expr

Here are some expressions and their representation in this syntax:

Expression Representation in type expr


17 CstI 17
x Var "x"
3+a Prim("+", CstI 3, Var "a")
b·9+a Prim("+", Prim("*", Var "b", CstI 9), Var "a")
4 1 Introduction

Next we need to extend the eval interpreter to give a meaning to such variables.
To do this, we give eval an extra argument env, a so-called environment. The role
of the environment is to associate a value (here, an integer) with a variable; that is,
the environment is a map or dictionary, mapping a variable name to the variable’s
current value. A simple classical representation of such a map is an association list:
a list of pairs of a variable name and the associated value:
let env = [("a", 3); ("c", 78); ("baf", 666); ("b", 111)];;

This environment maps "a" to 3, "c" to 78, and so on. The environment has
type (string * int) list. An empty environment, which does not map any
variable to anything, is represented by the empty association list
let emptyenv = [];;

To look up a variable in an environment, we define a function lookup of type


(string * int) list -> string -> int. An attempt to look up vari-
able x in an empty environment fails; otherwise, if the environment associates y with
v, and x equals y, the result is v; else the result is obtained by looking for x in the
rest r of the environment:
let rec lookup env x =
match env with
| [] -> failwith (x + "not found")
| (y, v)::r -> if x=y then v else lookup r x;;

As promised, our new eval function takes both an expression and an environment,
and uses the environment and the lookup function to determine the value of a
variable Var x. Otherwise the function is as before, except that env must be passed
on in recursive calls:
let rec eval e (env : (string * int) list) : int =
match e with
| CstI i -> i
| Var x -> lookup env x
| Prim("+", e1, e2) -> eval e1 env + eval e2 env
| Prim("*", e1, e2) -> eval e1 env * eval e2 env
| Prim("-", e1, e2) -> eval e1 env - eval e2 env
| Prim _ -> failwith "unknown primitive";;

Note that our lookup function returns the first value associated with a variable, so
if env is [("x", 11); ("x", 22)], then lookup env "x" is 11, not 22.
This is useful when we consider nested scopes in Chap. 2.
1.4 Syntax and Semantics 5

1.4 Syntax and Semantics

We have already mentioned syntax and semantics. Syntax deals with form: is this
program text well-formed? Semantics deals with meaning: what does this (well-
formed) program mean, how does it behave – what happens when we execute it?

• One may distinguish two kinds of syntax:

– By concrete syntax we mean the representation of a program as a text, with


whitespace, parentheses, curly braces, and so on, as in “3+ (a)”.
– By abstract syntax we mean the representation of a programs as a tree, either an
F# datatype term Prim("+", CstI 3, Var "a") as in Sect. 1.3 above,
or by an object structure as in Sect. 1.5. In such a representation, whitespace,
parentheses and so on have been abstracted away; this simplifies the processing,
interpretation and compilation of program fragments. Chapter 3 shows how to
systematically create abstract syntax from concrete syntax.

• One may distinguish two kinds of semantics:

– Dynamic semantics concerns the meaning or effect of a program at run-time;


what happens when it is executed? Dynamic semantics may be expressed by
eval functions such as those shown in Sect. 1.3 and later chapters.
– Static semantics roughly concerns the compile-time correctness of the program:
are variables declared, is the program well-typed, and so on; that is, those prop-
erties that can be checked without executing the program. Static semantics may
be enforced by closedness checks (is every variable defined, Sect. 2.3.2), type
checks (are all operators used with operands of the correct type, Sect. 4.8), type
inference (Sect. 6.4), and more.

The distinction between syntax and static semantics is not clear-cut. Syntax can tell
us that x12 is a legal variable name (in Java), but it is impractical to use syntax
to check that we do not declare x12 twice in the same scope (in Java). Hence this
restriction is usually enforced by static semantics checks.
In the rest of the book we shall study a small expression language, two small
functional languages (a first-order and a higher-order one), a subset of the imperative
language C, and a subset of the backtracking language Icon. In each case we take
the following approach:

• We describe abstract syntax using F# datatypes.


• We describe concrete syntax using lexer and parser specifications (see Chap. 3),
and implement lexers and parsers using the tools fslex and fsyacc.
• We describe semantics using F# functions, both static semantics (checks) and
dynamic semantics (execution). The dynamic semantics can be described in two
ways: by direct interpretation, using functions typically called eval, or by com-
pilation to another language, such as stack machine code, using functions typically
called comp.
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
6 1 Introduction

In addition we study some abstract stack machines, both homegrown ones and
two widely used so-called managed execution platforms: The Java Virtual Machine
(JVM) and Microsoft’s Common Language Infrastructure (CLI, also known as .Net).

1.5 Representing Expressions by Objects

In most of the book we use a functional language to represent expressions and


other program fragments. In particular, we use the F# algebraic datatype expr to
represent expressions in the form of abstract syntax. We use the eval function to
define their dynamic semantics, using pattern matching to distinguish the different
forms of expressions: constants, variables, operators applications.
In this section we briefly consider an alternative object-oriented modeling (in
Java, say) of expression syntax and expression evaluation. In general, this would
require an abstract base class Expr of expressions (instead of the expr datatype),
and a concrete subclass for each expression form (instead of a datatype constructor
for each expression form):
abstract class Expr { }
class CstI extends Expr {
protected final int i;
public CstI(int i) { this.i = i; }
}
class Var extends Expr {
protected final String name;
public Var(String name) { this.name = name; }
}
class Prim extends Expr {
protected final String oper;
protected final Expr e1, e2;
public Prim(String oper, Expr e1, Expr e2) {
this.oper = oper; this.e1 = e1; this.e2 = e2;
}
}

Note that each Expr subclass has fields of exactly the same types as the arguments
of the corresponding constructor in the expr datatype from Sect. 1.3.2. For instance,
class CstI has a field of type int just as constructor CstI has an argument of
type int. In object-oriented terms Prim is a composite because it has fields whose
type is its base type Expr; in functional programming terms one would say that type
expr is a recursively defined datatype.
How can we define an evaluation method for expressions similar to the F# eval
function in Sect. 1.3.2? That eval function uses pattern matching, which is not
available in Java or C#. A poor solution would be to use an if-else sequence that
tests on the class of the expression, as in if (e instanceof CstI) and so on.
1.5 Representing Expressions by Objects 7

The proper object-oriented solution is to declare an abstract method eval on class


Expr, override the eval method in each subclass, and rely on virtual method calls
to invoke the correct override in the composite case. Below we use a Java map from
variable name (String) to value (Integer) to represent the environment:
abstract class Expr {
abstract public int eval(Map<String,Integer> env);
}
class CstI extends Expr {
protected final int i;
...
public int eval(Map<String,Integer> env) {
return i;
}
}
class Var extends Expr {
protected final String name;
...
public int eval(Map<String,Integer> env) {
return env.get(name);
}
}
class Prim extends Expr {
protected final String oper;
protected final Expr e1, e2;
...
public int eval(Map<String,Integer> env) {
if (oper.equals("+"))
return e1.eval(env) + e2.eval(env);
else if (oper.equals("*"))
return e1.eval(env) * e2.eval(env);
else if (oper.equals("-"))
return e1.eval(env) - e2.eval(env);
else
throw new RuntimeException("unknown primitive");
}
}

An object built by new Prim("-", new CstI(3), new CstI(4)) will


then represent the expression “3 − 4”, much as Sect. 1.3.1. In fact, most of the devel-
opment in this book could have been carried out in an object-oriented language, but
the extra verbosity (of Java or C#) and the lack of pattern matching would often make
the presentation considerably more verbose.
8 1 Introduction

1.6 The History of Programming Languages

Since 1956, thousands of programming languages have been proposed and imple-
mented, several hundred of which have been widely used. Most new programming
languages arise as a reaction to some language that the designer knows (and likes
or dislikes) already, so one can propose a family tree or genealogy for programming
languages, just as for living organisms. Figure 1.1 presents one such attempt. Of
course there are many many more languages than those shown, in particular if one
counts also more domain-specific languages such as Matlab, SAS and R, and strange
“languages” such as spreadsheets [5].
In general, languages lower in the diagram (near the time axis) are closer to
the real hardware than those higher in the diagram, which are more “high-level”
in some sense. In Fortran77 or C, it is fairly easy to predict what instructions and
how many instructions will be executed at run-time for a given line of program. The
mental machine model that the C or Fortran77 programmer must use to write efficient
programs is close to the real machine.
Conversely, the top-most languages (SASL, Haskell, Standard ML, F#, Scala)
are functional languages, possibly with lazy evaluation, with dynamic or advanced
static type systems and with automatic memory management, and it is in general
difficult to predict how many machine instructions are required to evaluate any given
expression. The mental machine model that the Haskell or Standard ML or F# or
Scala programmer must use to write efficient programs is far from the details of a
real machine, so he can think on a rather higher level. On the other hand, he loses
control over detailed efficiency.
It is remarkable that the recent mainstream languages Java and C#, especially their
post-2004 incarnations, have much more in common with the academic languages
of the 1980’s than with those languages that were used in the “real world” during
those years (C, Pascal, C++).

SASL HASKELL
F#
LISP ML STANDARD ML
Scala
CAML LIGHT OCAML
SCHEME C# 2 C# 4
PROLOG GJ Java 5
BETA
SMALLTALK JAVA C# VB.NET 10
Go
SIMULA VISUAL BASIC

ALGOL 68 C++

ALGOL
CPL BCPL B C

PASCAL ADA ADA95 ADA2005


BASIC

COBOL FORTRAN90 FORTRAN2003

FORTRAN FORTRAN77

1956 1960 1970 1980 1990 2000 2010

Fig. 1.1 The genealogy of programming languages


1.6 The History of Programming Languages 9

Some interesting early papers on programming language design principles are


due to Landin [3], Hoare [2] and Wirth [9]. Building on Landin’s work, Tennent [7,
8] proposed the language design principles of correspondence and abstraction.
The principle of correspondence requires that the mechanisms of name binding
(the declaration and initialization of a variable let x = e, or the declaration of
a type type T = int, and so on) must behave the same as parametrization (the
passing of an argument e to a function with parameter x, or using a type int to
instantiate a generic type parameter T).
The principle of abstraction requires that any construct (an expression, a statement,
a type definition, and so on) can be named and parametrized over the identifiers that
appear in the construct (giving rise to function declarations, procedure declarations,
generic types, and so on).
Tennent also investigated how the programming language Pascal would have
looked if those principles had been systematically applied. It is striking how well
modern languages, such as Scala and C#, adhere to Tennent’s design principles, but
also that Standard ML [4] did so already in 1986.

1.7 Exercises

Exercise 1.1 (i) File Intro2.fs contains a definition of the expr expression
language and an evaluation function eval. Extend the eval function to handle
three additional operators: "max", "min", and "==". Like the existing operators,
they take two argument expressions. The equals operator should return 1 when true
and 0 when false.
(ii) Write some example expressions in this extended expression language, using
abstract syntax, and evaluate them using your new eval function.
(iii) Rewrite one of the eval functions to evaluate the arguments of a primitive
before branching out on the operator, in this style:
let rec eval e (env : (string * int) list) : int =
match e with
| ...
| Prim(ope, e1, e2) ->
let i1 = ...
let i2 = ...
match ope with
| "+" -> i1 + i2
| ...

(iv) Extend the expression language with conditional expressions If(e1, e2,
e3) corresponding to Java’s expression e1 ? e2 : e3 or F#’s conditional
expression if e1 then e2 else e3.
10 1 Introduction

You need to extend the expr datatype with a new constructor If that takes three
expr arguments.
(v) Extend the interpreter function eval correspondingly. It should evaluate e1, and
if e1 is non-zero, then evaluate e2, else evaluate e3. You should be able to evaluate
the expression If(Var "a", CstI 11, CstI 22) in an environment that
binds variable a.
Note that various strange and non-standard interpretations of the conditional
expression are possible. For instance, the interpreter might start by testing whether
expressions e2 and e3 are syntactically identical, in which case there is no need to
evaluate e1, only e2 (or e3). Although possible, this shortcut is rarely useful.

Exercise 1.2 (i) Declare an alternative datatype aexpr for a representation of arith-
metic expressions without let-bindings. The datatype should have constructors CstI,
Var, Add, Mul, Sub, for constants, variables, addition, multiplication, and subtrac-
tion.
Then x ∗ (y + 3) is represented as Mul(Var "x", Add(Var "y", CstI
3)), not as Prim("*", Var "x", Prim("+", Var "y", CstI 3)).
(ii) Write the representation of the expressions v − (w + z) and 2 ∗ (v − (w + z))
and x + y + z + v.
(iii) Write an F# function fmt : aexpr -> string to format expressions
as strings. For instance, it may format Sub(Var "x", CstI 34) as the string
"(x - 34)". It has very much the same structure as an eval function, but takes no
environment argument (because the name of a variable is independent of its value).
(iv) Write an F# function simplify : aexpr -> aexpr to perform expres-
sion simplification. For instance, it should simplify (x + 0) to x, and simplify (1 + 0)
to 1. The more ambitious student may want to simplify (1 + 0) ∗ (x + 0) to x. Hint:
Pattern matching is your friend. Hint: Don’t forget the case where you cannot simplify
anything.
You might consider the following simplifications, plus any others you find useful
and correct:

0+e −→ e
e+0 −→ e
e−0 −→ e
1∗e −→ e
e∗1 −→ e
0∗e −→ 0
e∗0 −→ 0
e−e −→ 0

(v) Write an F# function to perform symbolic differentiation of simple arithmetic


expressions (such as aexpr) with respect to a single variable.
Random documents with unrelated
content Scribd suggests to you:
CHAPTER XXVII

MATTERS PERSONAL, LITERARY, AND GENERAL.

THE Icelanders, as I have pictured them, are intellectual in their


tastes; and in domestic life they are highly social. Their amusements
are few, their enjoyments being principally in the family, at their
labor, and attending public worship. Throughout the country, they
gather from a circuit of many miles, to hear their ministers proclaim
“glad tidings,” and tell them of the reward that awaits a well-spent
life. In the long winter evenings, one member of the family is much
of the time reading aloud, while the others are engaged in domestic
duties, spinning, weaving, knitting, and making clothing and
domestic utensils, in which the males as well as the females, all
engage. In their personal demeanor, the Icelanders are generally
quiet, sober, and somewhat taciturn. A love of amusement, and a
fondness for sport, is not common. Some of the Icelanders that I
have seen, have had a great deal of vivacity, and large
conversational powers. Some that have visited foreign countries,
have returned home so impressed with their experience of the great
and busy world; that they have infused a spirit of activity and inquiry
into the whole circle where they move. They tell of one man, an
Icelander, who got off to the continent, and went through all the
wars of Napoleon, and after many years returned to his native land.
He was so glad to see his own good island, that he fell down and
embraced the earth, and declared, in the words of the national
proverb, “Iceland is the best country the sun shines upon.”[39] With
all that the poor soldier had seen of the luxury and variety of foreign
countries, there was, to him, “no place like home.” While the
Icelander is fond of conversation, when in the presence of strangers
he rather listen than talk. They come well up to Dr. Johnson’s
favorite character, a good listener. When a foreigner calls at the
house of an Icelander, he attends first to the personal wants of his
guest; then he is desirous of learning all the stranger has to
communicate. He is shrewd and inquisitive, and asks the most
pertinent and ingenious questions, and never rests satisfied till he
has learned with great minuteness all that the stranger has to tell
him respecting the great world, and the foreign countries he has
seen. He is always most respectful and obliging, and ready to
communicate information, and answer questions about every thing
relating to his country or pursuits. He seems to appreciate the
greater amount of wealth and luxury abroad, and the superior
magnificence and splendor of cities like Copenhagen, Paris, London,
or New York, as compared to his own small towns; yet his amor
patriæ and contentment make him superior to all temptations to
emigrate. His industry, fondness for reading and conversing, his
great integrity of character, a devotional spirit, and ardent love for
the precepts and practices of Christianity—these, with his
contentment and love of liberty, are the most prominent
characteristics of the Icelander. They do not show much fondness for
exact science, though they pay some attention to the studies of
geography and natural history. Having no fuel but turf—except what
is imported—none of the precious or useful metals, no material,
except wool, for the manufacture of textile fabrics, raising no fruits
or grain, and having little use for water or steam power, they have
few incentives to exert themselves in acquiring a knowledge of
chemistry, mineralogy, geology, electricity, magnetism, hydraulics,
pneumatics, or many of the mechanic and useful arts.
“Circumstances make men,” or bring out certain traits of character;
and the Icelander forms no exception to the general rule. We see
how he is placed. Obtaining his subsistence from the products of the
earth and the sea, engaged little in traffic, he does not experience
much of the fraud and wrong that is found in the busy haunts of
men; and in him we see little but the gentle and better
characteristics of our nature.
The Icelander is poor, and books are to him a luxury; yet he
possesses more, in proportion to his means, than the natives of any
other country. We shall see by comparison and looking at facts, what
their intellectual resources are. The number of books, of all sizes,
published in Iceland in each of the years 1847 and 1848, was
seventeen—thirty-four volumes in two years; and these for a
community of 60,000 people. Were there as many in proportion
printed for our population of twenty-five millions, the number of
books—distinct works, independent of periodicals—published
annually in the United States, would be over seven thousand. The
most of the Iceland books are duodecimos and octavos; the largest
volume for the year 1847 containing 928 pages. This was a sort of
“Congressional Globe,” though not issued in numbers—a record of
the proceedings of their Althing or Congress.[40] This seems like a
pretty lengthy journal of a session that lasted but little over a month.
They passed a number of acts of much importance to the people;
and very likely the session was enlivened with as many “speeches to
Buncombe,” as we hear in the same length of time on Capitol Hill.
Some of the works published in Icelandic, are issued from the press
in Copenhagen; but the majority of them are printed and bound in
Iceland. They have several printing-presses constantly at work, and
three newspapers—one once a week, and two issued once a
fortnight. In mechanical execution, their books and newspapers are
turned out in better style than the average of those issued from the
American press. They are, however, always without illustrations.
From what has been said, it will be seen that the Icelanders of the
present day are a different people from those of an earlier period. In
former times, the tyranny of rulers and the ambition of demagogues,
kept up a warlike spirit, and an ardent love of political liberty. While
they were less amiable and peaceful, they showed, both in letters
and politics, a greater degree of activity. Lest it may be thought that
I have drawn too favorable a picture of the early Icelanders, I will
here give an extract from a learned dissertation on the history and
literature of Iceland, by the distinguished Dr. (now Sir Henry)
Holland, who visited the country in 1810, in company with Sir
George Mackenzie.
Like the aurora borealis of their native sky, the poets and
historians of Iceland not only illuminated their own country,
but flashed the lights of their genius through the night which
then hung over the rest of Europe. Commerce was pursued
by the inhabitants with ardor and success; and they partook
of the maritime adventures of discovery and colonization,
which gave so much merited celebrity to the Norwegians of
this period. Of the several features which distinguish this
remarkable period in the history of Iceland, the literary
character of the people is doubtless the most extraordinary
and peculiar. We require much evidence to convince us of
the fact that a nation remote from the rest of Europe,
dwelling on a soil so sterile, and beneath such inclement
skies, should have sent forth men whose genius, taste, and
acquirements did honor to their country, and to the times in
which they lived. Such evidence, however, of the most
distinct and decisive kind, we possess in the many writings
which have come down from this period to the present age,
and in the testimonies afforded by the cotemporaneous
writers of other countries. The reality of the fact, indeed, can
admit of no doubt; and it is only left for us to speculate upon
the causes which led to this singular anomaly in the history
of literature.[41]
The above was written forty years ago, and by one of the most
intelligent travelers that ever visited Iceland.
I was asked by the Icelanders, if it would not be an object for some
of my countrymen to settle in Iceland, and teach them the practical
and productive arts as understood in my country. I told them, I did
not think it would be an object for the natives of any country I knew
to go and settle there. The restrictive laws of Denmark do not favor
trade with foreigners; the country produces too little variety, and too
small quantities of suitable articles for exportation, to create a trade
of much magnitude. Their soil is, a majority of it, entirely
unproductive; and the balance produces too little ever to support a
numerous population. The articles they have are good of the kind;
they raise excellent beef and mutton; the wool of their sheep is soft
and durable, but not fine or handsome. It is not so good for first-
class manufactures, as the sheep are often pied, spotted, and
variegated in color; and it is not so good for coloring, as they always
pull it off of the animals, instead of shearing it.[42] Fish—salmon and
cod—are important articles of export; and their horses, though
small, are very desirable animals. A little larger than the Shetland
pony, often of singular color, hardy, gentle, and docile; for pony
carriages, and for children and females to ride, I think they would be
a desirable addition to our stock of horses in the United States. A
schooner-load of them went from Iceland to Scotland, when I was in
the country; and I have no doubt they sold at a good profit, as the
average cost was less than ten dollars a head. As these animals are
never fed in winter, they are necessarily raised very cheaply; and,
were trade open with foreign countries, I have no doubt a great
demand would spring up for them, and add largely to the profits of
the Iceland farmer. Apropos of this subject of free trade, I will here
give an extract from the letter of an intelligent Icelander, which I
have just received, and which was written after the commencement
of hostilities in Europe. There is no reason why the king of Denmark
should not open the trade of Iceland equally to all nations. It is not a
particle of pecuniary benefit to his kingdom, as there are no duties
charged; but, by restricting the trade to Danish vessels, it is kept as
a kind of monopoly by a few merchants of Copenhagen; while the
poor Icelanders complain greatly of the oppression and hardship of
being dependent for their foreign necessaries and luxuries, entirely
on a few grasping speculators. Whenever the Iceland Althing passes
an act opening their ports to all nations, the king vetoes the bill.
They murmur at it as great injustice; but what avail the murmurs of
the weak? During the last war in Europe—1810–12—Denmark came
near losing the colony in two different ways. One was, the enemy
came near taking possession; and another escape they had, the
“mother country” not being able to protect the island, or send them
supplies, the people came near starving to death; and were only
saved from the greatest destitution by the clemency and liberality of
Great Britain, in treating the Icelanders as “friends,” while the
country was at war with Denmark. If his Danish Majesty should feel
compelled to take up arms in the present struggle, the island would
be in similar peril. Respecting this, and some other subjects, the
following letter, from a learned Icelander—the President of the
Iceland College—will be read with interest:
Reykjavik, March 1st, 1854.
SIR:

As to political news, I have not much to relate; nor, I am


sure, do you expect much from this quarter; yet, a change is
about to take place in our commercial relations. In all
probability, the Danish government will, after a monopoly of
two and a half centuries, at length, this year, condescend to
allow of our free intercourse, for mercantile purposes, with
all nations. It would be superfluous to write you any thing
about the impending war; but I cannot forbear stating, that
in case of war between England and Russia, to which
Denmark would probably be constrained to become a party,
our situation here, in this island, would needs become very
precarious.

Sir: I should be charmed to visit your stately country, to get


an idea of her soaring aspirations, to view her wonders of
civilization, with all her rapid improvements. She seems to be
the only country that at present enjoys the blessings of
freedom, and on whose soil liberty can prosper. But I very
much fear my desire of paying a visit there will ever remain a
“pium votum” which neither my financial circumstances nor
my occupation will allow of.
Though you have, dear sir, already rendered me so many
important services, I must, before concluding this letter, once
more importune you with a boon, which is in the interest of
my college, to procure me a copy of the following work, a
most excellent one, by one of your countrymen—“Report on
Education in Europe, to the Trustees of the Girard College for
Orphans, by Alex. Dallas Bache, Philadelphia, 1839.” I have
made several applications to my bookseller in Copenhagen,
but all in vain. Then, I should feel much obliged to you, if
you could procure me, by the means of your influential
friends in America and Great Britain, some examination
papers from some of your colleges or schools of England,
especially from Eton, Harrow, or Winchester, containing the
questions put to the pupils, as well as copies of the best
answers to them; together with specimens of their exercises
in Latin and Greek. If you could comply with this desire of
mine, you would render yourself one of the benefactors of
our college. I could send the expense to Mr. Younghusband,
your correspondent in Liverpool.

I remain, sir,
Your faithful and obliged friend,
BJARNI JOHNSON.

To PLINY MILES, Esq.,


Washington.

A man who can write thus, who can so express himself, in the purest
and most forcible English, does not belong to a community of people
who are entirely ignorant of the world at large, or indifferent to the
national, political, and educational movements of the powerful
nations of the earth. If the Danish government should open the
ports of Iceland to all nations, it would be in accordance with the
advanced and progressive spirit of the age, and while conferring a
great benefit on a quiet, peaceful, and isolated colony, knit more
closely the ties of affection and union between the colonists and the
parent country. Then we might chronicle the arrival and departure of
vessels, a little oftener, between the northern isle of the ocean and
our own seaports.
Last year, a ship bearing the classic name of the “SAGA,”[43] sailed into
the harbor of New-York, direct from Iceland, being the first arrival
from that country to this, in a period of more than eight hundred
years! I think the maritime records of the world would be searched
in vain for a parallel case. The crew of this ship were the “followers”
of Eric the Red, and his compeers, who discovered the American
continent, and gave it the name of Vinland; but they were certainly a
long time in following him.[44]

FOOTNOTES:

39. “Island er hinn besta land, sem solinn skinnar uppá.”

40. “Tiðindi frá Alþingi. Annað þing, 1 Juli til 7 Agust, 1847.”

41. From “Mackenzie’s Iceland;” “Preliminary Dissertation” on the


Literature and History of the country, by Dr. Henry Holland.

42. This may be thought barbarous and cruel; but probably it is


not; for it is pulled at two or three different times, and only
that portion pulled off that comes easy. Then, perhaps, too,
custom is something, like the adage of the eels, &c.

43. A vessel—the “BALDAUR,” as it was printed in the newspapers—


seems to have derived its name from Northern Mythology
—“Baldur, the Fair.” This ship was spoken of as having sailed
near a steamer on the track of the missing “Glasgow.” Now
and then, it seems, a name, or maritime event, connects us
with the far north.

44. Since the above was in type, intelligence has arrived from
Denmark, that a law has just been passed, throwing open the
ports of Iceland to the trade of the world. For this, none will
rejoice more than the Icelanders themselves; for a more
relentless, grinding, and hated monopoly never oppressed a
poor people. The resident Danish merchants will now not be
able to have every thing their own way. As the law takes effect
in April, 1855, a trade between Iceland and England, and
Iceland and America, will soon spring up. The articles that the
Icelanders most require from foreign countries, and the
productions of the island which they have to export, will be
found enumerated in preceding chapters.
CHAPTER XXVIII

RAMBLES BROUGHT TO A CLOSE—EMBARKATION.

THOUGH this little book was not written for the Iceland market, I
cannot help making one or two remarks respecting their own
internal affairs. Most undoubtedly they have learned more from
experience than a foreigner from a hasty visit could teach them, but
I believe they do not appreciate the productiveness and value of
their soil. As scanty as are the agricultural resources of Iceland, and
as short as their seasons are, I am confident that this “art of arts”
might be greatly advanced here. Plowing would, certainly, in many
places, greatly improve their land, smooth the surface, and enable
them to lay it down with a better quality of grass. Their seed would,
the most of it, however, have to be brought from foreign countries.
On seeing their fine meadows of “red top”—the kind of grass most
prevalent,—I at once told them that the white, if not the red clover,
would be much more productive than their native grasses.
Afterwards, I saw many farms in the valleys of the Laxá and the
Thiorsá rivers, that were well seeded with white clover; and as it
was the haying season, I could see that these farms yielded about
double the hay that other farms did, where there was no clover. The
clover had once been sown, and then it had propagated itself. I
believe many of the more favorably located farms could be made to
produce barley and oats, if the land were properly prepared. These
grains are raised in Orkney, Shetland, and the Faroe Isles; and the
latter group is but little south of Iceland. Nothing would do, however,
without plowing; and in Iceland never a horse wore harness yet, so
it would take a little time to get such a business started. If the
governor of Iceland were a thoroughly practical man, he could do
much towards introducing these and other improvements. A good
opening place for the plow would be the “public square” in
Reykjavik, about two acres of irregular grass; that, once broken up,
and leveled, and seeded down to white clover, would make a
beautiful village green. If they had plows, they would make larger
gardens than they now do with the spade, and more table
vegetables would be raised. This would be conducive to the health
and comfort of the people, and would, probably, in time, if not
entirely eradicate at least greatly reduce the diseases of the skin,
and that terrible plague, the leprosy; both of which are somewhat
common, and undoubtedly produced, or greatly aggravated, by
living to a great extent on animal food.
The Icelanders, like all other ancient people, are extremely attached
to their own customs, and averse to innovation. I noticed one thing
here, that—though, as Captain Cuttle would say, there was not much
wisdom in it—is characteristic of every people under the sun. While
fond of every foreign article, particularly of ornament, they about
entirely neglected the native productions. With great pains and
trouble, they would rear in their houses, geraniums, roses, fuchsias,
violets, and other exotics, and yet neglect to plant one single native
flower. The beautiful and fragrant heath, common over much of
Iceland, does not grow within several miles of Reykjavik; and yet not
one single resident had planted by his dwelling a stalk of this elegant
little shrub, to bloom and give out perpetual fragrance. I saw, also,
beautiful annual flowers growing wild in the fields, and on the river
banks, but which were never cultivated. Sir George Mackenzie has
given a list of the Iceland Flora, and a pretty long catalogue it is.
I believe a carriage road could be made in some places, particularly
between Reykjavik and Hafnarfiorth; but then it might not pay to
attempt to make many carriage roads, and introduce wheeled
vehicles in Iceland. If the land was leveled and seeded down, and
bogs and wet places drained, and converted into dry, productive
meadows, I believe it would be an object for the larger farmers to
have carts to draw their hay on, rather than carry it in bundles on
the backs of men or horses. Then, too, if their meadows were
smooth the product would be much greater, and they would be able
to introduce a much larger scythe than the little two-foot knife-blade
affair used there at present. With the improvement of their land,
their tools could be greatly improved. The population of Iceland has
been stated at 60,000 souls, and probably the increase is not one-
and-a-half per cent. annually. Women, as well as men, work in the
fields, during the hay season; but, in fishing, the men only are
engaged. The exposure attendant on this latter business gives many
complaints of the lungs; and probably more die of consumption than
of any other disease. The plague, about five hundred years ago,
visited Iceland; but cholera and yellow fever have never been here.
There are but few physicians in the country, and the distances they
have to travel often make their services of no avail, Death calling on
the patient before the doctor does. In countries of more luxury and
refinement, Death often calls soon after the doctor! From what I
learn, I should judge longevity was not as great here as in most
countries in the temperate zones.
The last Sunday I was in Iceland I attended church at the Reykjavik
cathedral. This is a beautiful little edifice, of brick, with a fine altar—
altogether of an ornamental appearance. The sermon was in
Icelandic, the service Lutheran, but much after the style of the
Church of England. Three Sundays out of four, I think it is, that the
service in this place is in Icelandic, and every fourth Sunday in
Danish. What the use may be of having any service in Danish is
more than I can tell, for a more worldly, ungodly set than the Danish
merchants of Iceland I never saw in a Christian country. At this
place, their example has driven nearly all religious observances away
from the Icelanders. Though the day was beautiful, and but one
church in the village, and all professing the same religion, and all the
people, too, understanding both languages, there were not, from
among the twelve hundred people of the place, fifty worshipers. This
certainly does not accord with what I have said of the moral and
religious habits of the Icelanders in general. I do not think I do the
Danes injustice, when I lay the immorality in and around Reykjavik
to their influence and example. In several villages and country
places I had a good opportunity of observing, and I know that ten
times greater proportion of the people attended church than here in
Reykjavik. A class like these merchants, who notoriously do nothing
but traffic, make money, gamble, and drink, cannot improve the
morals of a simple, pious, and intellectual people.
The people assembled at the church very quietly, and took their
seats without tarrying at the door, or entering into conversation.
They were all dressed neatly, and two or three females wore the
ancient costume of the country. It is very picturesque, but
“Description will not suit itself in words.”

I cannot do better than give another extract from the letter of


President Johnson—quoted in last chapter—under date of March 1st,
1854, as well as part of one written the November previous. Only a
portion of the letters are given, and all of this is of a private and
personal nature, intended for no eye but my own. Barring the
compliments that are given, the extracts will be read with interest,
both as showing the composition of an Icelander in a foreign
language, and the educational, parochial, and local news
communicated. Commencing his letter of March 1st, he says:
“MY DEAR SIR!
“I have to acknowledge from you the third letter since we
parted—of Dec. 4th, last (Washington)—together with a
large parcel of books, all sent to me by the care of your
friend Mr. Younghusband, at Liverpool, who, besides, had the
kindness to write me a very friendly letter, and send me the
last copies of the leading newspapers of Great Britain.—
Indeed, sir, I feel quite ashamed at receiving so many proofs
of your friendship, without being capable of giving you the
least mark of my gratitude; for all I can furnish is our little
“Þjoðolfur,”[45] a poor return for all your liberality. To this I
take the liberty to add an examination paper—(Program[46])—
in Icelandic and Danish—of the management and teaching of
our College, for the year 1852, ’53.

I have forwarded all your presents to the persons interested


that are living here in town and neighborhood: such as were
destined for the interior of the country, I must keep till the
spring, all communication therewith being impracticable
except on foot. Now I am charged with the task of bringing
you their thanks, for your kindness in remembering them
when you had so little to thank for. I left your direction with
them, intimating that a letter from them would be much
esteemed by you, even though written in Danish or
Icelandic. And as to news concerning your acquaintances
here, all is unchanged. None of the ladies you mention, are
married. The Misses Johnson are keeping a female school
pretty successfully; the Misses Sivertsen living with their
parents, and I am to tell you the compliment of their father.
[47]
He has delivered to me the flask you so kindly presented
me with, and which I shall keep as a souvenir of you, though
rather too small for my capacious stomach! The Dean
Johnson is going to leave in March, to the regret of his
friends. He is to have another living in the interior of the
country. Thorarensen has left the College, and you will find
his name (S. Thorarensen) as well as that of Jon Sveinson in
the examination paper I send you here inclosed. Mrs.
Egilson,[48] Mr. Ranthrys, the Apothecary, and his lady, Mr.
Jon Arnason,[49] were all extremely pleased with the N. Y.
Illustrated News you sent them. I have also to salute you
from the Bishop.”
In Mr. Johnson’s letter of Nov. 15th, 1853, he says:
“I have to acknowledge from you the reception of two
letters; the former of Sept. 24, 1852 (Glasgow), the latter of
Sept. 5, this year (Washington), both attended with
newspapers, for which I feel very much obliged to you, as for
your friendship in general. I am very glad to learn by your
latter letter, that you are returned sound and safe to your
native country, from your long and checkered journey. But I
trust you will not repent the toils and hardships inseparably
connected with such a ‘tour’ almost around the world. You
will, I am sure, allow of its important consequences for our
own mental improvement and development. Old Horace
says: ‘Qui multorum providus urbes et mores hominum
inspexit—latumque per æquor, aspera multa pertulit adversis
rerum immersabilis undis.’
“I am very much indebted to you for the copies of
newspapers you so kindly have sent to me. However, I
deeply regret none of them contained your lectures upon the
curiosities of this country, as in general what attracted your
notice on your extensive journey. But then I console myself
by your kind promise to send me a copy of your Travels in
Iceland, when ready from the press.

I have to announce to you Jon Sveinson’s most heartfelt


thanks for your letter of introduction to your friend at Hull,[50]
which benefited him very much during his stay there; and I
feel obliged to join my thanks to his, as it was on my
recommendation that you gave him the said letter. Indeed,
sir, he feels very much bound in gratitude to you and your
friends for all the kindness they poured on him. He has now
left the college—last season—with a very honorable
testimonial; and but for the cholera that has been raging in
Denmark during the latter part of the last summer, he would
have gone to the University of Copenhagen; but now having
postponed his journey thither to the next spring, he passes
this winter at his father’s, who is a reputed clergyman of
easy circumstances, in the interior of this country. Jon
Sveinson’s visit to Hull, has also procured me a friend there.
The last summer, I had successively received some copies of
English newspapers, without knowing from what quarter
they came. I thought of you or some of my other friends in
Great Britain; but a couple of months ago I received a letter
from Mr. Archibald Kidd, Saville street, Hull (if I decipher his
name correctly), who informed me that it was to him I was
indebted for the favor of the newspapers, and who asked me
some information about the means of studying Icelandic
literature, and the method of setting out about it. I most
readily complied with his request, as far as I could, and
wrote him by the last post-ship for Liverpool. As he intimated
to know you, I expect you to be so kind as to give me in
your next letter some information about this gentleman.

I send you enclosed a copy of the Thiotholfur for the whole


year 1852–53. I wish you to tell me whether I am to
continue it. This I might easily do, especially in the summer
time, as at that season there are frequent occasions for
sending to England; whereas, in winter it is more difficult,
the only ship going there being the post-ship, and my
extensive official correspondence with the ministry of public
instruction seldom permitting me sufficient leisure to write to
my private friends.
“Now, I wish these lines may find you in good health and
happiness; and I sign myself, my dear sir,
“Your very much indebted friend,
“BJARNI JOHNSON.”

“To Mr. PLINY MILES,


Washington.”

It should be stated that the great capacity of my friend does not


consist in the appetite, so much as a certain embonpoint, coming, as
he does partly up to Shakspeare’s description of Cardinal Wolsey—“a
man of an unbounded stomach.”
In closing my account of the Icelanders at Reykjavik, I have to
record the pleasure and profit that I derived from the friendly
attentions of these excellent people. I spent many and most
pleasant hours with President Johnson, and with Mr. Sivertsen and
his wife and daughters; also a most agreeable evening at the house
of the Dean, Rev. Mr. Johnson, who made a small party on my
account. The young ladies in this family, as also in Mr. Sivertsen’s,
and Mr. Ranthry’s, contributed much to the agreeable socialities of
my stay in Reykjavik. Were these fair daughters of the North to
appear in society in England or America, a comparison to their
disadvantage could not be drawn. Speaking several languages—
always two or more—good players on the pianoforte and the guitar,
skilled also in vocal music, and to these accomplishments, add a
knowledge of household duties, and I fear that many of the
graduates of our female boarding-schools could not successfully
come into competition with them. I also partook of the hospitalities
of their most excellent bishop, who lives a little way out of town, on
a pleasant part of the coast, opposite the island of Vithey. Before
leaving Copenhagen, and on my return there, I formed a most
agreeable acqaintance with Mr. Gisli Brinjulfsson, quite a young man,
but already enjoying a good literary reputation, both in his own
country and in Denmark. He is a graduate of the Iceland College,
and edited for two successive years the “NORTHURFARI,”[51]—an Iceland
“Annual.” This volume gives a résumé of the political news of the
world for the year previous, together with tales, original poetry, and
many interesting translations from English and American writers. But
the time of my departure from the country, arrives and these jottings
must close. As the vessel prepared to sail, several of my Iceland
friends came to see me off, and wish me a pleasant journey. As I
took their parting hands, I could not but think that this, in all human
probability, was our last meeting on earth. Promises to write and
send newspapers were mutually interchanged. The booming gun
echoes o’er the broad waters—the sail is set—the mountains fast
disappearing in the distance, and the shores of Iceland grow dim on
my sight. The little ship with the wandering pilgrim goes dancing
over the waves.
“The land is no longer in view,
The clouds have begun to frown;
But, with a stout vessel and crew,
We’ll say, let the storm come down.

“And the song of our hearts shall be,


While the winds and waters rave,—
A home, a home, on the firm-set lea!
And not on the bounding wave!”

FOOTNOTES:

45. “Þjoðolfur,” the Reykjavik newspaper.

46. “Efterretninger.”

47. To this excellent gentleman, Mr. Sivertsen, I am indebted for


numerous hospitalities. Forty-two years before, in 1810, he
entertained at his house Sir George Mackenzie and his
companions.

48. Widow of Sweinborn Egilson, a poet and literary man, who


died a few days after I left the country.

49. Librarian of the public library at Reykjavik.

50. Mr. Joseph W. Leng, Publisher and Bookseller, Saville street,


Hull; a gentleman of intelligence and high worth, to whom I
am indebted for many kind attentions to myself, as well as for
his favors to my young Iceland friend.

51. “Norðurfari,”—literally, Northern Journalist.


CHAPTER XXIX

And we sailed, and we flew, and went near the Maelstrom bay,
And we danced, and we frolicked, and we fiddled all the way.
OLD SONG.

A FINE morning in August found our little schooner dancing over the
waves of the Greenland strait. Towering up on our right, was the
lofty Snæfell Jokull, one of the highest mountains in Iceland. It has
the regular conical shape of most volcanoes. It is six thousand feet
high, being one-third higher than Vesuvius. At this season about
two-thirds of its height is black, and the rest is covered with
perpetual snow. When more than fifty miles to the south, I took a
drawing of it. It is near the end of a long peninsula, south of
Breithifiorth, and very nearly the westernmost point of Iceland. The
sharp outline of the mountain is distinctly visible in the clear
atmosphere here for more than a hundred miles. This volcano has
not had an eruption for several centuries. Two or three parties of
modern travelers have been to the summit. They have described the
ascent, after reaching the snow-line, as extremely dangerous. Wide
and deep cracks in the everlasting ice, and treacherous bridges of
snow, made the danger so great that they tied themselves in a
string, to a long rope, and walked about six feet apart. Then, if one
man fell through into a chasm, the rest pulled him out. No lives were
lost, however, in these excursions; the toil sweetened the pleasure,
the danger spiced it, and they were much gratified with their lofty
journey. To the east of Snæfell Jokull, we sailed by Stapi, a small
town near some famous basaltic cliffs, on the coast. Immense
perpendicular columns, and many thrown down, give the coast much
the appearance of the vicinity of the Giant’s Causeway, and the
island of Staffa. The coast here is more varied, and the scenery
more magnificent, than the north of Ireland; but there is no cave yet
discovered that will vie with the famed one of Fingal’s. Some of the
pillars here at Stapi are near eight feet in diameter, and all of them
of the regular geometrical shape so often seen in basaltic rocks.
They are like the cells in honeycombs, but solid, and generally
hexagonal, but sometimes heptagons and pentagons. Though the
time when these basalts were in a state of fusion is very remote, yet
there is no doubt of their volcanic character. If geologists and
mineralogists wish to see volcanic matter in every variety of form, let
them come to Iceland.
We passed by the Meal Sack and the Grenadier Islands, the first day,
and rounded the long nose of Cape Reykjanes, and the second
found us driving before a southwest wind; due east, along the south
coast of Iceland. We sailed near the Westmann Islands, and plainly
in sight of the lofty summits of Hekla, Torfa, Eyjafjalla, and Tindfjalla
Jokulls. The most singular curiosity on the south coast of Iceland,
that can be seen from the sea, is a group of rocks that I should call
The Needles, from their great resemblance to the “Needles” of the
Isle of Wight. They are near a little fishing village called Dyarholar, or
“Portland.” The rocks are shaped a little more like bodkins than
needles, and some of them rear their pointed heads near a hundred
feet high. They all stand in the ocean, some of them over a mile
from land. As we sailed east, the craggy summit of the Oræfa Jokull
showed his lofty and chilly head. The sides, too, were visible as well
as the summit, and perpendicular rocks and dark-looking caverns
showed the foot-prints of mighty convulsions of nature. The Oræfa
Jokull, forming part of that immense mountain known as Skaptar
Jokull, is, as I have mentioned before, the highest in Iceland. By
trigonometrical measurement, it is 6,760 feet high. Snæfell Jokull is
6,000 feet; Eyjafjalla Jokull, 5,900; and Hekla, 5,700. The Thiorsá
river, a stream larger than the Hudson or the Rhine, rises high up on
the side of Skaptar Jokull, 3,000 feet above the level of the sea, and
in a deep cañon in the lava, pours its resistless torrent down into the
ocean. Its rapid and turbulent current may be imagined. These
mountains in the interior of the country, the volcanic islands out at
sea, the rapid and powerful rivers, the Geysers, and innumerable hot
springs, along with the magnificent coast scenery, form the most
prominent physical features of Iceland.
For two days we were skirting the island on the south coast. This,
and the eastern part of Iceland, has few harbors. The coast is, much
of it, low and sandy, and difficult of approach. Some years since, a
French vessel was wrecked here in the winter season, and the crew
cast ashore, perfectly destitute. A few poor Icelanders that lived in
the vicinity, carried them to their huts, fed and took care of them,
and gave them shelter till spring. The next summer, on the annual
return of the French war-vessel that visits Iceland, the sailors were
taken home; and king Louis Philippe ordered a handsome
compensation and reward in money, to the Icelanders who had so
hospitably protected his shipwrecked sailors. They, however, did not
wish it; said they had only done their duty, and neither wanted nor
deserved compensation; and steadily refused to accept a single
penny. Determined to do something in return for their kindness,
Louis Philippe ordered his representative in Iceland to state that he
would educate at the University of France, four young Icelanders;
and the Governor, the Bishop, and the President of the College,
made choice of the young men who were to be recipients of the
favor. At the end of their term—four years—as many more were
selected; and thus the French government undertook the constant
care and expense of the education of four Iceland boys, who were
appointed for their ability, diligence, and good conduct, to receive
the bounty of the French government; and all for an act of humanity
towards a crew of shipwrecked sailors. The whole transaction
reflects the highest honor on all concerned. One of the young
gentlemen who was a recipient of this privilege, was a son of my
friend Mr. Sivertsen. After the French war-vessel, the unfortunate
LILLOISE, was lost, or failed to return from the Arctic sea, in connection
with one of the expeditions that went in search of her, there was a
scientific corps—a “Scandinavian Commission”—organized, of
learned men from France, Denmark, and Iceland, to gather
information, make drawings of landscapes, and collect specimens of
mineralogy, botany, and the various branches of natural history. The
commission was headed by M. Paul Geimar, and our young Icelander
was one of the party. The results of the expedition, in a scientific
point of view, were of the highest value. A work was published,
containing several folio volumes of plates, many of them colored,
and the Journal of the Expedition, in six octavos; and altogether it
forms the most valuable work of the kind extant. It comprises
Iceland, Greenland, Lapland, and Spitzbergen; and nothing, either of
a geographical, scientific, or historical nature has been omitted.
Along with portraits of Geimar and others of the Commission, is a
“counterfeit presentment” of young Sivertsen; and his is one of the
finest faces ever delineated. It has the lively, intelligent
countenance, lofty brow, and beaming eye of the Anglo-Saxons, and
equal to the finest specimens of the Caucasian race in any part of
the world. This promising young man died in France, a few years
after his return from the North, universally esteemed by all, and by
none more than by Louis Philippe himself.
But the winds are drifting us lazily to the eastward. We sailed north
of Faroe, and saw the cliffs of the lofty Stromoe towering upwards
like the ruins of some gigantic temple. The return voyage was all
beautiful September weather. Our passengers—except the bachelor
of the present writing—consisted of twelve young Iceland ladies, and
a small lad; and we had a regular “jolly” time. Several of the young
ladies were singers, and two of them had guitars. Nearly every
afternoon we had a dance. The young ladies made fast progress in
English—and Yankee—manners, customs, language, and dancing. I
also got well posted up in Icelandic, particularly in the sentimental,—
or, as Sam Weller would say, in the more “tenderer vords.” Guitar
music, Iceland hymns, the violin, and “threading the dance” on a
rocking deck, were all matters of every-day occurrence. Did I say
every day? Not with me. But the master of the Sölöven, Captain
Heinrich Stilhoff, was certainly the most reckless, irreligious man for
a sea-captain, that ever I saw in my life. Had a sober traveler come
alongside of us on Sunday, he would have been bothered to have
found out what kind of worship we had aboard. His reflections would
probably have been like old Lambro’s, when he returned, from his
piratical cruise, to his island and his daughter. Suppose such a one in
his yacht had come up with us:
A Christian he, and as our ship he nears,
He looks aboard, and finds no signs of idling,
He hears—alas! no music of the spheres,
But an unhallowed, earthly sound of fiddling!
A melody which makes him doubt his ears,
The cause being past his guessing or unriddling:
But, lo! it is the sailors all a prancing,
The women, too, and Captain Stilhoff, dancing!

It does not speak well for the Danish people and nation, that their
mail-ship, the only government vessel running between Denmark
and Iceland, is commanded by a man of the character of Captain
Stilhoff; and I cannot think it will long continue so. Commanding a
vessel carrying the Government dispatches, and having the most
popular and direct passenger traffic between the two countries, a
profligate who openly boasts of debauching his female passengers,
defenseless women, the sisters and daughters of the citizens of both
countries; a state of things that certainly does not reflect any honor
on the proprietors of the vessel, or show much sagacity in their
choice of a commander.
On, on, goes our little bark; the northern shore
“Fades o’er the waters blue;
The night winds sigh, the breakers roar,
And shrieks the wild sea-mew.”

Old Norway’s coast appears, and we are several days in sight of the
brown and snowy mountains, and little villages of wooden houses.
The thirteenth day, we passed Cape Lindesness, and Christiansand.
We were then within two hundred and fifty miles of Copenhagen—
only a few hours’ voyage for a steamship; but we had no steam a-
board, except what might be found in certain kettles and casks, and
these did not aid our progress much. I thought two days, at farthest
would suffice for the rest of our voyage; but Boreas was not in the
ascendant, nor any of his brethren either, much, for we had very
little wind from any quarter. The current in the Skager Rack took us
outwardly about two miles an hour, and the wind was southeasterly,
and we were bound in. One tack would throw us near the coast of
Norway, and the next brought us along the low, flat sands of
Jutland. We progressed from twenty-five to fifty miles a day. Several
huge steamers boomed past us, with their black sides, and volumes
of smoke, and swift progress. Some of them were bound into the
Baltic, and some out, and some to Norwegian ports. At last we
rounded the Skagen Horn, and entered the Cattegat. Finally, the
towers of Elsinore Castle appeared; and, a breeze springing up from
the north, we dropped anchor before Copenhagen, the twentieth
day after leaving Iceland; and, in a most terrible rain—so anxious
were we to tread the land again—all the passengers were set on the
quay, and found lodgings amid the turmoil of a great city.
GENERAL INDEX.

Adam of Bremen, page 41.


Ætna, 142, 151.
Agriculture in Iceland, 178, 303.
Almannagjá, 73.
Althing, or Iceland Congress, 42, 45, 78.
Althing, Journal of, 296.
America discovered by the Northmen, 36.
Angelica Archangelica, 125.
Angling, 78.
Annexation of an island to Denmark, 148.
Apavatn Lake, 97.
Arbrandsá river, 115.
Arnason, Jon, Librarian of Public Library, 309.
Atmosphere, its transparency, 141.

Barrow, the English traveler, 206.


Bath in the Geyser, 111.
Beard a protection against the elements, 121.
Beards worn in Iceland, 60.
Beards worn by the gods, 249.
Bessastath, 63.
Biarni Heriulfson, the First Discoverer of America, 63.
Birds—the curlew, 169;
cormorant, 223;
eider-duck, 219;
western eider, 221;
fulmar, 168;
gannet, or solan goose, 31, 224;
Iceland gull, 228;
skua gull, 228;
jer-falcon, 230;
white owl, 229;
penguin, 222;
plover, 169;
pochard, 118;
ptarmigan, 90;
puffin, 163, 168;
ravens, 114, 170;
sea-fowl on the Westmann Islands, 163;
on the coast of Iceland, 198;
snow-birds, 226;
tern, or sea-swallow, 107, 198.
Bjarnarfell mountain, 112.
Bjolfell mountain, 141, 145.
Blacksmithing, 89.
Blue berry, the only fruit in Iceland, 157.
Books published in Iceland, 295.
Bræthratunga church, 119.
Brandy, use of it in Iceland, 180.
Breithifjorth, 313.
Briem, Rev. Johan, 123.
Brinjulfsson, Gisli, 311.
Bruará or Bridge River, 97.
Bruce’s Address, in Icelandic and English, 286–7.
Brydone, 93, 135.

Caraway growing spontaneously in Iceland, 125.


Cathedral worship in Reykjavik, 306.
Cattegat, 17, 21, 22, 320.
Cave in a hill, 96.
Cave of Surtshellir, 109, 243, note.
Christianity introduced into Iceland, 82.
Christiansand, 23, 319.
Churchyards and burial customs, 178.
Clays, beautifully colored, 102, 191, 200, 208.
College at Reykjavik, 57.
Columbus, his visit to Iceland, 39.
Copenhagen, 17, 320.
Craters of Hekla, 138, 143.

Dancing on ship-board, 317.


Danish laws in Iceland, 298.
Danish merchants in Reykjavik, 306.
Dining on Mount Hekla, 140.
Diseases in Iceland, 305.
Domestic animals of Iceland, 55.
Domestic labor of the Icelanders, 58, 293.

Eddas, poems of the early Icelanders, 271.


Edda, the Elder; ascribed to Sæmund Frode, 271.
Edda, the Younger; ascribed to Snorri Sturlason, 272.
Egilson, Sweinborn, 52, 308.
Eider-down beds, 127, 218.
Elsinore castle and town, 17, 22, 320.
Eric the Red, 35.
Ericsson, descendant of Eric the Red, 36.
Exports of Iceland, 56, 298.
Eyjafjalla Jokull, 142, 151, 160, 315.

Farming in Iceland, 179, 182, 303.


Farming tools, 117.
Faroe Isles, 24, 25, 233.
Feasts, in old times, 59.
Ferryman on the Hvitá river, 185.
Fish, Iceland method of curing, 215.
Fishing season in Iceland, 116.
Fish lake, its disappearance, 152.
Finn Magnusen, 37.
Finnsen, William, Treasurer of Iceland, 28.
Floki, a pirate, 170.
Flower on Mount Hekla, 136.
Flowers on a desert island, 121.
Fourth of July at sea, 23, 24.
Franklin’s Story of a Whistle, in Icelandic, 289.
French officers traveling in Iceland, 66, 70, 76, 84.
French vessel wrecked in Iceland, 315.

Game in Iceland, 55, 56, 90, 169, 170.


Gardar Swarfarson, 35.
Garden vegetables, 62, 179.
Geimar’s Iceland, Greenland, and Spitzbergen, 317.
Geographical names and terms, 85.
Geyser, Eruptions of, 105.
Geyser, its appearance when still, 100.
Gissur Thorvaldsen, son-in-law of Snorri Sturlason, 274.
Graba, a Danish traveler in Faroe, 236.
Greenland, discovery of, 35.
Grenadier island, 31, 314.
Grænavatn, or Green Lake, 142, 201.
Gudmundsen, Thomas, 175.

Hacon, King of Norway, 274.


Hafnarfiorth, 63, 213, 215.
Hávamál, an Eddaic Poem, 275.
Haying season, 303.
Heath, 157, 158, 159.
Heimskringla, 275.
Hjalli, 195.
Hekla, ascent of, 132.
Catalogue of its eruptions, 153.
its height, 315.
its last eruption, in 1845, 134, 138.
seen from a distance, 95, 115, 128, 161, 314.
View from the summit, 140, 151.
Helsingborg, 21.
Herdisa, wife of Snorri Sturlason, 273.
Hlitharvatn, 198.
Holland, Dr. 135, 297.
“Horrible Lava,” 211.
Horses in Iceland, 65, 116, 129, 298.
Hospitality of the Icelanders, 197.
Hot Springs, 187.
Hraungerthi, 177.
Hruni, and its hospitable clergyman, 122.
Hunting sea-fowl in the Westmann islands, 163.
Hvitá or White river, 118, 119, 185.

Iceland, its discovery and settlement, 35.


its situation and extent, 48.
Hymn, Jacob weeping over Rachel, 288.
Newspaper, quotation from, 291.
Youths educated in France, 316.
Icelander in the Wars of Napoleon, 293.

You might also like