SlideShare a Scribd company logo
Read Anytime Anywhere Easy Ebook Downloads at ebookmeta.com
Nim in Action 1st Edition Dominik Picheta
https://ebookmeta.com/product/nim-in-action-1st-edition-
dominik-picheta/
OR CLICK HERE
DOWLOAD EBOOK
Visit and Get More Ebook Downloads Instantly at https://ebookmeta.com
Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.
Agile Leadership in Practice Applying Management 3 0 2nd
Edition Dominik Maximini
https://ebookmeta.com/product/agile-leadership-in-practice-applying-
management-3-0-2nd-edition-dominik-maximini/
ebookmeta.com
Test Driven iOS Development with Swift 3 Hauser Dr Dominik
https://ebookmeta.com/product/test-driven-ios-development-with-
swift-3-hauser-dr-dominik/
ebookmeta.com
Flexibility Planning in Distribution Networks A
Flexibility Planning Model for the Consumer Goods Industry
1st Edition Dominik Pfeiffer
https://ebookmeta.com/product/flexibility-planning-in-distribution-
networks-a-flexibility-planning-model-for-the-consumer-goods-
industry-1st-edition-dominik-pfeiffer/
ebookmeta.com
Mayor of Elf Town 2 1st Edition Dante King
https://ebookmeta.com/product/mayor-of-elf-town-2-1st-edition-dante-
king-3/
ebookmeta.com
The Experienced Soul 1st Edition Glenda Abramson
https://ebookmeta.com/product/the-experienced-soul-1st-edition-glenda-
abramson/
ebookmeta.com
Learn Lua for iOS Game Development Jayant Varma
https://ebookmeta.com/product/learn-lua-for-ios-game-development-
jayant-varma/
ebookmeta.com
The War Came To Us 1st Edition Christopher Miller
https://ebookmeta.com/product/the-war-came-to-us-1st-edition-
christopher-miller/
ebookmeta.com
Sor Juana Inde la Cruz and the Gender Politics of
Knowledge in Colonial Mexico 1st Edition Stephanie Kirk
https://ebookmeta.com/product/sor-juana-inde-la-cruz-and-the-gender-
politics-of-knowledge-in-colonial-mexico-1st-edition-stephanie-kirk/
ebookmeta.com
Sucker Punch Girls On Top Series 1st Edition Dee Ellis
https://ebookmeta.com/product/sucker-punch-girls-on-top-series-1st-
edition-dee-ellis-3/
ebookmeta.com
AVR Workshop: A Hands-On Introduction with 60 Projects
(NOT genuine pdf) 1st Edition John Boxall
https://ebookmeta.com/product/avr-workshop-a-hands-on-introduction-
with-60-projects-not-genuine-pdf-1st-edition-john-boxall/
ebookmeta.com
Nim in Action 1st Edition Dominik Picheta
Nim in Action
Dominik Picheta
Copyright
For online information and ordering of this and other Manning books,
please visit www.manning.com. The publisher offers discounts on this
book when ordered in quantity. For more information, please contact
Special Sales Department
Manning Publications Co.
20 Baldwin Road
PO Box 761
Shelter Island, NY 11964
Email: orders@manning.com
©2017 by Manning Publications Co. All rights reserved.
No part of this publication may be reproduced, stored in a retrieval
system, or transmitted, in any form or by means electronic,
mechanical, photocopying, or otherwise, without prior written
permission of the publisher.
Many of the designations used by manufacturers and sellers to
distinguish their products are claimed as trademarks. Where those
designations appear in the book, and Manning Publications was
aware of a trademark claim, the designations have been printed in
initial caps or all caps.
Recognizing the importance of preserving what has been written,
it is Manning’s policy to have the books we publish printed on acid-
free paper, and we exert our best efforts to that end. Recognizing
also our responsibility to conserve the resources of our planet,
Manning books are printed on paper that is at least 15 percent
recycled and processed without the use of elemental chlorine.
Manning Publications Co.
20 Baldwin Road
PO Box 761
Shelter Island, NY 11964
Development editors: Cynthia Kane, Dan Seiter,
Marina Michaels
Technical development editor: Andrew West
Review editor: Donna Clements
Project editor: Karen Gulliver
Copyeditor: Andy Carroll
Proofreader: Katie Tennant
Technical proofreader: Michiel Trimpe
Typesetter: Dottie Marsico
Cover designer: Marija Tudor
ISBN 9781617293436
Printed in the United States of America
1 2 3 4 5 6 7 8 9 10 – EBM – 22 21 20 19 18 17
Brief Table of Contents
Copyright
Brief Table of Contents
Table of Contents
Preface
Acknowledgments
About this Book
About the Author
About the Cover Illustration
1. The basics of Nim
Chapter 1. Why Nim?
Chapter 2. Getting started
2. Nim in practice
Chapter 3. Writing a chat application
Chapter 4. A tour through the standard library
Chapter 5. Package management
Chapter 6. Parallelism
Chapter 7. Building a Twitter clone
3. Advanced concepts
Chapter 8. Interfacing with other languages
Chapter 9. Metaprogramming
Appendix A. Getting help
Appendix B. Installing Nim
Nim Reference
Index
List of Figures
List of Tables
List of Listings
Table of Contents
Copyright
Brief Table of Contents
Table of Contents
Preface
Acknowledgments
About this Book
About the Author
About the Cover Illustration
1. The basics of Nim
Chapter 1. Why Nim?
1.1. What is Nim?
1.1.1. Use cases
1.1.2. Core features
1.1.3. How does Nim work?
1.2. Nim’s benefits and shortcomings
1.2.1. Benefits
1.2.2. Areas where Nim still needs to improve
1.3. Summary
Chapter 2. Getting started
2.1. Nim syntax
2.1.1. Keywords
2.1.2. Indentation
2.1.3. Comments
2.2. Nim basics
2.2.1. Basic types
2.2.2. Defining variables and other storage
2.2.3. Procedure definitions
2.3. Collection types
2.3.1. Arrays
2.3.2. Sequences
2.3.3. Sets
2.4. Control flow
2.5. Exception handling
2.6. User-defined types
2.6.1. Objects
2.6.2. Tuples
2.6.3. Enums
2.7. Summary
2. Nim in practice
Chapter 3. Writing a chat application
3.1. The architecture of a chat application
3.1.1. What will the finished application look like?
3.2. Starting the project
3.3. Retrieving input in the client component
3.3.1. Retrieving command-line parameters supplied
by the user
3.3.2. Reading data from the standard input stream
3.3.3. Using spawn to avoid blocking input/output
3.4. Implementing the protocol
3.4.1. Modules
3.4.2. Parsing JSON
3.4.3. Generating JSON
3.5. Transferring data using sockets
3.5.1. What is a socket?
3.5.2. Asynchronous input/output
3.5.3. Transferring data asynchronously
3.6. Summary
Chapter 4. A tour through the standard library
4.1. A closer look at modules
4.1.1. Namespacing
4.2. Overview of the standard library
4.2.1. Pure modules
4.2.2. Impure modules
4.2.3. Wrappers
4.2.4. Online documentation
4.3. The core modules
4.4. Data structures and algorithms
4.4.1. The tables module
4.4.2. The sets module
4.4.3. The algorithms
4.4.4. Other modules
4.5. Interfacing with the operating system
4.5.1. Working with the filesystem
4.5.2. Executing an external process
4.5.3. Other operating system services
4.6. Understanding and manipulating data
4.6.1. Parsing command-line arguments
4.7. Networking and the internet
4.8. Summary
Chapter 5. Package management
5.1. The Nim package manager
5.2. Installing Nimble
5.3. The nimble command-line tool
5.4. What is a Nimble package?
5.5. Installing Nimble packages
5.5.1. Using the install command
5.5.2. How does the install command work?
5.6. Creating a Nimble package
5.6.1. Choosing a name
5.6.2. A Nimble package’s directory layout
5.6.3. Writing the .nimble file and sorting out
dependencies
5.7. Publishing Nimble packages
5.8. Developing a Nimble package
5.8.1. Giving version numbers meaning
5.8.2. Storing different versions of a single package
5.9. Summary
Chapter 6. Parallelism
6.1. Concurrency vs. parallelism
6.2. Using threads in Nim
6.2.1. The threads module and GC safety
6.2.2. Using thread pools
6.2.3. Exceptions in threads
6.3. Parsing data
6.3.1. Understanding the Wikipedia page-counts
format
6.3.2. Parsing the Wikipedia page-counts format
6.3.3. Processing each line of a file efficiently
6.4. Parallelizing a parser
6.4.1. Measuring the execution time of
sequential_counts
6.4.2. Parallelizing sequential_counts
6.4.3. Type definitions and the parse procedure
6.4.4. The parseChunk procedure
6.4.5. The parallel readPageCounts procedure
6.4.6. The execution time of parallel_counts
6.5. Dealing with race conditions
6.5.1. Using guards and locks to prevent race
conditions
6.5.2. Using channels so threads can send and receive
messages
6.6. Summary
Chapter 7. Building a Twitter clone
7.1. Architecture of a web application
7.1.1. Routing in microframeworks
7.1.2. The architecture of Tweeter
7.2. Starting the project
7.3. Storing data in a database
7.3.1. Setting up the types
7.3.2. Setting up the database
7.3.3. Storing and retrieving data
7.3.4. Testing the database
7.4. Developing the web application’s view
7.4.1. Developing the user view
7.4.2. Developing the general view
7.5. Developing the controller
7.5.1. Implementing the /login route
7.5.2. Extending the / route
7.5.3. Implementing the /createMessage route
7.5.4. Implementing the user route
7.5.5. Adding the Follow button
7.5.6. Implementing the /follow route
7.6. Deploying the web application
7.6.1. Configuring Jester
7.6.2. Setting up a reverse proxy
7.7. Summary
3. Advanced concepts
Chapter 8. Interfacing with other languages
8.1. Nim’s foreign function interface
8.1.1. Static vs. dynamic linking
8.1.2. Wrapping C procedures
8.1.3. Type compatibility
8.1.4. Wrapping C types
8.2. Wrapping an external C library
8.2.1. Downloading the library
8.2.2. Creating a wrapper for the SDL library
8.2.3. Dynamic linking
8.2.4. Wrapping the types
8.2.5. Wrapping the procedures
8.2.6. Using the SDL wrapper
8.3. The JavaScript backend
8.3.1. Wrapping the canvas element
8.3.2. Using the Canvas wrapper
8.4. Summary
Chapter 9. Metaprogramming
9.1. Generics
9.1.1. Generic procedures
9.1.2. Generics in type definitions
9.1.3. Constraining generics
9.1.4. Concepts
9.2. Templates
9.2.1. Passing a code block to a template
9.2.2. Parameter substitution in templates
9.2.3. Template hygiene
9.3. Macros
9.3.1. Compile-time function execution
9.3.2. Abstract syntax trees
9.3.3. Macro definition
9.3.4. Arguments in macros
9.4. Creating a configuration DSL
9.4.1. Starting the configurator project
9.4.2. Generating the object type
9.4.3. Generating the constructor procedure
9.4.4. Generating the load procedure
9.4.5. Testing the configurator
9.5. Summary
Appendix A. Getting help
A.1. Real-time communication
A.2. Forum
A.3. Other communication methods
Appendix B. Installing Nim
B.1. Installing the Nim compiler
B.1.1. Getting up-to-date installation info
B.1.2. Building from source
B.2. Installing the Aporia IDE
B.3. Testing your new development environment
B.4. Troubleshooting
B.4.1. Nim command not found
B.4.2. Nim and C compiler disagree on target architecture
B.4.3. Could not load DLL
Nim Reference
Index
List of Figures
List of Tables
List of Listings
Preface
Nim has been my labor of love over the years. Gradually, from the
time I discovered it, I’ve become increasingly involved in its
development. Although I sacrificed considerable time working on it,
Nim gave back in the form of experience and knowledge. My work
with Nim has taught me far more than any other work or studies
have done. Many opportunities have also opened up for me, a
shining example being this book.
I never actually thought I would end up writing a book, and until a
Manning acquisitions editor got in touch with me, I didn’t realize that
I wanted to. While planning this book, I looked to other books and
determined where they fell short. I realized that this, the first book
on Nim, must be written for programmers with a bit of experience. I
decided that I wanted to write a book that teaches programmers
about Nim, but that also teaches other programming concepts that
work well in Nim’s particular programming paradigms. These
concepts can also be applied to other programming languages and
have been very useful in my career.
My other goal for this book was to make it fun and engaging. I
decided to do this by building some chapters around small projects.
The projects are designed to be practical and to teach a number of
Nim features and concepts. By following along and developing these
projects, you’ll gain hands-on experience developing Nim
applications. This should put you in a good position to write your
own software, which is the ultimate goal of this book.
Nim in Action covers a lot, but it can’t cover everything. It shouldn’t
be viewed as a complete Nim reference; instead, it should be
considered a practical guide to writing software in Nim.
It’s my hope that this book helps you learn Nim and that you find it
a useful reference for many years to come. I and the Nim
community are at your disposal and are available online to help you
solve any problems you run into. Thank you for purchasing this book
and taking an interest in Nim.
Acknowledgments
First, I would like to thank Andreas Rumpf for creating Nim and for
both his reviews and words of encouragement throughout the
development of this book. Andreas created a one-of-a-kind
programming language, and without his commitment to Nim, this
book wouldn’t exist.
This book wouldn’t be what it is today without the brilliant and
passionate people at Manning publications. I give my thanks to
Marjan Bace, who made it possible to publish this book; my editors
Cynthia Kane, Dan Seiter, and Marina Michaels, for helping me
improve my writing; and the production team, including Andy
Carroll, Janet Vail, Karen Gulliver, and Katie Tennant.
I thank the Nim community and everyone who participated in
reviews and provided feedback on the manuscript, including
technical proofreader Michiel Trimpe, and the following reviewers:
Andrea Ferretti, Yuriy Glukhov, Michał Zieliński, Stefan Salewski,
Konstantin Molchanov, Sébastien Ménard, Abel Brown, Alessandro
Campeis, Angelo Costa, Christoffer Fink, Cosimo Attanasi, James
Anaipakos, Jonathan Rioux, Marleny Nunez, Mikkel Arentoft, Mohsen
Mostafa Jokar, Paulo Nuin, Peter Hampton, Robert Walsh, Samuel
Bosch, Thomas Ballinger, and Vincent Keller.
Thanks also to the readers of the Manning Early Access Program
(MEAP). Their corrections and comments on the manuscript as it
was being written were invaluable.
Finally, I’d like to thank my family and friends, who in their own way
steered my life in a positive direction, leading me to authoring this
book. First, I thank my mother, Bogumiła Picheta, for her bravery
and hard work, without which I wouldn’t have had the means to
start my programming journey, and I especially thank her for making
a hard decision that turned out to be very beneficial for my future. I
would also like to thank my uncle, Piotr Kossakowski-Stefański, and
aunt, Marzena Kossakowska--Stefańska, for inspiring and challenging
me to write software, and also for always being there to share their
advice. Thanks to Ilona, Maciej Sr., and Maciej Jr. Łosinski for my
first exposure to a computer and the internet. And I thank Kazimierz
Ślebioda, a.k.a Kazik, for the Age of Empires 2 LAN parties and for
showing me how delicious chicken with garlic can be.
Most of all, I thank my partner, Amy-Leigh Shaw, for always
believing in me, and for her patience and support throughout my
work on this book. I love you very much Amy, and am lucky to have
you.
About this Book
Nim in Action is a practical way to learn how to develop software
using the open source Nim programming language. This book
includes many examples, both large and small, to show and teach
you how software is written in Nim.
Nim is unique. It’s multi-paradigm, and unlike most other languages,
it doesn’t emphasize object-oriented programming. Because of this, I
encourage you to consciously absorb the styles used in this book
instead of applying your own. Nim in Action will teach you a set of
best practices and idioms that you’ll also find useful in other
programming languages.
By learning Nim, you’ll discover a language that straddles the lines
between efficiency, expressiveness, and elegance. Nim will make you
productive and your end users happy.
Who should read this book
This is by no means a beginner’s book. It assumes that you know at
least one other programming language and have experience writing
software in it. For example, I expect you to be aware of basic
programming language features such as functions, variables, and
types. The fundamentals of programming aren’t explained in this
book.
This book will teach you how to develop practical software in the
Nim programming language. It covers features that are present in all
programming languages, such as concurrency, parallelism, user-
defined types, the standard library, and more. In addition, it covers
Nim features that you may not be familiar with, such as
asynchronous input/output, metaprogramming, and the foreign
function interface.
How the book is organized
The book is divided into three parts and includes a total of nine
chapters.
Part 1 introduces the language and its basic features:
Chapter 1 explains what Nim is, compares it to other
programming languages, and discusses its strengths and
weaknesses.
Chapter 2 teaches the basics, such as the syntax and
fundamental features of the language. This includes a
demonstration of procedure definitions and exception handling.
Part 2 includes a wide range of examples to show how Nim is used in
practice:
Chapter 3 is where you’ll develop your first nontrivial Nim
application. The primary purpose of this application is
communication: it allows messages to be sent through a
network. You’ll learn, among other things, how to create
command-line interfaces, parse JSON, and transfer data over a
network in Nim.
Chapter 4 gives an overview of the standard library, particularly
the parts of it that aren’t covered in other chapters but are
useful.
Chapter 5 discusses package management in Nim and teaches
you how to create your own packages and make them available
to others.
Chapter 6 explains what parallelism is and how it can be applied
to different programming tasks. You’ll see a parsing example,
demonstrating different ways to parse data in Nim and how
parsing can be parallelized.
Chapter 7 is where you’ll develop your second nontrivial Nim
application: a web application based on Twitter. You’ll learn how
to store data in a SQL database and generate HTML.
Part 3 introduces some advanced Nim features:
Chapter 8 looks at the foreign function interface and shows how
it can be used to make use of C and JavaScript libraries. You’ll
develop a simple application that draws the letter N on the
screen, first using a C library and then using JavaScript’s Canvas
API.
Chapter 9 explains what metaprogramming is, discussing
features such as generics, templates, and macros. At the end of
this chapter, you’ll use macros to create a domain-specific
language.
You may wish to skip the first two chapters if you already know the
basics of Nim. I recommend reading the book from beginning to
end, and I especially encourage you to follow along with the
examples. Each chapter teaches you something new about Nim,
even if it primarily focuses on a standalone example. If you get
stuck, feel free to get in touch with me or the Nim community.
Appendix A contains information on how to get help, so use it to
your advantage.
Code conventions and downloads
The source code examples in this book are fairly close to the
samples that you’ll find online, but for the sake of brevity, many of
the comments were removed. The online samples include a lot of
comments to make them as easy to understand as possible, so
you’re encouraged to take a look at them to learn more.
The source code is available for download from the publisher’s
website at https://manning.com/books/nim-in-action and from GitHub at
https://github.com/dom96/nim-in-action-code. Nim is still evolving, so be
sure to watch the repository for changes. I’ll do my best to keep it
up to date with the latest Nim version.
This book contains many examples of source code, both in
numbered listings and inline with normal text. In both cases, source
code is formatted in a mono-spaced typeface like this, to
distinguish it from ordinary text. Sometimes code is also in bold
to highlight code that has changed from previous steps in the
chapter, such as when a new feature is added to existing code.
In many cases, the original source code has been reformatted for
print; we’ve added line breaks and reworked the indentation to
accommodate the available page space in the book. In rare cases,
even this was not enough, and listings include line-continuation
markers ( ). Additionally, comments in the source code have often
been removed from the listings when the code is described in the
text.
Book forum
The purchase of Nim in Action includes free access to a private web
forum run by Manning Publications, where you can make comments
about the book, ask technical questions, and receive help from the
author and from other users. To access the forum, go to
https://forums.manning.com/forums/nim-in-action. You can also learn
more about Manning’s forums and the rules of conduct at
https://forums.manning.com/forums/about.
Manning’s commitment to our readers is to provide a venue where a
meaningful dialogue between individual readers and between
readers and the author can take place. It is not a commitment to
any specific amount of participation on the part of the author, whose
contribution to the forum remains voluntary (and unpaid). We
suggest you try asking him some challenging questions lest his
interest stray! The forum and the archives of previous discussions
will be accessible from the publisher’s website as long as the book is
in print.
About the Author
DOMINIK PICHETA (@d0m96, picheta.me) is a Computer Science
student at Queen’s University Belfast. He is one of the core
developers of the Nim programming language and has been using it
for most of its history. He also wrote Nimble, the official Nim
package manager, and many other Nim libraries and tools.
About the Cover Illustration
The figure on the cover of Nim in Action is captioned “Morlaque de
l’Isle Opus,” or “A Morlach from the Island of Opus.” The Morlachs
were a Vlach people originally centered around the eastern Adriatic
port of Ragusa, or modern Dubrovnik. The illustration is taken from
a collection of dress costumes from various countries by Jacques
Grasset de Saint-Sauveur (1757–1810), titled Costumes de Différents
Pays, published in France in 1797. Each illustration is finely drawn
and colored by hand. The rich variety of Grasset de Saint-Sauveur’s
collection reminds us vividly of how culturally apart the world’s
towns and regions were just 200 years ago. Isolated from each
other, people spoke different dialects and languages. In the streets
or in the countryside, it was easy to identify where they lived and
what their trade or station in life was just by their dress.
The way we dress has changed since then and the diversity by
region, so rich at the time, has faded away. It is now hard to tell
apart the inhabitants of different continents, let alone different
towns, regions, or countries. Perhaps we have traded cultural
diversity for a more varied personal life—certainly, for a more varied
and fast-paced technological life.
At a time when it is hard to tell one computer book from another,
Manning celebrates the inventiveness and initiative of the computer
business with book covers based on the rich diversity of regional life
of two centuries ago, brought back to life by Grasset de Saint-
Sauveur’s pictures.
Part 1. The basics of Nim
This part of the book begins your study of the Nim programming
language. It doesn’t assume you know much about Nim, so chapter 1
begins by looking at the characteristics of the language, what makes
it different from other languages, and how it’s used in the real world.
Chapter 2 looks at some of the most commonly used elements of any
programming language—the syntax, semantics, and type system—
and in doing so teaches you the necessary foundations for writing
simple applications in Nim.
Chapter 1. Why Nim?
This chapter covers
What Nim is
Why you should learn about it
Comparing Nim to other programming languages
Use cases
Strengths and weaknesses
Nim is still a relatively new programming language. In fact, you’re
holding one of the very first books about it. The language is still not
fully complete, but core aspects, like its syntax, the semantics of
procedures, methods, iterators, generics, templates, and more, are all
set in stone. Despite its newness, there has been significant interest in
Nim from the programming community because of the unique set of
features that it implements and offers its users.
This chapter answers questions that you may ask before learning Nim,
such as why you might want to use it. In this chapter, I outline some of
the common practical uses of Nim, compare it to other programming
languages, and discuss some of its strengths and weaknesses.
1.1. What is Nim?
Nim is a general-purpose programming language designed to be
efficient, expressive, and elegant. These three goals are difficult to
achieve at the same time, so Nim’s designers gave each of them
different priorities, with efficiency being the most important and
elegance being the least.
But despite the fact that elegance is relatively unimportant to Nim’s
design, it’s still considered during the design process. Because of this,
the language remains elegant in its own right. It’s only when trade-offs
between efficiency and elegance need to be made that efficiency wins.
On the surface, Nim shares many of Python’s characteristics. In
particular, many aspects of Nim’s syntax are similar to Python’s,
including the use of indentation to delimit scope as well as the
tendency to use words instead of symbols for certain operators. Nim
also shares other aspects with Python that aren’t related to syntax,
such as the highly user-friendly exception tracebacks, shown here:
Traceback (most recent call last)
request.nim(74) request
request.nim(25) getUsers
json.nim(837) []
tables.nim(147) []
Error: unhandled exception: key not found: totalsForAllResults
[KeyError]
You’ll also see many differences, especially when it comes to the
semantics of the language. The major differences lie within the type
system and execution model, which you’ll learn about in the next
sections.
A little bit about Nim’s history
Andreas Rumpf started developing Nim in 2005. The project soon
gained support and many contributions from the open source
community, with many volunteers around the world contributing code
via pull requests on GitHub. You can see the current open Nim pull
requests at https://github.com/nim-lang/Nim/pulls.
Contributing to Nim
The compiler, standard library, and related tools are all open source
and written in Nim. The project is available on GitHub, and everyone is
encouraged to contribute. Contributing to Nim is a good way to learn
how it works and to help with its development. See Nim’s GitHub page
for more information: https://github.com/nim-lang/Nim#contributing.
1.1.1. Use cases
Nim was designed to be a general-purpose programming language
from the outset. As such, it consists of a wide range of features that
make it usable for just about any software project. This makes it a
good candidate for writing software in a wide variety of application
domains, ranging from web applications to kernels. In this section, I’ll
discuss how Nim’s features and programming support apply in several
use cases.
Although Nim may support practically any application domain, this
doesn’t make it the right choice for everything. Certain aspects of the
language make it more suitable for some categories of applications
than others. This doesn’t mean that some applications can’t be written
using Nim; it just means that Nim may not support the code styles that
are best suited for writing some kinds of applications.
Nim is a compiled language, but the way in which it’s compiled is
special. When the Nim compiler compiles source code, it first translates
the code into C code. C is an old but well supported systems
programming language that allows easier and more direct access to
the physical hardware of the machine. This makes Nim well suited to
systems programming, allowing projects such as operating systems
(OSs), compilers, device drivers, and embedded system software to be
written.
Internet of Things (IoT) devices, which are physical devices with
embedded electronics that are connected to the internet, are good
targets for Nim, primarily thanks to the power offered by Nim’s ease of
use and its systems programming capabilities.
A good example of a project making use of Nim’s systems
programming features is a very simple OS called NimKernel available
on GitHub: https://github.com/dom96/nimkernel.
How does Nim compile source code?
I describe Nim’s unusual compilation model and its benefits in detail in
section 1.1.3.
Applications written in Nim are very fast; in many cases, just as fast as
applications written in C, and more than thirteen times faster than
applications written in Python. Efficiency is the highest priority, and
some features make optimizing code easy. This goes hand in hand with
a soft real-time garbage collector, which allows you to specify the
amount of time that should be spent collecting memory. This feature
becomes important during game development, where an ordinary
garbage collector may slow down the rendering of frames on the
screen if it uses too much time collecting memory. It’s also useful in
real-time systems that need to run in very strict time frames.
Nim can be used alongside other much slower languages to speed up
certain performance-critical components. For example, an application
written in Ruby that requires certain CPU-intensive calculations can be
partially written in Nim to gain a considerable speed advantage. Such
speed-ups are important in areas such as scientific computing and
high-speed trading.
Applications that perform I/O operations, such as reading files or
sending data over a network, are also well supported by Nim. Web
applications, for example, can be written easily using a number of web
frameworks like Jester (https://github.com/dom96/jester). Nim’s script-like
syntax, together with its powerful, asynchronous I/O support, makes it
easy to develop these applications rapidly.
Command-line applications can benefit greatly from Nim’s efficiency.
Also, because Nim applications are compiled, they’re standalone and so
don’t require any bulky runtime dependencies. This makes their
distribution incredibly easy. One such application written in Nim is
Nimble; it’s a package manager for Nim that allows users to install Nim
libraries and applications.
These are just a few use cases that Nim fits well; it’s certainly not an
exhaustive list.
Another thing to keep in mind is that, at the time of writing, Nim is still
in development, not having yet reached version 1.0. Certain features
haven’t been implemented yet, making Nim less suited for some
applications. For example, Nim includes a backend that allows you to
write JavaScript applications for your web pages in Nim. This backend
works, but it’s not yet as mature as the rest of the language. This will
improve with time.
Of course, Nim’s ability to compile to JavaScript makes it suitable for
full-stack applications that need components that run on a server and
in a browser. This is a huge advantage, because code can easily be
reused for both the browser and server components of the application.
Now that you know a little bit about what Nim is, its history, and some
of the applications that it’s particularly well suited for, let’s look at some
of Nim’s features and talk about how it works.
1.1.2. Core features
In many ways, Nim is very innovative. Many of Nim’s features can’t be
found in any other programming language. If you enjoy learning new
programming languages, especially those with interesting and unique
features, then Nim is definitely the language for you.
In this section, we’ll look at some of the core features of Nim—in
particular, the features that make Nim stand out from other
programming languages:
A facility called metaprogramming, used for, among many things,
molding the language to your needs.
Style-insensitive variable, function, and type names. By using this
feature, which is slightly controversial, you can treat identifiers in
whatever style you wish, no matter if they were defined using
camelCase or snake_case.
A type system that’s rich in features such as generics, which make
code easier to write and maintain.
Compilation to C, which allows Nim programs to be efficient and
portable. The compilation itself is also very fast.
A number of different types of garbage collectors that can be
freely selected or removed altogether.
Metaprogramming
The most practical, and in some senses unique, feature of Nim is its
extensive metaprogramming support. Metaprogramming allows you to
read, generate, analyze, and transform source code. It was by no
means a Nim invention, but there’s no other programming language
with metaprogramming that’s so extensive and at the same time easy
to pick up as Nim’s. If you’re familiar with Lisp, then you might have
some experience with metaprogramming already.
With metaprogramming, you treat code as data in the form of an
abstract syntax tree. This allows you to manipulate existing code as
well as generate brand new code while your application is being
compiled.
Metaprogramming in Nim is special because languages with good
metaprogramming features typically belong to the Lisp family of
languages. If you’re already familiar with the likes of Java or Python,
you’ll find it easier to start using Nim than Lisp. You’ll also find it more
natural to learn how to use Nim’s metaprogramming features than
Lisp’s.
Although it’s generally an advanced topic, metaprogramming is a very
powerful feature that you’ll get to know in far more detail in chapter 9
of this book. One of the main benefits that metaprogramming offers is
the ability to remove boilerplate code. Metaprogramming also allows
the creation of domain-specific languages (DSLs); for example,
html:
body:
p: "Hello World"
This DSL specifies a bit of HTML code. Depending on how it’s
implemented, the DSL will likely be translated into Nim code
resembling the following:
echo("<html>")
echo(" <body>")
echo(" <p>Hello World</p>")
echo(" </body>")
echo("</html>")
That Nim code will result in the following output:
<html>
<body>
<p>Hello World</p>
</body>
</html>
With Nim’s metaprogramming, you can define DSLs and mix them
freely with your ordinary Nim code. Such languages have many use
cases; for example, the preceding one can be used to create HTML
templates for your web apps.
Metaprogramming is at the center of Nim’s design. Nim’s designer
wants to encourage users to use metaprogramming in order to
accommodate their style of programming. For example, although Nim
does offer some object-oriented programming (OOP) features, it
doesn’t have a class definition construct. Instead, anyone wishing to
use OOP in Nim in a style similar to that of other languages should use
metaprogramming to create such a construct.
Style insensitivity
Another of Nim’s interesting and likely unique features is style
insensitivity. One of the hardest things a programmer has to do is
come up with names for all sorts of identifiers like variables, functions,
and modules. In many programming languages, these names can’t
contain whitespace, so programmers have been forced to adopt other
ways of separating multiple words in a single name. Multiple differing
methods were devised, the most popular being snake_case and
camelCase. With Nim, you can use snake_case even if the identifier
has been defined using camelCase, and vice versa. So you can write
code in your preferred style even if the library you’re using adopted a
different style for its identifiers.
Listing 1.1. Style insensitivity
import strutils 1
echo("hello".to_upper()) 2
echo("world".toUpper()) 3
1 The strutils module defines a procedure called toUpper.
2 You can call it using snake_case.
3 As it was originally defined, you can call it using
camelCase.
This works because Nim considers the identifiers to_upper and
toUpper to be equal.
When comparing identifiers, Nim considers the case of the first
character, but it doesn’t bother with the case of the rest of the
identifier’s characters, ignoring the underscores as well. As a result, the
identifiers toUpper and ToUpper aren’t equal because the case of
the first character differs. This allows type names to be distinguished
from variable names, because, by convention, type names should start
with an uppercase letter and variable names should start with a
lowercase letter.
The following listing shows one scenario where this convention is
useful.
Listing 1.2. Style insensitivity and type identifiers
type
Dog = object 1
age: int 2
let dog = Dog(age: 3) 3
1 The Dog type is defined with an uppercase first letter.
2 Only primitive types such as int start with a lowercase
letter.
3 A dog variable can be safely defined because it won’t
clash with the Dog type.
Powerful type system
One of the many characteristics that differentiate programming
languages from one another is their type system. The main purpose of
a type system is to reduce the opportunities for bugs in your programs.
Other benefits that a good type system provides are certain compiler
optimizations and better documentation of code.
The main categories used to classify type systems are static and
dynamic. Most programming languages fall somewhere between the
two extremes and incorporate ideas from both. This is because both
static and dynamic type systems require certain trade-offs. Static
typing finds more errors at compile time, but it also decreases the
speed at which programs can be written. Dynamic typing is the
opposite.
Nim is statically typed, but unlike some statically typed programming
languages, it also incorporates many features that make development
fast. Type inference is a good example of that: types can be resolved
by the compiler without the need for you to write the types out
yourself (though you can choose to). Because of that, your program
can be bug-free and yet your development speed isn’t hindered. Nim
also incorporates some dynamic type-checking features, such as
runtime type information, which allows for the dynamic dispatch of
functions.
One way that a type system ensures that your program is free of bugs
is by verifying memory safety. Some programming languages, like C,
aren’t memory safe because they allow programs to access memory
that hasn’t been assigned for their use. Other programming languages
are memory safe at the expense of not allowing programs to access
low-level details of memory, which in some cases is necessary. Nim
combines both: it’s memory safe as long as you don’t use any of the
unsafe types, such as ptr, in your program, but the ptr type is
necessary when interfacing with C libraries. Supporting these unsafe
features makes Nim a powerful systems programming language.
By default, Nim protects you against every type of memory error:
Arrays are bounds-checked at compile time, or at runtime when
compile-time checks aren’t possible, preventing both buffer
overflows and buffer overreads.
Pointer arithmetic isn’t possible for reference types as they’re
entirely managed by Nim’s garbage collector; this prevents issues
such as dangling pointers and other memory issues related to
managing memory manually.
Variables are always initialized by Nim to their default values,
which prevents variables containing unexpected and corrupt data.
Finally, one of the most important features of Nim’s type system is the
ability to use generic programming. Generics in Nim allow for a great
deal of code reuse without sacrificing type safety. Among other things,
they allow you to specify that a single function can accept multiple
different types. For example, you may have a showNumber procedure
that displays both integers and floats on the screen:
proc showNumber(num: int | float) =
echo(num)
showNumber(3.14)
showNumber(42)
Here, the showNumber procedure accepts either an int type or a
float type. The | operator specifies that both int and float can be
passed to the procedure.
This is a simple demonstration of Nim’s generics. You’ll learn a lot more
about Nim’s type system, as well as its generics, in later chapters.
Compilation
I mentioned in the previous section that the Nim compiler compiles
source code into C first, and then feeds that source code into a C
compiler. You’ll learn a lot more about how this works in section 1.1.3,
but right now I’ll talk about some of the many practical advantages of
this compilation model.
The C programming language is very well established as a systems
programming language and has been in use for over 40 years. C is one
of the most portable programming languages, with multiple
implementations for Windows, Linux, Mac OS, x86, AMD64, ARM, and
many other, more obscure OSs and platforms. C compilers support
everything from supercomputers to microcontrollers. They’re also very
mature and implement many powerful optimizations, which makes C
very efficient.
Nim takes advantage of these aspects of C, including its portability,
widespread use, and efficiency.
Compiling to C also makes it easy to use existing C and C++ libraries—
all you need to do is write some simple wrapper code. You can write
this code much faster by using a tool called c2nim. This tool converts
C and C++ header files to Nim code, which wraps those files. This is of
great benefit because many popular libraries are written in C and C++.
Nim also offers you the ability to build libraries that are compatible with
C and C++. This is handy if you want your library to be used from
other programming languages. You’ll learn all about wrapping C and
C++ libraries in chapter 8.
Nim source code can also be compiled into Objective C and JavaScript.
The Objective C language is mainly used for iOS software
development; by compiling to it, you can write iOS applications natively
in Nim. You can also use Nim to develop Android applications by using
the C++ compilation backend. JavaScript is the client-side language
used by billions of websites; it’s sometimes called the “assembly
language of the web” because it’s the only programming language
that’s supported by all the major web browsers. By compiling to
JavaScript, you can write client-side applications for web browsers in
Nim. Figure 1.1 shows the available Nim backends.
Figure 1.1. Compilation backends
You may now be wondering just how fast Nim is at compiling software.
Perhaps you’re thinking that it’s very slow; after all, Nim needs to
translate source code to an intermediate language first. But in fact it’s
fairly fast. As an example, the Nim compiler, which consists of around
100,000 lines of Nim code, takes about 12 seconds to compile on a
MacBook Pro with a 2.7 GHz Intel Core i5 CPU. Each compilation is
cached, so the time drops to 5 seconds after the initial compilation.
Memory management
C and C++ both require you to manually manage memory, carefully
ensuring that what you allocate is deallocated once it’s no longer
needed. Nim, on the other hand, manages memory for you using a
garbage collector. But there are situations when you may want to avoid
garbage collectors; they’re considered by many to be inadequate for
certain application domains, like embedded systems and games. For
this reason, Nim supports a number of different garbage collectors with
Exploring the Variety of Random
Documents with Different Content
apprehension and hatred by all the nobler warriors of the tribes, ran
round the circle; and Black Eagle rose, saying--
"Let them be examined; and, if the stripe be found upon them,
set honest men to guard the lad. To-morrow, at the great council,
we will discuss his fate; and the Great Spirit send us dreams of what
is right! Come with me, my child. The Blossom is ever dear."
Thus saying, he turned and entered the lodge.
CHAPTER XXXI.
The promise of the sunset was verified. The succeeding day
dawned bright and clear. The wind had shifted to the south-west;
and, as frequently happens in the American autumn, the cold and icy
breath of the north-east had been succeeded by a wind as soft and
gentle as the warmest sigh of spring. In large masses, the snow fell
from the boughs of the hemlock and the pine; the white surface of
the earth's covering glistened as if with shining scales, as the upper
surface began to melt; and, drop after drop, the water trickled from
the extreme boughs of the trees, till the fully-risen sun sent the
snow away dissolved into the streams and into the lake. It was like
the recovery of the mind from sorrow, under the bright influence of
happier days.
Only here and there, a patch of snow was still seen upon the tops
of the hills, or in the more shady parts of the forest; only here and
there upon the sky lingered the fragment of a cloud; but, instead of
the dark, heavy, gray mass which had palled the heavens on the
preceding day, that cloud was as light and soft as the down of the
swan.
About two o'clock, several long lines of Indian chiefs and warriors
might be seen approaching the great Oneida village. Soon after, a
great fire was lighted before the door of the principal lodge; and, as
on the preceding evening, the warriors were ranged in a circle
round, and the women and children in another beyond.
The great chief, dressed in all the glittering finery of the Indian
peace-costume, with feathers, and red and white head-dress, and
crimson mantle, and embroidered shirt, and over-dress, and medals
innumerable hanging round his neck, took the seat of honour with a
grave dignity such as few civilized monarchs have ever, after the
greatest study, been able to attain. He wore no warlike weapons;
nothing but a single knife appeared in his girdle; and in his hand he
carried the richly-ornamented calumet, or pipe of peace.
Close behind her father sat Otaitsa, with her heart greatly
troubled, less perhaps with fear than with expectation. The Black
Eagle had been kind and tender with her when they were alone
together. He had held her to his heart with a display of fondness
such as an Indian rarely shows openly to his child. He had listened
to the whole tale of her love for Walter Prevost without a word of
disapprobation or reproach; and sometimes even a playful smile had
come upon his dark stern face as her words recalled the memory of
feelings experienced in youth--like a well-remembered song heard
again after a long lapse of years. Instead of reprehending her
attempt to deliver Walter, he commended it highly.
"It was thy part, my child," said he; "thou shouldst have been a
boy, Otaitsa; the warrior's spirit is in the maiden's bosom."
But when she came to speak of her lover's fate--to plead, to sue,
to entreat--the stern, grave coldness of the Indian chief returned;
and though she could see that he was full of fixed resolves, she
could in no degree discover what they were. The explanation of
them she knew was now to come; and it may be imagined, with
what eager and intense interest she listened for every word.
There was, of course, some little confusion as the multitude took
their places; but it was soon hushed, and then a deep silence
ensued. The great pipe was lighted, and sent from hand to hand till
it had passed all round the circle; and then, and not till then, Black
Eagle rose and spoke.
"Have my words been heard?" he asked; "have my warriors
examined whether any of the dark and infernal order of the
Honontkoh are amongst us."
He seated himself again as soon as he had made the inquiry; and,
after a moment's pause, two middle-aged warriors who had been
with him on the preceding day rose, and took a step forward, while
one of them said,--
"We have heard thy words, and examined. The brother of the
Snake, Apukwa the medicine-man, and the Flying Squirrel, are
Honontkoh. The stripe is upon them, and upon none else."
"It is well," said the chief, rising again. "Bring forward that man
who was taken at our Castle-door last night."
Half-a-dozen young men sprang upon their feet, and speedily
brought from the door of a neighbouring lodge the half-breed
runner, Proctor, whom we have seen with Brooks and Lord H----, at
Albany. He had a calumet in his hand, the sign of a peaceful mission;
and he showed no fear, for he knew that his life would be respected,
although he had learned by this time that the Oneidas had been
greatly excited by some acts referring to the very object of his
mission.
Standing in the midst, then, as calm and collected as he had been
in the fort at Albany, he hardly gave a glance around the circle, but
looked straight, with a cold and inexpressive countenance, at the
chief before whom he was placed.
"What hast thou to say?" demanded Black Eagle.
The man remained silent, although there was an evident
movement of his lips as if to speak.
"Fear not," said Black Eagle, mistaking the ineffectual effort to
speak for a sign of apprehension, although it really proceeded from
an habitual unwillingness to hear the sound of his own voice; "thou
shalt go in safety, whatever be thy message. Art thou dumb, man?
Is thy tongue a stone?"
"I am not dumb--I am not afraid," said the runner, with a strong
effort. "Great chiefs in Albany send me to say, 'Give us the boy.'"
There he stopped, for it had cost him much to utter so many
words.
"Were they war chiefs?" demanded Black Eagle, aloud.
The man nodded his head, and Black Eagle asked--
"Did they threaten the Oneidas? Did they say they would unbury
the hatchet?"
The runner shook his head; and the chief asked--
"What did they say, then, would befall us if we refused to
comply?"
"Shame!" replied Proctor, aloud.
Black Eagle suddenly drew his mantle over his face.
A low murmur spread around, like the hum of a hive of bees.
When it had subsided, the chief again rose, and with an air of grave,
sad dignity, looked round upon his people.
"Ye have heard, O children of the Stone," he said, in a rich, clear,
deep-toned voice, "what the chiefs of the pale-faces say of the
Oneida nation; and there are warriors here who were with me
yesterday, when our brethren, the Mohawks, reproached me with
treachery and inhospitality towards our pale-face brother, Prevost;
and the Black Eagle had nothing to answer. Ye know the history.
Why should I sing again the song of yesterday? A man of our nation
was slain by one of the Yengees; and the brethren of the dead man
seized upon the son of Prevost, who is also our son, without
searching for him who had spilt the blood. This was contrary to the
custom of the Five Nations. But they say the man was not to be
found--he was already beyond our territory; and we must take the
first we can find to appease the spirit of our brother. Now Prevost is
a good man, loved by all the Five Nations, a brother to the red man,
a friend who trusted us. So hard do the Mohawks and the
Onondagas think this deed, that they have dealt subtly with the
Oneidas, and striven to rescue our captive from our hands by the
crooked ways of the serpent. The pale-face chiefs, too, have sent
men into our land, and think darkly of the Oneidas. But the Black
Eagle saw what they did, and spread his wings and drove them
forth. He had no answer for the reproaches of the Mohawks or of
the Yengees. He will give them both their answer this day by the
messenger; and the children of the Stone will thereby know his
mind. Let them say if it be good."
Then turning to Proctor, he stretched out his hand towards the
south, saying--
"When thou goest hence, two of my warriors shall go with thee to
the Castle of the Mohawk, and thou shalt say, 'Why hast thou dealt
subtly with the Oneida? If thou hadst aught against him, why didst
thou not send a messenger of peace to tell thy brother thy mind? or
why didst thou not appeal to the great council of the Five Nations to
judge between thee and him? If thou wilt unbury the hatchet, and
cut down the tree of peace, and bring trouble into the Five Nations,
that the pale-face may prevail and our Long House be pulled down
to the ground, paint thy face, and dance the war-dance, and come
upon the battle-way; but follow not the trail of the serpent, to steal
unperceived into thy brother's land.'"
A murmur of approbation followed this bold speech; but the next
moment the chief continued, still addressing Proctor, and saying--
"When thou hast thus spoken to the Mohawk, thou shalt go on to
the pale-face chiefs at Albany, and to them thou shalt say, 'The
children of the Stone have heard your message. They are the
children of the great King. He is their father and they love him; but
the Oneidas have their own laws, and are led by their own chiefs.
They take the war-path against your enemies as against their own;
and ye are glad in the day of battle when they fight the Frenchmen
by your side. It is sweet to them that you have used no threats; and
they would not have their white brother think darkly of them. They
love, too, the chief, Prevost. They love his son as a brother; but one
of their own children has been slain by one of yours, and their law
must be fulfilled. His spirit must not be shut out from the happy
hunting-grounds. They will mourn as a whole nation for Walter
Prevost; but Walter Prevost must die, unless the murderer be taken.
Thus says the Black Eagle, the great chief of the Oneida nation; he
who has taken a hundred scalps of his enemies, and fought in fifteen
battles with your foes and his. Give us up the murderer if ye would
save the boy. He is in your land: you can find him. Do justly by us in
this matter, and walk not in the trail of the fox to deceive us, and to
save from us our captive.'"
Then pausing for an instant, he somewhat lowered his voice, but
spoke the succeeding words very slowly and distinctly, in order that
every syllable might not only be impressed upon the mind of the
man he addressed, but be clearly heard and comprehended by all
the people around.
"Thou shalt say, moreover, to our brethren, the pale-face chiefs at
Albany, 'The Black Eagle finds that Walter Prevost has fallen into the
hands of bad men, men who are not to be trusted, dealers in dark
things, vultures whose heads are bare, but whose hearts are
covered. The Black Eagle will take the boy from their hands, and will
treat him well, and keep him in safety till the hour come. As ye have
said that the Oneidas are hasty, that they do rashly, that they have
not sought as they ought to seek--for six moons will Black Eagle
keep the lad in peace, as his own son, to see whether ye will give
him up the murderer of an Oneida. But, as the chief would slay his
own son, if the laws of his people required it at his hands, so will he
and the chiefs of his nation slay Walter Prevost, if, in six moons, ye
do not give him up the murderer. He shall die the death of a warrior,
with his hands unbound, and, as Black Eagle knows the spirit that is
in him, he is sure he will die as a warrior should.' This thou shalt say
to the English chiefs; let them look to it; the fate of the boy depends
upon their counsel. Give him a roll of wampum for his reward, and
let him go in peace."
His commands were immediately obeyed, and the half-breed
runner removed from the circle.
Then, turning to the warriors without reseating himself, the chief
demanded--
"Have I said well?"
The usual words of approbation followed, repeated by almost
every voice present; and then Black Eagle resumed, in a sterner
tone, saying--
"And now, my children, what shall be done to the Honontkoh? I
have already removed the captive from their hands; for they are a
people without faith. They live in darkness, and they wrap
themselves in a shadow. They take their paths in deceit, and we see
blood and dissension follow them. Already have they raised against
us the wrath of our brethren of the Five Nations; they have brought
the yellow cloud of shame upon the Oneidas. They have well nigh
severed the threads which hold the roll of our league together. They
have laid the hatchet to the root of the tree which we and our
English father planted. I say, let them go forth from amongst us. The
Totem of the Tortoise casts them forth. We will not have our lodges
near their lodges. They shall not dwell within our palisade. Let them
betake themselves to the darkness of the forest, and to the secret
holes of the rock; for darkness and secrecy are the dwelling-places
of their hearts. Or let them go, if they will, to the deceitful Hurons,
to the people beyond Horicon, and fight beside the deceitful
Frenchmen. With us they shall not dwell; let them be seen no more
amongst us.--Is my judgment good?"
A general cry of approbation followed; the council broke up, and
the warriors commenced wandering about, those who came from a
distance seeking hospitality in the neighbouring lodges; for the great
lodge itself could not afford room for all.
To her own little chamber, Otaitsa retired at once; and, barring
the door, went down upon her knees, to offer up thanksgiving and
prayer--thanksgiving, for hope is ever a blessing--prayer, for danger
was still before her eyes. Safe for the next six months she knew
Walter would be, in the careful custody of her father; but she still
prayed earnestly that her mother's God would find some way of
deliverance, for the sake of Him who died to save mankind.
CHAPTER XXXII.
More than five months had passed, months of great trouble and
anxiety to many. The usual tragedies of life had been enacted in
many a house, and in many a home: the dark, ever-recurring scene
of death and suffering and grief had passed through the dwellings of
rich and poor. Many a farce, too, in public and private, had been
exhibited to the gaze; for, in the history of each man and of all the
world, the ridiculous and the grand, the sad and the cheerful, stand
side by side in strange proximity.
The woods, blazing in their autumnal crimson when last we saw
them, had worn and soiled, in about a fortnight, the glorious
vestments of the autumn, and cast them to the earth; and now they
had put on the green garments of the summer, and robed
themselves in the tender hues of youth. The rivers and the streams,
bound in icy chains for many a month, now dashed wildly and
impetuously along in the joy of lately-recovered freedom, and,
swollen by the spring rains, in some places became torrents; in
some places, slowly flooded the flat land, marching over the
meadows like a vast invading army.
The beasts of the forest were busy in their coverts, the birds in
the brake, or on the tree-top; the light clouds skimmed along the
soft blue sky; and the wind tossed the light young branches to and
fro in its sport. Everything was gay and active on the earth, and over
the earth; everything spoke of renewed life, and energy, and hope.
To the fancy of those who have not seen it, the vast primæval
forest presents an idea of monotony; and certainly, when seen from
a distance, it produces that impression on the mind. Looming dark
and sombre, thick and apparently impenetrable, over upland and
dell, over plain and mountain, it conveys a sensation of solemnity by
its very sameness; and, though the first sight is sublime, its long-
continued presence is oppressive. But penetrate into its depths, and
you will find infinite variety; now the dense, tangled thicket, through
which the panther and the wild cat creep with difficulty, and into
which the deer cannot venture; now the quaking morass, unsafe to
the foot, yet bearing up the tamarach or cedar, with its rank grasses,
its strangely-shaped leaves, and its rich and infinitely varied flowers;
now the wide grove, extending for miles and miles, with the tall bolls
of the trees rising up distinct and separate, and with little or no
brushwood hiding the carpet of dry pine-spindles and cones on
which they stand; then the broad savanna, with its grass knee-high,
green and fresh and beautiful, and merely a tree here and there to
shelter some spot from the sun, and cast a soft blue shadow on the
natural meadow; and then again, in many spots, a space of ground
where every characteristic of the forest is mingled--here thick and
tangled brush, there a patch of open green, here the swamp running
along the brook-side, there the sturdy oak or wide-spreading
chestnut, standing far apart in reverence for each other's giant
limbs, shading many a pleasant slope, or topping the lofty crag.
It was under one of these large trees, on a high bank
commanding the whole prospect round for many and many a mile,
and in the eastern part of the province of New York, that three red
men were seated in the early summer of 1758. A little distance in
advance of them, and somewhat lower down the hill, was a small
patch of brush, composed of fantastic-looking bushes, and one small
blasted tree. It formed, as it were, a sort of screen to the Indians'
resting-place from all eyes below, yet did not in the least impede
their sight as it wandered over the wide forest world around them.
From the elevation on which they were placed, the eye of the red
man, which seems, from constant practice, to have gained the
keenness of the eagle's sight, could plunge into every part of the
woods around where the trees were not actually contiguous. The
trail, wherever it quitted the shelter of the branches; the savanna,
wherever it broke the outline of the forest; the river, where it wound
along in its course to the ocean; the military road from the banks of
the Hudson to the head of Lake Horicon; the smallest pond, the little
stream, were all spread out to view as if upon a map.
Over the wide, extensive prospect the eyes of those three Indians
wandered incessantly, not as if employed in searching for some
definite object, the direction of which, if not the precise position,
they knew, but rather as if they were looking for anything which
might afford them some object of pursuit or interest. They sat there
nearly two hours in the same position; and during the whole of that
time not more than four or five words passed between them.
At length they began to converse, though at first in a low tone, as
if the silence had its awe even for them. One of them pointed with
his hand towards a spot to the eastward, saying, "There is
something doing there."
In the direction to which he called the attention of his companions
was seen spread out, in the midst of the forest and hills, a small, but
exquisitely beautiful lake, seemingly joined on to another, of much
greater extent, by a narrow channel. Of the former, the whole extent
could not be seen; for, every here and there, a spur of the mountain
cut off the view, and broke in upon the beautiful waving line of the
shore. The latter was more distinctly seen, spread out broad and
even, with every little islet, headland, and promontory, marked clear
and distinctly against the bright, glistening surface of the waters.
Near the point where the two lakes seemed to meet, the Indians
could descry walls, and mounds of earth, and various buildings of
considerable size; nay, even what was probably the broad banner of
France, though it seemed but a mere whitish spot in the distance.
At the moment when the Indians spoke, coming from a distant
point on the larger lake, the extreme end of which was lost to view
in a sort of indistinct blue haze, a large boat or ship might be seen,
with broad white sails, wafted swiftly onward by a cold north-
easterly wind. Some way behind it, another moving object appeared-
-a boat likewise, but much more indistinct; and, here and there
nearer in shore, two or three black specks, probably canoes, were
darting along upon the bosom of the lake, like water-flies upon the
surface of a still stream.
"The pale-faces take the war-path against each other," said
another of the Indians, after gazing for a moment or two.
"May they all perish!" exclaimed the third. "Why are our people so
mad as to help them? Let them fight, and slay, and scalp as many of
each other as they can, and then the red men tomahawk the
remainder."
The other two uttered a bitter malediction, in concert with this
fierce, but not impolitic, thought; and then, after one of their long
pauses, the first who had spoken, resumed the conversation, saying-
-
"Yet I would give one of the feathers of the White Bird to know
what the pale-faces are doing. Their hearts are black against each
other. Can you not tell us, Apukwa? You were on the banks of
Horican yesterday, and must have heard the news from Corlear."
"The news from Albany matters much more," answered Apukwa.
"The Yengees are marching up with a cloud of fighting-men; and
people know not where they will fall. Some think Oswego; some
think Ticonderoga. I am sure that it is the place of the Singing
Waters that they go against."
"Will they do much in the war-path?" asked the brother of the
Snake; "or will the Frenchman make himself as red as he did last
year, at the south end of Horicon?"
"The place of the Singing Waters is strong, brother," replied
Apukwa, in a musing tone, "and the Frenchmen are great warriors;
but the Yengees are many in number, and they have called for aid
from the Five Nations. I told the Huron who sold me powder, where
the eagles would come down; and I think he would not let the
tidings slumber beneath his tongue. The great-winged canoes are
coming up Corlear very quick; but I think my words must have been
whispered in the French chief's ear, to cause them to fly so quickly
to Ticonderoga."
A faint, nearly-suppressed smile came upon the lips of his two
companions as they heard of this proceeding; but the younger of the
three said--
"And what will Apukwa do in the battle?"
"Scalp my enemies," replied Apukwa, looking darkly round.
"Which is thine enemy?" asked the brother of the Snake.
"Both," answered the medicine-man, bitterly; "and every true
Honontkoh should do as I do; follow them closely, and slay every
man that flies, be his nation what it may. So long as he be white, it
is enough for us. He is an enemy; let us blunt our scalping-knives on
the skulls of the pale-faces. Then, when the battle is over, we can
take our trophies to the conqueror, and say, 'We have been upon thy
side.'"
"But will he not know?" suggested the younger man; "will he
listen so easily to the song?"
"How should he know?" asked Apukwa, coldly. "If we took him
red men's scalps, he might doubt; but all he asks is white men's
scalps, and we will take them. They are all alike, and they will have
no faces under them."
This ghastly jest was highly to the taste of the two hearers; and,
bending down their heads together, the three continued to converse
for several minutes in a whisper. At length, one of them said--
"Could we not take Prevost's house as we go? How many brothers
did you say would muster?"
"Nine," answered Apukwa; "and our three selves make twelve."
Then, after pausing for a moment or two in thought, he added, "It
would be sweet as the strawberry and as easy to gather; but there
may be thorns near it. We may tear ourselves, my brothers."
"I fear not," returned the brother of the Snake; "so that I but set
my foot within that lodge, with my rifle in my hand, and my
tomahawk in my belt, I care not what follows."
"The boy's to die," rejoined Apukwa; "why seek more in his lodge
at thine own risk?"
The other did not answer; but, after a moment's pause, he asked-
-"Who is it has built the lodge still farther to the morning?"
"One of the workers of iron," answered Apukwa, meaning the
Dutch. "He is a great chief, they say, and a friend of the Five
Nations."
"Then no friend of ours, my brother," responded the other
speaker; "for though it be the children of the Stone who have shut
the door of the lodge against us, and driven us from the council-fire,
the Five Nations have confirmed their saying, and made the
Honontkoh a people apart. Why should we not fire that lodge too,
and then steal on to the dwelling of Prevost?"
"Thy lip is thirsty for something," said Apukwa. "Is it the maiden
thou wouldst have?"
The other smiled darkly; and, after remaining silent for a short
space, answered--
"They have taken from me my captive; and my hand can never
reach the Blossom I sought to gather. The boy may die, but not by
my tomahawk; and, when he does die, I am no better, for I lose that
which I sought to gain by his death. Are Apukwa's eyes misty, that
he cannot see? The spirit of the Snake would have been as well
satisfied with the blood of any other pale-face; but that would not
have satisfied me."
"Yet making Prevost's house red will not gather for thee the
Blossom," answered Apukwa.
The third and younger of the Indians laughed, saying----
"The wind changes, Apukwa, and so does the love of our brother.
The maiden in the lodge of Prevost is more beautiful than the
Blossom. We have seen her thrice since this moon grew big; and my
brother calls her the Fawn, because she has become the object of
his chase."
"Thou knowest not my thought," said the brother of the Snake,
gravely. "The maiden is fair, and she moves round her father's lodge
like the sun. She shall be the light of mine, too; but the brother of
the snake forgets not those who disappoint him; and the boy
Prevost would rather have seen the tomahawk falling, than know
that the Fawn is in his lodge."
The other two uttered that peculiar humming sound by which the
Indians sometimes intimate that they are satisfied; and the
conversation which went on between them related chiefly to the
chances of making a successful attack upon the house of Mr.
Prevost. Occasionally, indeed, they turned their eyes towards the
boats upon Lake Champlain, and commented upon the struggle that
was about to be renewed between France and England. That each
party had made vast preparations was well known, and intelligence
of the extent and nature of those preparations had spread far and
wide amongst the tribes, with wonderful accuracy as to many of the
details, but without any certain knowledge of where the storm was
to break.
All saw, however, and comprehended, that a change had come
over the British government; that the hesitating and doubtful policy
which had hitherto characterized their military movements in
America was at an end; and that the contest was now to be waged
for the gain and loss of all the European possessions on the North
American continent. Already was it known amongst the Five Nations,
although the time for the transmission of the intelligence was
incredibly small, that a large fleet and armament had arrived at
Halifax, and that several naval successes over the French had
cleared the way for some great enterprise in the north. At the same
time, the neighbourhood of Albany was full of the bustle of military
preparation; a large force was already collected under Abercrombie
for some great attempt upon the lakes: and from the west news had
been received that a British army was marching rapidly towards the
French posts upon the Ohio and the Monongahela.
The Indian nations roused themselves at the sound of war; for,
though some few of them acted more regularly in alliance with one
or the other of the contending European powers, a greater number
than is generally believed cared little whom they attacked, or for
whom they fought, or whom they slew; and were, in reality, but as a
flock of vultures spreading their wings at the scent of battle, and
ready to take advantage of the carnage, whatever was the result of
the strife.
CHAPTER XXXIII.
We must now return to the scene in which this narrative
commenced. But oh, how changed was the aspect of all things from
that which the house of Mr. Prevost presented but five short months
before! The father and the daughter were there alone. The brother
no longer glanced about the house with his blithesome air and active
energies; and the thought of him and of his fate hung continually
like a dark shadow over those to whom he was so dear. They were
not wholly without comfort, they were not wholly without hope; for,
from time to time, renewed assurances came to them from many a
quarter that Walter would still be saved. Yet time wore on, and he
was not delivered.
When one speaks of five months of uncertainty, it seems a long
and tedious period, and it would be so if it were all one blank; but
there are a thousand little incidents--incidents external and internal--
that fill up the time, and make it pass wonderfully soon, especially if
fear predominates over hope.
Didst thou ever sit up, reader, with the sick or dying through the
livelong night? In contemplation, it seems an awful task of long
endurance to watch there with the eternal battle going on in your
breast between the only two deathless passions--the only two which
may be called the immortal passions of the soul--from the fading of
the evening light till the breaking of another day. And yet it is
wonderful how soon, how very soon, one sees the faint blue light of
dawn mingling with the sickly yellow glare of the watcher's lamp.
Every thought, every expectation, is an incident. The change of
breathing, the restless movement, the muttered word, the whispered
comfort, the moistening of the parched lip, the smoothing of the
pillow,--all are events that hurry on the time.
And so it was in the house of Mr. Prevost. Each day had its
something; each hour; and although the object was always the
same, or rarely varied, yet the rapid changes of thought and feeling
made the time fly far more rapidly than might have been expected.
During the winter, Lord H---- visited the house very frequently;
and it is probable that, had no dark cloud overshadowed the hopes
as well as the happiness of all, he would have pressed for the prize
of Edith's hand without delay; but he loved not the mingling of joy
and sorrow. In that, at least, his view of the world, and life, and
fate, was deceitful. He was not yet convinced, although he had some
experience, that such a thing as unalloyed happiness, even for a few
short days, is not to be found on earth--that the only mine of gold
without dross lies beneath the grave.
Once, indeed, he hinted, rather than asked, that an early day
might be fixed for his union with her he loved; but a tear rose in
Edith's eye, and she bent down her head. Her father would have
made no objection, although he still thought her very, very young to
take upon her the duties of a wife. In that respect his feelings were
not changed; but the loss of his son weighed heavily upon him, and,
calling him away from the present, had projected his thoughts into
the future. What might be Edith's fate, he asked himself, if he too
should be taken from her? Any of the many accidents of life might
leave her alone, and an orphan; and there is nothing which brings
home so sensibly to our thoughts the unstable hold which we have
upon all earthly things, so much as our tenderness for those we
love.
But Lord H---- saw that it would be painful to Edith herself to
become his bride as long as Walter's late was uncertain; and he said
no more.
In the meantime the gathering together of the British soldiers on
the Hudson and the Mohawk had, like one wave meeting another,
somewhat repelled the Indian tribes. A runner, a half-breed, or one
or two red men together--more frequently from the nation of the
Mohawks than from any other tribe--would be seen occasionally
wandering through the woods or crossing the open ground near the
settler's dwelling; but they seldom approached the house; and their
appearance caused no apprehension. Relations of the greatest amity
had been re-established between the British authorities and the
chiefs of the Five Nations; and several of the tribes were preparing
to take part in the coming strife upon the side of England.
Three times during the winter the house of Mr. Prevost was visited
by a single Indian of the Oneida tribe. On two occasions it was a
man who presented himself; and his stay was very short. On the
first occasion, Edith was alone; when, without the sound of a
footfall, he glided in like a dark shadow. His look was friendly,
though for a moment he said nothing. Edith, well knowing Indian
habits, asked if he would take food. He answered "Yes," in his own
language; and she called some of the servants to supply him; but,
before he ate he looked up in her face, saying--
"I am bidden to tell thee that thy brother shall be safe."
"Whose words do you bear?" asked Edith. "Is it the Black Eagle
who speaks?"
"Nay, it is Otaitsa," replied the man.
This was all Edith could learn; for the messenger was either
ignorant of more, or affected to be so; yet still it was a comfort to
her. The next who came was a woman somewhat past the middle
age, and by no means beautiful. She stayed long; and, with good-
humoured volubility, related all that had happened immediately after
Edith's visit to the Oneida castle. She dwelt upon the attempt of the
Blossom to deliver her lover as she would have expatiated upon
some feat of daring courage in a warrior; and though in the end she
had to tell how the maiden's bold attempt had been frustrated, she
concluded by saying--
"Yet he shall be safe. They shall not slay our brother."
The third time the man returned, hearing the same assurance;
but, as hour after hour and day after day went by without the lad's
return, or any definite news of him, hope sickened and grew faint.
By this time it was known that the efforts of the Mohawks and
Onondagas had been frustrated; and, moreover, it was plainly
intimated by the chiefs of those two nations that they would
interfere no more.
"The Oneidas have reproved us," they said, "and we had no reply.
We must not make the children of the Stone hiss at our children;
neither must we break the bands of our alliance for the sake of one
man."
The scouts who had been put under the order of Woodchuck
were recalled to the army early in the spring without having effected
anything. All that had been heard at the forts showed that the young
prisoner had been removed to the very farthest part of the Oneida
territory, where it was impossible for any one Englishman to
penetrate without being discovered by the Indians.
If, in civilized times, with a country cleared in a great degree of its
forests, and with a regular organization ensuring rapid intercourse
between place and place, it is possible for a man to be hidden for
weeks and months from the most diligent search; how much more
easy was concealment in those days, when, with the exception of a
few patches of maize or other grain, the whole land was one wild
tangled wood, crossed, it is true, with innumerable Indian trails, but
with no direct means of communication, except by one large road,
and the lakes and rivers. Search would have been in vain, even if in
the political state of the country it could have been attempted; but
the attempt was impossible, without rendering the whole country
hostile; for the Mohawks themselves showed no inclination to suffer
any considerable body of men to cross their territory, except indeed
a small party of soldiers, now and then, destined to strengthen the
garrisons at Oswego, or any of the regular British posts.
Of Woodchuck himself, nothing was heard, till the flowers began
to spring up close upon the footsteps of the snow. It was believed
that he was still in the forest; but even of this, no one was assured;
and all that could with any accuracy be divined, was, that he had not
fallen into the hands of the Oneidas, inasmuch as there was every
reason to believe that, had such been the case, Walter's liberation
would immediately have followed.
Thus matters had gone on in the household of Mr. Prevost, till
about a month before the period at which I have thought best to
present to the reader the three Indians seated on the hill. The snow
had melted, except in a few places, where it still lay in white
patches, under shelter of the darker and thicker-leaved evergreens;
here and there, too, it might be seen in the shade of a steep bank;
but the general surface of the country was free, and, despite, the
variable character of the American spring--one day as soft as
summer, and then two or three following, with the icy fang of winter
in the wind, and the sky covered with low lurid clouds--the flowers
were peeping out in every covert, and mingling themselves thickly

More Related Content

PDF
(Ebook) JavaScript Application Design: A Build First Approach by Nicolas Be...
PDF
Linux Administration: A Beginner's Guide 8th Edition Wale Soyinka
PDF
Eclipse Rich Client Platform 2nd Edition Jeff Mcaffer
PDF
Eclipse Rich Client Platform 2nd Edition Jeff Mcaffer
PDF
Rich client programming plugging into the NetBeans Platform 1. print Edition ...
PDF
Linux Administration: A Beginner's Guide 8th Edition Wale Soyinka
PDF
Linux Administration: A Beginner's Guide 8th Edition Wale Soyinka
PDF
Linux Administration: A Beginner's Guide 8th Edition Wale Soyinka
(Ebook) JavaScript Application Design: A Build First Approach by Nicolas Be...
Linux Administration: A Beginner's Guide 8th Edition Wale Soyinka
Eclipse Rich Client Platform 2nd Edition Jeff Mcaffer
Eclipse Rich Client Platform 2nd Edition Jeff Mcaffer
Rich client programming plugging into the NetBeans Platform 1. print Edition ...
Linux Administration: A Beginner's Guide 8th Edition Wale Soyinka
Linux Administration: A Beginner's Guide 8th Edition Wale Soyinka
Linux Administration: A Beginner's Guide 8th Edition Wale Soyinka

Similar to Nim in Action 1st Edition Dominik Picheta (20)

PDF
Rich client programming plugging into the NetBeans Platform 1. print Edition ...
PDF
Buy ebook Linux Administration: A Beginner's Guide 8th Edition Wale Soyinka c...
PDF
Functional Programming in C#: How to write better C# code 1st Edition Enrico ...
DOCX
Digital Literacy Objectives
PDF
Linux Administration: A Beginner's Guide 8th Edition Wale Soyinka
PDF
Linux Administration: A Beginner's Guide 8th Edition Wale Soyinka
PDF
Ionic in Action Hybrid Mobile Apps with Ionic and AngularJS 1st Edition Jerem...
PDF
Download full Managing Kubernetes operating Kubernetes clusters in the real w...
PDF
Open Source ESBs in Action 1st Edition Tijs Rademakers
PDF
Clean Code. An Agile Guide to Software Craft Kameron H.
PDF
Go Web Programming 1st Edition Sau Sheong Chang
PDF
Instant download Ubuntu Linux Unleashed 2021 Edition Helmke pdf all chapter
PDF
Programming Python 3rd ed Edition Mark Lutz
PDF
Clean Code. An Agile Guide to Software Craft Kameron H.
PDF
Clean Code. An Agile Guide to Software Craft Kameron H.
PDF
Linux Cookbook 1st Edition Carla Schroder
PDF
Web Development With Java Using Hibernate Jsps And Servlets Tim Downey
PDF
Open Source ESBs in Action 1st Edition Tijs Rademakers
PDF
Azure Infrastructure as Code: With ARM templates and Bicep 1st Edition Henry ...
PDF
Azure Infrastructure as Code: With ARM templates and Bicep 1st Edition Henry ...
Rich client programming plugging into the NetBeans Platform 1. print Edition ...
Buy ebook Linux Administration: A Beginner's Guide 8th Edition Wale Soyinka c...
Functional Programming in C#: How to write better C# code 1st Edition Enrico ...
Digital Literacy Objectives
Linux Administration: A Beginner's Guide 8th Edition Wale Soyinka
Linux Administration: A Beginner's Guide 8th Edition Wale Soyinka
Ionic in Action Hybrid Mobile Apps with Ionic and AngularJS 1st Edition Jerem...
Download full Managing Kubernetes operating Kubernetes clusters in the real w...
Open Source ESBs in Action 1st Edition Tijs Rademakers
Clean Code. An Agile Guide to Software Craft Kameron H.
Go Web Programming 1st Edition Sau Sheong Chang
Instant download Ubuntu Linux Unleashed 2021 Edition Helmke pdf all chapter
Programming Python 3rd ed Edition Mark Lutz
Clean Code. An Agile Guide to Software Craft Kameron H.
Clean Code. An Agile Guide to Software Craft Kameron H.
Linux Cookbook 1st Edition Carla Schroder
Web Development With Java Using Hibernate Jsps And Servlets Tim Downey
Open Source ESBs in Action 1st Edition Tijs Rademakers
Azure Infrastructure as Code: With ARM templates and Bicep 1st Edition Henry ...
Azure Infrastructure as Code: With ARM templates and Bicep 1st Edition Henry ...
Ad

Recently uploaded (20)

PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
Lesson notes of climatology university.
PPTX
GDM (1) (1).pptx small presentation for students
PDF
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
A systematic review of self-coping strategies used by university students to ...
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PPTX
Pharma ospi slides which help in ospi learning
PDF
Weekly quiz Compilation Jan -July 25.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Complications of Minimal Access Surgery at WLH
PPTX
Orientation - ARALprogram of Deped to the Parents.pptx
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
Module 4: Burden of Disease Tutorial Slides S2 2025
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Lesson notes of climatology university.
GDM (1) (1).pptx small presentation for students
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
Final Presentation General Medicine 03-08-2024.pptx
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Anesthesia in Laparoscopic Surgery in India
2.FourierTransform-ShortQuestionswithAnswers.pdf
202450812 BayCHI UCSC-SV 20250812 v17.pptx
STATICS OF THE RIGID BODIES Hibbelers.pdf
A systematic review of self-coping strategies used by university students to ...
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
Pharma ospi slides which help in ospi learning
Weekly quiz Compilation Jan -July 25.pdf
O7-L3 Supply Chain Operations - ICLT Program
Complications of Minimal Access Surgery at WLH
Orientation - ARALprogram of Deped to the Parents.pptx
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Ad

Nim in Action 1st Edition Dominik Picheta

  • 1. Read Anytime Anywhere Easy Ebook Downloads at ebookmeta.com Nim in Action 1st Edition Dominik Picheta https://ebookmeta.com/product/nim-in-action-1st-edition- dominik-picheta/ OR CLICK HERE DOWLOAD EBOOK Visit and Get More Ebook Downloads Instantly at https://ebookmeta.com
  • 2. Recommended digital products (PDF, EPUB, MOBI) that you can download immediately if you are interested. Agile Leadership in Practice Applying Management 3 0 2nd Edition Dominik Maximini https://ebookmeta.com/product/agile-leadership-in-practice-applying- management-3-0-2nd-edition-dominik-maximini/ ebookmeta.com Test Driven iOS Development with Swift 3 Hauser Dr Dominik https://ebookmeta.com/product/test-driven-ios-development-with- swift-3-hauser-dr-dominik/ ebookmeta.com Flexibility Planning in Distribution Networks A Flexibility Planning Model for the Consumer Goods Industry 1st Edition Dominik Pfeiffer https://ebookmeta.com/product/flexibility-planning-in-distribution- networks-a-flexibility-planning-model-for-the-consumer-goods- industry-1st-edition-dominik-pfeiffer/ ebookmeta.com Mayor of Elf Town 2 1st Edition Dante King https://ebookmeta.com/product/mayor-of-elf-town-2-1st-edition-dante- king-3/ ebookmeta.com
  • 3. The Experienced Soul 1st Edition Glenda Abramson https://ebookmeta.com/product/the-experienced-soul-1st-edition-glenda- abramson/ ebookmeta.com Learn Lua for iOS Game Development Jayant Varma https://ebookmeta.com/product/learn-lua-for-ios-game-development- jayant-varma/ ebookmeta.com The War Came To Us 1st Edition Christopher Miller https://ebookmeta.com/product/the-war-came-to-us-1st-edition- christopher-miller/ ebookmeta.com Sor Juana Inde la Cruz and the Gender Politics of Knowledge in Colonial Mexico 1st Edition Stephanie Kirk https://ebookmeta.com/product/sor-juana-inde-la-cruz-and-the-gender- politics-of-knowledge-in-colonial-mexico-1st-edition-stephanie-kirk/ ebookmeta.com Sucker Punch Girls On Top Series 1st Edition Dee Ellis https://ebookmeta.com/product/sucker-punch-girls-on-top-series-1st- edition-dee-ellis-3/ ebookmeta.com
  • 4. AVR Workshop: A Hands-On Introduction with 60 Projects (NOT genuine pdf) 1st Edition John Boxall https://ebookmeta.com/product/avr-workshop-a-hands-on-introduction- with-60-projects-not-genuine-pdf-1st-edition-john-boxall/ ebookmeta.com
  • 7. Copyright For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: orders@manning.com ©2017 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid- free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine.
  • 8. Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Development editors: Cynthia Kane, Dan Seiter, Marina Michaels Technical development editor: Andrew West Review editor: Donna Clements Project editor: Karen Gulliver Copyeditor: Andy Carroll Proofreader: Katie Tennant Technical proofreader: Michiel Trimpe Typesetter: Dottie Marsico Cover designer: Marija Tudor ISBN 9781617293436 Printed in the United States of America 1 2 3 4 5 6 7 8 9 10 – EBM – 22 21 20 19 18 17
  • 9. Brief Table of Contents Copyright Brief Table of Contents Table of Contents Preface Acknowledgments About this Book About the Author About the Cover Illustration 1. The basics of Nim Chapter 1. Why Nim? Chapter 2. Getting started 2. Nim in practice Chapter 3. Writing a chat application Chapter 4. A tour through the standard library Chapter 5. Package management Chapter 6. Parallelism Chapter 7. Building a Twitter clone 3. Advanced concepts Chapter 8. Interfacing with other languages Chapter 9. Metaprogramming Appendix A. Getting help Appendix B. Installing Nim
  • 10. Nim Reference Index List of Figures List of Tables List of Listings
  • 11. Table of Contents Copyright Brief Table of Contents Table of Contents Preface Acknowledgments About this Book About the Author About the Cover Illustration 1. The basics of Nim Chapter 1. Why Nim? 1.1. What is Nim? 1.1.1. Use cases 1.1.2. Core features 1.1.3. How does Nim work? 1.2. Nim’s benefits and shortcomings 1.2.1. Benefits 1.2.2. Areas where Nim still needs to improve 1.3. Summary Chapter 2. Getting started 2.1. Nim syntax 2.1.1. Keywords
  • 12. 2.1.2. Indentation 2.1.3. Comments 2.2. Nim basics 2.2.1. Basic types 2.2.2. Defining variables and other storage 2.2.3. Procedure definitions 2.3. Collection types 2.3.1. Arrays 2.3.2. Sequences 2.3.3. Sets 2.4. Control flow 2.5. Exception handling 2.6. User-defined types 2.6.1. Objects 2.6.2. Tuples 2.6.3. Enums 2.7. Summary 2. Nim in practice Chapter 3. Writing a chat application 3.1. The architecture of a chat application 3.1.1. What will the finished application look like? 3.2. Starting the project
  • 13. 3.3. Retrieving input in the client component 3.3.1. Retrieving command-line parameters supplied by the user 3.3.2. Reading data from the standard input stream 3.3.3. Using spawn to avoid blocking input/output 3.4. Implementing the protocol 3.4.1. Modules 3.4.2. Parsing JSON 3.4.3. Generating JSON 3.5. Transferring data using sockets 3.5.1. What is a socket? 3.5.2. Asynchronous input/output 3.5.3. Transferring data asynchronously 3.6. Summary Chapter 4. A tour through the standard library 4.1. A closer look at modules 4.1.1. Namespacing 4.2. Overview of the standard library 4.2.1. Pure modules 4.2.2. Impure modules 4.2.3. Wrappers 4.2.4. Online documentation 4.3. The core modules
  • 14. 4.4. Data structures and algorithms 4.4.1. The tables module 4.4.2. The sets module 4.4.3. The algorithms 4.4.4. Other modules 4.5. Interfacing with the operating system 4.5.1. Working with the filesystem 4.5.2. Executing an external process 4.5.3. Other operating system services 4.6. Understanding and manipulating data 4.6.1. Parsing command-line arguments 4.7. Networking and the internet 4.8. Summary Chapter 5. Package management 5.1. The Nim package manager 5.2. Installing Nimble 5.3. The nimble command-line tool 5.4. What is a Nimble package? 5.5. Installing Nimble packages 5.5.1. Using the install command 5.5.2. How does the install command work? 5.6. Creating a Nimble package 5.6.1. Choosing a name
  • 15. 5.6.2. A Nimble package’s directory layout 5.6.3. Writing the .nimble file and sorting out dependencies 5.7. Publishing Nimble packages 5.8. Developing a Nimble package 5.8.1. Giving version numbers meaning 5.8.2. Storing different versions of a single package 5.9. Summary Chapter 6. Parallelism 6.1. Concurrency vs. parallelism 6.2. Using threads in Nim 6.2.1. The threads module and GC safety 6.2.2. Using thread pools 6.2.3. Exceptions in threads 6.3. Parsing data 6.3.1. Understanding the Wikipedia page-counts format 6.3.2. Parsing the Wikipedia page-counts format 6.3.3. Processing each line of a file efficiently 6.4. Parallelizing a parser 6.4.1. Measuring the execution time of sequential_counts 6.4.2. Parallelizing sequential_counts 6.4.3. Type definitions and the parse procedure
  • 16. 6.4.4. The parseChunk procedure 6.4.5. The parallel readPageCounts procedure 6.4.6. The execution time of parallel_counts 6.5. Dealing with race conditions 6.5.1. Using guards and locks to prevent race conditions 6.5.2. Using channels so threads can send and receive messages 6.6. Summary Chapter 7. Building a Twitter clone 7.1. Architecture of a web application 7.1.1. Routing in microframeworks 7.1.2. The architecture of Tweeter 7.2. Starting the project 7.3. Storing data in a database 7.3.1. Setting up the types 7.3.2. Setting up the database 7.3.3. Storing and retrieving data 7.3.4. Testing the database 7.4. Developing the web application’s view 7.4.1. Developing the user view 7.4.2. Developing the general view 7.5. Developing the controller
  • 17. 7.5.1. Implementing the /login route 7.5.2. Extending the / route 7.5.3. Implementing the /createMessage route 7.5.4. Implementing the user route 7.5.5. Adding the Follow button 7.5.6. Implementing the /follow route 7.6. Deploying the web application 7.6.1. Configuring Jester 7.6.2. Setting up a reverse proxy 7.7. Summary 3. Advanced concepts Chapter 8. Interfacing with other languages 8.1. Nim’s foreign function interface 8.1.1. Static vs. dynamic linking 8.1.2. Wrapping C procedures 8.1.3. Type compatibility 8.1.4. Wrapping C types 8.2. Wrapping an external C library 8.2.1. Downloading the library 8.2.2. Creating a wrapper for the SDL library 8.2.3. Dynamic linking 8.2.4. Wrapping the types 8.2.5. Wrapping the procedures
  • 18. 8.2.6. Using the SDL wrapper 8.3. The JavaScript backend 8.3.1. Wrapping the canvas element 8.3.2. Using the Canvas wrapper 8.4. Summary Chapter 9. Metaprogramming 9.1. Generics 9.1.1. Generic procedures 9.1.2. Generics in type definitions 9.1.3. Constraining generics 9.1.4. Concepts 9.2. Templates 9.2.1. Passing a code block to a template 9.2.2. Parameter substitution in templates 9.2.3. Template hygiene 9.3. Macros 9.3.1. Compile-time function execution 9.3.2. Abstract syntax trees 9.3.3. Macro definition 9.3.4. Arguments in macros 9.4. Creating a configuration DSL 9.4.1. Starting the configurator project
  • 19. 9.4.2. Generating the object type 9.4.3. Generating the constructor procedure 9.4.4. Generating the load procedure 9.4.5. Testing the configurator 9.5. Summary Appendix A. Getting help A.1. Real-time communication A.2. Forum A.3. Other communication methods Appendix B. Installing Nim B.1. Installing the Nim compiler B.1.1. Getting up-to-date installation info B.1.2. Building from source B.2. Installing the Aporia IDE B.3. Testing your new development environment B.4. Troubleshooting B.4.1. Nim command not found B.4.2. Nim and C compiler disagree on target architecture B.4.3. Could not load DLL Nim Reference Index List of Figures
  • 20. List of Tables List of Listings
  • 21. Preface Nim has been my labor of love over the years. Gradually, from the time I discovered it, I’ve become increasingly involved in its development. Although I sacrificed considerable time working on it, Nim gave back in the form of experience and knowledge. My work with Nim has taught me far more than any other work or studies have done. Many opportunities have also opened up for me, a shining example being this book. I never actually thought I would end up writing a book, and until a Manning acquisitions editor got in touch with me, I didn’t realize that I wanted to. While planning this book, I looked to other books and determined where they fell short. I realized that this, the first book on Nim, must be written for programmers with a bit of experience. I decided that I wanted to write a book that teaches programmers about Nim, but that also teaches other programming concepts that work well in Nim’s particular programming paradigms. These concepts can also be applied to other programming languages and have been very useful in my career. My other goal for this book was to make it fun and engaging. I decided to do this by building some chapters around small projects. The projects are designed to be practical and to teach a number of Nim features and concepts. By following along and developing these projects, you’ll gain hands-on experience developing Nim applications. This should put you in a good position to write your own software, which is the ultimate goal of this book. Nim in Action covers a lot, but it can’t cover everything. It shouldn’t be viewed as a complete Nim reference; instead, it should be considered a practical guide to writing software in Nim.
  • 22. It’s my hope that this book helps you learn Nim and that you find it a useful reference for many years to come. I and the Nim community are at your disposal and are available online to help you solve any problems you run into. Thank you for purchasing this book and taking an interest in Nim.
  • 23. Acknowledgments First, I would like to thank Andreas Rumpf for creating Nim and for both his reviews and words of encouragement throughout the development of this book. Andreas created a one-of-a-kind programming language, and without his commitment to Nim, this book wouldn’t exist. This book wouldn’t be what it is today without the brilliant and passionate people at Manning publications. I give my thanks to Marjan Bace, who made it possible to publish this book; my editors Cynthia Kane, Dan Seiter, and Marina Michaels, for helping me improve my writing; and the production team, including Andy Carroll, Janet Vail, Karen Gulliver, and Katie Tennant. I thank the Nim community and everyone who participated in reviews and provided feedback on the manuscript, including technical proofreader Michiel Trimpe, and the following reviewers: Andrea Ferretti, Yuriy Glukhov, Michał Zieliński, Stefan Salewski, Konstantin Molchanov, Sébastien Ménard, Abel Brown, Alessandro Campeis, Angelo Costa, Christoffer Fink, Cosimo Attanasi, James Anaipakos, Jonathan Rioux, Marleny Nunez, Mikkel Arentoft, Mohsen Mostafa Jokar, Paulo Nuin, Peter Hampton, Robert Walsh, Samuel Bosch, Thomas Ballinger, and Vincent Keller. Thanks also to the readers of the Manning Early Access Program (MEAP). Their corrections and comments on the manuscript as it was being written were invaluable. Finally, I’d like to thank my family and friends, who in their own way steered my life in a positive direction, leading me to authoring this book. First, I thank my mother, Bogumiła Picheta, for her bravery and hard work, without which I wouldn’t have had the means to start my programming journey, and I especially thank her for making
  • 24. a hard decision that turned out to be very beneficial for my future. I would also like to thank my uncle, Piotr Kossakowski-Stefański, and aunt, Marzena Kossakowska--Stefańska, for inspiring and challenging me to write software, and also for always being there to share their advice. Thanks to Ilona, Maciej Sr., and Maciej Jr. Łosinski for my first exposure to a computer and the internet. And I thank Kazimierz Ślebioda, a.k.a Kazik, for the Age of Empires 2 LAN parties and for showing me how delicious chicken with garlic can be. Most of all, I thank my partner, Amy-Leigh Shaw, for always believing in me, and for her patience and support throughout my work on this book. I love you very much Amy, and am lucky to have you.
  • 25. About this Book Nim in Action is a practical way to learn how to develop software using the open source Nim programming language. This book includes many examples, both large and small, to show and teach you how software is written in Nim. Nim is unique. It’s multi-paradigm, and unlike most other languages, it doesn’t emphasize object-oriented programming. Because of this, I encourage you to consciously absorb the styles used in this book instead of applying your own. Nim in Action will teach you a set of best practices and idioms that you’ll also find useful in other programming languages. By learning Nim, you’ll discover a language that straddles the lines between efficiency, expressiveness, and elegance. Nim will make you productive and your end users happy. Who should read this book This is by no means a beginner’s book. It assumes that you know at least one other programming language and have experience writing software in it. For example, I expect you to be aware of basic programming language features such as functions, variables, and types. The fundamentals of programming aren’t explained in this book. This book will teach you how to develop practical software in the Nim programming language. It covers features that are present in all programming languages, such as concurrency, parallelism, user- defined types, the standard library, and more. In addition, it covers Nim features that you may not be familiar with, such as
  • 26. asynchronous input/output, metaprogramming, and the foreign function interface. How the book is organized The book is divided into three parts and includes a total of nine chapters. Part 1 introduces the language and its basic features: Chapter 1 explains what Nim is, compares it to other programming languages, and discusses its strengths and weaknesses. Chapter 2 teaches the basics, such as the syntax and fundamental features of the language. This includes a demonstration of procedure definitions and exception handling. Part 2 includes a wide range of examples to show how Nim is used in practice: Chapter 3 is where you’ll develop your first nontrivial Nim application. The primary purpose of this application is communication: it allows messages to be sent through a network. You’ll learn, among other things, how to create command-line interfaces, parse JSON, and transfer data over a network in Nim. Chapter 4 gives an overview of the standard library, particularly the parts of it that aren’t covered in other chapters but are useful. Chapter 5 discusses package management in Nim and teaches you how to create your own packages and make them available to others. Chapter 6 explains what parallelism is and how it can be applied to different programming tasks. You’ll see a parsing example,
  • 27. demonstrating different ways to parse data in Nim and how parsing can be parallelized. Chapter 7 is where you’ll develop your second nontrivial Nim application: a web application based on Twitter. You’ll learn how to store data in a SQL database and generate HTML. Part 3 introduces some advanced Nim features: Chapter 8 looks at the foreign function interface and shows how it can be used to make use of C and JavaScript libraries. You’ll develop a simple application that draws the letter N on the screen, first using a C library and then using JavaScript’s Canvas API. Chapter 9 explains what metaprogramming is, discussing features such as generics, templates, and macros. At the end of this chapter, you’ll use macros to create a domain-specific language. You may wish to skip the first two chapters if you already know the basics of Nim. I recommend reading the book from beginning to end, and I especially encourage you to follow along with the examples. Each chapter teaches you something new about Nim, even if it primarily focuses on a standalone example. If you get stuck, feel free to get in touch with me or the Nim community. Appendix A contains information on how to get help, so use it to your advantage. Code conventions and downloads The source code examples in this book are fairly close to the samples that you’ll find online, but for the sake of brevity, many of the comments were removed. The online samples include a lot of comments to make them as easy to understand as possible, so you’re encouraged to take a look at them to learn more.
  • 28. The source code is available for download from the publisher’s website at https://manning.com/books/nim-in-action and from GitHub at https://github.com/dom96/nim-in-action-code. Nim is still evolving, so be sure to watch the repository for changes. I’ll do my best to keep it up to date with the latest Nim version. This book contains many examples of source code, both in numbered listings and inline with normal text. In both cases, source code is formatted in a mono-spaced typeface like this, to distinguish it from ordinary text. Sometimes code is also in bold to highlight code that has changed from previous steps in the chapter, such as when a new feature is added to existing code. In many cases, the original source code has been reformatted for print; we’ve added line breaks and reworked the indentation to accommodate the available page space in the book. In rare cases, even this was not enough, and listings include line-continuation markers ( ). Additionally, comments in the source code have often been removed from the listings when the code is described in the text. Book forum The purchase of Nim in Action includes free access to a private web forum run by Manning Publications, where you can make comments about the book, ask technical questions, and receive help from the author and from other users. To access the forum, go to https://forums.manning.com/forums/nim-in-action. You can also learn more about Manning’s forums and the rules of conduct at https://forums.manning.com/forums/about. Manning’s commitment to our readers is to provide a venue where a meaningful dialogue between individual readers and between readers and the author can take place. It is not a commitment to
  • 29. any specific amount of participation on the part of the author, whose contribution to the forum remains voluntary (and unpaid). We suggest you try asking him some challenging questions lest his interest stray! The forum and the archives of previous discussions will be accessible from the publisher’s website as long as the book is in print.
  • 30. About the Author DOMINIK PICHETA (@d0m96, picheta.me) is a Computer Science student at Queen’s University Belfast. He is one of the core developers of the Nim programming language and has been using it for most of its history. He also wrote Nimble, the official Nim package manager, and many other Nim libraries and tools.
  • 31. About the Cover Illustration The figure on the cover of Nim in Action is captioned “Morlaque de l’Isle Opus,” or “A Morlach from the Island of Opus.” The Morlachs were a Vlach people originally centered around the eastern Adriatic port of Ragusa, or modern Dubrovnik. The illustration is taken from a collection of dress costumes from various countries by Jacques Grasset de Saint-Sauveur (1757–1810), titled Costumes de Différents Pays, published in France in 1797. Each illustration is finely drawn and colored by hand. The rich variety of Grasset de Saint-Sauveur’s collection reminds us vividly of how culturally apart the world’s towns and regions were just 200 years ago. Isolated from each other, people spoke different dialects and languages. In the streets or in the countryside, it was easy to identify where they lived and what their trade or station in life was just by their dress. The way we dress has changed since then and the diversity by region, so rich at the time, has faded away. It is now hard to tell apart the inhabitants of different continents, let alone different towns, regions, or countries. Perhaps we have traded cultural diversity for a more varied personal life—certainly, for a more varied and fast-paced technological life. At a time when it is hard to tell one computer book from another, Manning celebrates the inventiveness and initiative of the computer business with book covers based on the rich diversity of regional life of two centuries ago, brought back to life by Grasset de Saint- Sauveur’s pictures.
  • 32. Part 1. The basics of Nim This part of the book begins your study of the Nim programming language. It doesn’t assume you know much about Nim, so chapter 1 begins by looking at the characteristics of the language, what makes it different from other languages, and how it’s used in the real world. Chapter 2 looks at some of the most commonly used elements of any programming language—the syntax, semantics, and type system— and in doing so teaches you the necessary foundations for writing simple applications in Nim.
  • 33. Chapter 1. Why Nim? This chapter covers What Nim is Why you should learn about it Comparing Nim to other programming languages Use cases Strengths and weaknesses Nim is still a relatively new programming language. In fact, you’re holding one of the very first books about it. The language is still not fully complete, but core aspects, like its syntax, the semantics of procedures, methods, iterators, generics, templates, and more, are all set in stone. Despite its newness, there has been significant interest in Nim from the programming community because of the unique set of features that it implements and offers its users. This chapter answers questions that you may ask before learning Nim, such as why you might want to use it. In this chapter, I outline some of the common practical uses of Nim, compare it to other programming languages, and discuss some of its strengths and weaknesses. 1.1. What is Nim? Nim is a general-purpose programming language designed to be efficient, expressive, and elegant. These three goals are difficult to achieve at the same time, so Nim’s designers gave each of them different priorities, with efficiency being the most important and elegance being the least. But despite the fact that elegance is relatively unimportant to Nim’s design, it’s still considered during the design process. Because of this,
  • 34. the language remains elegant in its own right. It’s only when trade-offs between efficiency and elegance need to be made that efficiency wins. On the surface, Nim shares many of Python’s characteristics. In particular, many aspects of Nim’s syntax are similar to Python’s, including the use of indentation to delimit scope as well as the tendency to use words instead of symbols for certain operators. Nim also shares other aspects with Python that aren’t related to syntax, such as the highly user-friendly exception tracebacks, shown here: Traceback (most recent call last) request.nim(74) request request.nim(25) getUsers json.nim(837) [] tables.nim(147) [] Error: unhandled exception: key not found: totalsForAllResults [KeyError] You’ll also see many differences, especially when it comes to the semantics of the language. The major differences lie within the type system and execution model, which you’ll learn about in the next sections. A little bit about Nim’s history Andreas Rumpf started developing Nim in 2005. The project soon gained support and many contributions from the open source community, with many volunteers around the world contributing code via pull requests on GitHub. You can see the current open Nim pull requests at https://github.com/nim-lang/Nim/pulls. Contributing to Nim The compiler, standard library, and related tools are all open source and written in Nim. The project is available on GitHub, and everyone is encouraged to contribute. Contributing to Nim is a good way to learn how it works and to help with its development. See Nim’s GitHub page for more information: https://github.com/nim-lang/Nim#contributing.
  • 35. 1.1.1. Use cases Nim was designed to be a general-purpose programming language from the outset. As such, it consists of a wide range of features that make it usable for just about any software project. This makes it a good candidate for writing software in a wide variety of application domains, ranging from web applications to kernels. In this section, I’ll discuss how Nim’s features and programming support apply in several use cases. Although Nim may support practically any application domain, this doesn’t make it the right choice for everything. Certain aspects of the language make it more suitable for some categories of applications than others. This doesn’t mean that some applications can’t be written using Nim; it just means that Nim may not support the code styles that are best suited for writing some kinds of applications. Nim is a compiled language, but the way in which it’s compiled is special. When the Nim compiler compiles source code, it first translates the code into C code. C is an old but well supported systems programming language that allows easier and more direct access to the physical hardware of the machine. This makes Nim well suited to systems programming, allowing projects such as operating systems (OSs), compilers, device drivers, and embedded system software to be written. Internet of Things (IoT) devices, which are physical devices with embedded electronics that are connected to the internet, are good targets for Nim, primarily thanks to the power offered by Nim’s ease of use and its systems programming capabilities. A good example of a project making use of Nim’s systems programming features is a very simple OS called NimKernel available on GitHub: https://github.com/dom96/nimkernel.
  • 36. How does Nim compile source code? I describe Nim’s unusual compilation model and its benefits in detail in section 1.1.3. Applications written in Nim are very fast; in many cases, just as fast as applications written in C, and more than thirteen times faster than applications written in Python. Efficiency is the highest priority, and some features make optimizing code easy. This goes hand in hand with a soft real-time garbage collector, which allows you to specify the amount of time that should be spent collecting memory. This feature becomes important during game development, where an ordinary garbage collector may slow down the rendering of frames on the screen if it uses too much time collecting memory. It’s also useful in real-time systems that need to run in very strict time frames. Nim can be used alongside other much slower languages to speed up certain performance-critical components. For example, an application written in Ruby that requires certain CPU-intensive calculations can be partially written in Nim to gain a considerable speed advantage. Such speed-ups are important in areas such as scientific computing and high-speed trading. Applications that perform I/O operations, such as reading files or sending data over a network, are also well supported by Nim. Web applications, for example, can be written easily using a number of web frameworks like Jester (https://github.com/dom96/jester). Nim’s script-like syntax, together with its powerful, asynchronous I/O support, makes it easy to develop these applications rapidly. Command-line applications can benefit greatly from Nim’s efficiency. Also, because Nim applications are compiled, they’re standalone and so don’t require any bulky runtime dependencies. This makes their distribution incredibly easy. One such application written in Nim is Nimble; it’s a package manager for Nim that allows users to install Nim libraries and applications.
  • 37. These are just a few use cases that Nim fits well; it’s certainly not an exhaustive list. Another thing to keep in mind is that, at the time of writing, Nim is still in development, not having yet reached version 1.0. Certain features haven’t been implemented yet, making Nim less suited for some applications. For example, Nim includes a backend that allows you to write JavaScript applications for your web pages in Nim. This backend works, but it’s not yet as mature as the rest of the language. This will improve with time. Of course, Nim’s ability to compile to JavaScript makes it suitable for full-stack applications that need components that run on a server and in a browser. This is a huge advantage, because code can easily be reused for both the browser and server components of the application. Now that you know a little bit about what Nim is, its history, and some of the applications that it’s particularly well suited for, let’s look at some of Nim’s features and talk about how it works. 1.1.2. Core features In many ways, Nim is very innovative. Many of Nim’s features can’t be found in any other programming language. If you enjoy learning new programming languages, especially those with interesting and unique features, then Nim is definitely the language for you. In this section, we’ll look at some of the core features of Nim—in particular, the features that make Nim stand out from other programming languages: A facility called metaprogramming, used for, among many things, molding the language to your needs. Style-insensitive variable, function, and type names. By using this feature, which is slightly controversial, you can treat identifiers in
  • 38. whatever style you wish, no matter if they were defined using camelCase or snake_case. A type system that’s rich in features such as generics, which make code easier to write and maintain. Compilation to C, which allows Nim programs to be efficient and portable. The compilation itself is also very fast. A number of different types of garbage collectors that can be freely selected or removed altogether. Metaprogramming The most practical, and in some senses unique, feature of Nim is its extensive metaprogramming support. Metaprogramming allows you to read, generate, analyze, and transform source code. It was by no means a Nim invention, but there’s no other programming language with metaprogramming that’s so extensive and at the same time easy to pick up as Nim’s. If you’re familiar with Lisp, then you might have some experience with metaprogramming already. With metaprogramming, you treat code as data in the form of an abstract syntax tree. This allows you to manipulate existing code as well as generate brand new code while your application is being compiled. Metaprogramming in Nim is special because languages with good metaprogramming features typically belong to the Lisp family of languages. If you’re already familiar with the likes of Java or Python, you’ll find it easier to start using Nim than Lisp. You’ll also find it more natural to learn how to use Nim’s metaprogramming features than Lisp’s. Although it’s generally an advanced topic, metaprogramming is a very powerful feature that you’ll get to know in far more detail in chapter 9 of this book. One of the main benefits that metaprogramming offers is the ability to remove boilerplate code. Metaprogramming also allows the creation of domain-specific languages (DSLs); for example,
  • 39. html: body: p: "Hello World" This DSL specifies a bit of HTML code. Depending on how it’s implemented, the DSL will likely be translated into Nim code resembling the following: echo("<html>") echo(" <body>") echo(" <p>Hello World</p>") echo(" </body>") echo("</html>") That Nim code will result in the following output: <html> <body> <p>Hello World</p> </body> </html> With Nim’s metaprogramming, you can define DSLs and mix them freely with your ordinary Nim code. Such languages have many use cases; for example, the preceding one can be used to create HTML templates for your web apps. Metaprogramming is at the center of Nim’s design. Nim’s designer wants to encourage users to use metaprogramming in order to accommodate their style of programming. For example, although Nim does offer some object-oriented programming (OOP) features, it doesn’t have a class definition construct. Instead, anyone wishing to use OOP in Nim in a style similar to that of other languages should use metaprogramming to create such a construct. Style insensitivity Another of Nim’s interesting and likely unique features is style insensitivity. One of the hardest things a programmer has to do is come up with names for all sorts of identifiers like variables, functions, and modules. In many programming languages, these names can’t
  • 40. contain whitespace, so programmers have been forced to adopt other ways of separating multiple words in a single name. Multiple differing methods were devised, the most popular being snake_case and camelCase. With Nim, you can use snake_case even if the identifier has been defined using camelCase, and vice versa. So you can write code in your preferred style even if the library you’re using adopted a different style for its identifiers. Listing 1.1. Style insensitivity import strutils 1 echo("hello".to_upper()) 2 echo("world".toUpper()) 3 1 The strutils module defines a procedure called toUpper. 2 You can call it using snake_case. 3 As it was originally defined, you can call it using camelCase. This works because Nim considers the identifiers to_upper and toUpper to be equal. When comparing identifiers, Nim considers the case of the first character, but it doesn’t bother with the case of the rest of the identifier’s characters, ignoring the underscores as well. As a result, the identifiers toUpper and ToUpper aren’t equal because the case of the first character differs. This allows type names to be distinguished from variable names, because, by convention, type names should start with an uppercase letter and variable names should start with a lowercase letter. The following listing shows one scenario where this convention is useful. Listing 1.2. Style insensitivity and type identifiers type Dog = object 1 age: int 2
  • 41. let dog = Dog(age: 3) 3 1 The Dog type is defined with an uppercase first letter. 2 Only primitive types such as int start with a lowercase letter. 3 A dog variable can be safely defined because it won’t clash with the Dog type. Powerful type system One of the many characteristics that differentiate programming languages from one another is their type system. The main purpose of a type system is to reduce the opportunities for bugs in your programs. Other benefits that a good type system provides are certain compiler optimizations and better documentation of code. The main categories used to classify type systems are static and dynamic. Most programming languages fall somewhere between the two extremes and incorporate ideas from both. This is because both static and dynamic type systems require certain trade-offs. Static typing finds more errors at compile time, but it also decreases the speed at which programs can be written. Dynamic typing is the opposite. Nim is statically typed, but unlike some statically typed programming languages, it also incorporates many features that make development fast. Type inference is a good example of that: types can be resolved by the compiler without the need for you to write the types out yourself (though you can choose to). Because of that, your program can be bug-free and yet your development speed isn’t hindered. Nim also incorporates some dynamic type-checking features, such as runtime type information, which allows for the dynamic dispatch of functions. One way that a type system ensures that your program is free of bugs is by verifying memory safety. Some programming languages, like C, aren’t memory safe because they allow programs to access memory
  • 42. that hasn’t been assigned for their use. Other programming languages are memory safe at the expense of not allowing programs to access low-level details of memory, which in some cases is necessary. Nim combines both: it’s memory safe as long as you don’t use any of the unsafe types, such as ptr, in your program, but the ptr type is necessary when interfacing with C libraries. Supporting these unsafe features makes Nim a powerful systems programming language. By default, Nim protects you against every type of memory error: Arrays are bounds-checked at compile time, or at runtime when compile-time checks aren’t possible, preventing both buffer overflows and buffer overreads. Pointer arithmetic isn’t possible for reference types as they’re entirely managed by Nim’s garbage collector; this prevents issues such as dangling pointers and other memory issues related to managing memory manually. Variables are always initialized by Nim to their default values, which prevents variables containing unexpected and corrupt data. Finally, one of the most important features of Nim’s type system is the ability to use generic programming. Generics in Nim allow for a great deal of code reuse without sacrificing type safety. Among other things, they allow you to specify that a single function can accept multiple different types. For example, you may have a showNumber procedure that displays both integers and floats on the screen: proc showNumber(num: int | float) = echo(num) showNumber(3.14) showNumber(42) Here, the showNumber procedure accepts either an int type or a float type. The | operator specifies that both int and float can be passed to the procedure.
  • 43. This is a simple demonstration of Nim’s generics. You’ll learn a lot more about Nim’s type system, as well as its generics, in later chapters. Compilation I mentioned in the previous section that the Nim compiler compiles source code into C first, and then feeds that source code into a C compiler. You’ll learn a lot more about how this works in section 1.1.3, but right now I’ll talk about some of the many practical advantages of this compilation model. The C programming language is very well established as a systems programming language and has been in use for over 40 years. C is one of the most portable programming languages, with multiple implementations for Windows, Linux, Mac OS, x86, AMD64, ARM, and many other, more obscure OSs and platforms. C compilers support everything from supercomputers to microcontrollers. They’re also very mature and implement many powerful optimizations, which makes C very efficient. Nim takes advantage of these aspects of C, including its portability, widespread use, and efficiency. Compiling to C also makes it easy to use existing C and C++ libraries— all you need to do is write some simple wrapper code. You can write this code much faster by using a tool called c2nim. This tool converts C and C++ header files to Nim code, which wraps those files. This is of great benefit because many popular libraries are written in C and C++. Nim also offers you the ability to build libraries that are compatible with C and C++. This is handy if you want your library to be used from other programming languages. You’ll learn all about wrapping C and C++ libraries in chapter 8. Nim source code can also be compiled into Objective C and JavaScript. The Objective C language is mainly used for iOS software development; by compiling to it, you can write iOS applications natively
  • 44. in Nim. You can also use Nim to develop Android applications by using the C++ compilation backend. JavaScript is the client-side language used by billions of websites; it’s sometimes called the “assembly language of the web” because it’s the only programming language that’s supported by all the major web browsers. By compiling to JavaScript, you can write client-side applications for web browsers in Nim. Figure 1.1 shows the available Nim backends. Figure 1.1. Compilation backends You may now be wondering just how fast Nim is at compiling software. Perhaps you’re thinking that it’s very slow; after all, Nim needs to translate source code to an intermediate language first. But in fact it’s fairly fast. As an example, the Nim compiler, which consists of around 100,000 lines of Nim code, takes about 12 seconds to compile on a MacBook Pro with a 2.7 GHz Intel Core i5 CPU. Each compilation is cached, so the time drops to 5 seconds after the initial compilation. Memory management C and C++ both require you to manually manage memory, carefully ensuring that what you allocate is deallocated once it’s no longer needed. Nim, on the other hand, manages memory for you using a garbage collector. But there are situations when you may want to avoid garbage collectors; they’re considered by many to be inadequate for certain application domains, like embedded systems and games. For this reason, Nim supports a number of different garbage collectors with
  • 45. Exploring the Variety of Random Documents with Different Content
  • 46. apprehension and hatred by all the nobler warriors of the tribes, ran round the circle; and Black Eagle rose, saying-- "Let them be examined; and, if the stripe be found upon them, set honest men to guard the lad. To-morrow, at the great council, we will discuss his fate; and the Great Spirit send us dreams of what is right! Come with me, my child. The Blossom is ever dear." Thus saying, he turned and entered the lodge.
  • 47. CHAPTER XXXI. The promise of the sunset was verified. The succeeding day dawned bright and clear. The wind had shifted to the south-west; and, as frequently happens in the American autumn, the cold and icy breath of the north-east had been succeeded by a wind as soft and gentle as the warmest sigh of spring. In large masses, the snow fell from the boughs of the hemlock and the pine; the white surface of the earth's covering glistened as if with shining scales, as the upper surface began to melt; and, drop after drop, the water trickled from the extreme boughs of the trees, till the fully-risen sun sent the snow away dissolved into the streams and into the lake. It was like the recovery of the mind from sorrow, under the bright influence of happier days. Only here and there, a patch of snow was still seen upon the tops of the hills, or in the more shady parts of the forest; only here and there upon the sky lingered the fragment of a cloud; but, instead of the dark, heavy, gray mass which had palled the heavens on the preceding day, that cloud was as light and soft as the down of the swan. About two o'clock, several long lines of Indian chiefs and warriors might be seen approaching the great Oneida village. Soon after, a great fire was lighted before the door of the principal lodge; and, as on the preceding evening, the warriors were ranged in a circle round, and the women and children in another beyond.
  • 48. The great chief, dressed in all the glittering finery of the Indian peace-costume, with feathers, and red and white head-dress, and crimson mantle, and embroidered shirt, and over-dress, and medals innumerable hanging round his neck, took the seat of honour with a grave dignity such as few civilized monarchs have ever, after the greatest study, been able to attain. He wore no warlike weapons; nothing but a single knife appeared in his girdle; and in his hand he carried the richly-ornamented calumet, or pipe of peace. Close behind her father sat Otaitsa, with her heart greatly troubled, less perhaps with fear than with expectation. The Black Eagle had been kind and tender with her when they were alone together. He had held her to his heart with a display of fondness such as an Indian rarely shows openly to his child. He had listened to the whole tale of her love for Walter Prevost without a word of disapprobation or reproach; and sometimes even a playful smile had come upon his dark stern face as her words recalled the memory of feelings experienced in youth--like a well-remembered song heard again after a long lapse of years. Instead of reprehending her attempt to deliver Walter, he commended it highly. "It was thy part, my child," said he; "thou shouldst have been a boy, Otaitsa; the warrior's spirit is in the maiden's bosom." But when she came to speak of her lover's fate--to plead, to sue, to entreat--the stern, grave coldness of the Indian chief returned; and though she could see that he was full of fixed resolves, she could in no degree discover what they were. The explanation of them she knew was now to come; and it may be imagined, with what eager and intense interest she listened for every word. There was, of course, some little confusion as the multitude took their places; but it was soon hushed, and then a deep silence ensued. The great pipe was lighted, and sent from hand to hand till it had passed all round the circle; and then, and not till then, Black Eagle rose and spoke.
  • 49. "Have my words been heard?" he asked; "have my warriors examined whether any of the dark and infernal order of the Honontkoh are amongst us." He seated himself again as soon as he had made the inquiry; and, after a moment's pause, two middle-aged warriors who had been with him on the preceding day rose, and took a step forward, while one of them said,-- "We have heard thy words, and examined. The brother of the Snake, Apukwa the medicine-man, and the Flying Squirrel, are Honontkoh. The stripe is upon them, and upon none else." "It is well," said the chief, rising again. "Bring forward that man who was taken at our Castle-door last night." Half-a-dozen young men sprang upon their feet, and speedily brought from the door of a neighbouring lodge the half-breed runner, Proctor, whom we have seen with Brooks and Lord H----, at Albany. He had a calumet in his hand, the sign of a peaceful mission; and he showed no fear, for he knew that his life would be respected, although he had learned by this time that the Oneidas had been greatly excited by some acts referring to the very object of his mission. Standing in the midst, then, as calm and collected as he had been in the fort at Albany, he hardly gave a glance around the circle, but looked straight, with a cold and inexpressive countenance, at the chief before whom he was placed. "What hast thou to say?" demanded Black Eagle. The man remained silent, although there was an evident movement of his lips as if to speak. "Fear not," said Black Eagle, mistaking the ineffectual effort to speak for a sign of apprehension, although it really proceeded from
  • 50. an habitual unwillingness to hear the sound of his own voice; "thou shalt go in safety, whatever be thy message. Art thou dumb, man? Is thy tongue a stone?" "I am not dumb--I am not afraid," said the runner, with a strong effort. "Great chiefs in Albany send me to say, 'Give us the boy.'" There he stopped, for it had cost him much to utter so many words. "Were they war chiefs?" demanded Black Eagle, aloud. The man nodded his head, and Black Eagle asked-- "Did they threaten the Oneidas? Did they say they would unbury the hatchet?" The runner shook his head; and the chief asked-- "What did they say, then, would befall us if we refused to comply?" "Shame!" replied Proctor, aloud. Black Eagle suddenly drew his mantle over his face. A low murmur spread around, like the hum of a hive of bees. When it had subsided, the chief again rose, and with an air of grave, sad dignity, looked round upon his people. "Ye have heard, O children of the Stone," he said, in a rich, clear, deep-toned voice, "what the chiefs of the pale-faces say of the Oneida nation; and there are warriors here who were with me yesterday, when our brethren, the Mohawks, reproached me with treachery and inhospitality towards our pale-face brother, Prevost; and the Black Eagle had nothing to answer. Ye know the history. Why should I sing again the song of yesterday? A man of our nation
  • 51. was slain by one of the Yengees; and the brethren of the dead man seized upon the son of Prevost, who is also our son, without searching for him who had spilt the blood. This was contrary to the custom of the Five Nations. But they say the man was not to be found--he was already beyond our territory; and we must take the first we can find to appease the spirit of our brother. Now Prevost is a good man, loved by all the Five Nations, a brother to the red man, a friend who trusted us. So hard do the Mohawks and the Onondagas think this deed, that they have dealt subtly with the Oneidas, and striven to rescue our captive from our hands by the crooked ways of the serpent. The pale-face chiefs, too, have sent men into our land, and think darkly of the Oneidas. But the Black Eagle saw what they did, and spread his wings and drove them forth. He had no answer for the reproaches of the Mohawks or of the Yengees. He will give them both their answer this day by the messenger; and the children of the Stone will thereby know his mind. Let them say if it be good." Then turning to Proctor, he stretched out his hand towards the south, saying-- "When thou goest hence, two of my warriors shall go with thee to the Castle of the Mohawk, and thou shalt say, 'Why hast thou dealt subtly with the Oneida? If thou hadst aught against him, why didst thou not send a messenger of peace to tell thy brother thy mind? or why didst thou not appeal to the great council of the Five Nations to judge between thee and him? If thou wilt unbury the hatchet, and cut down the tree of peace, and bring trouble into the Five Nations, that the pale-face may prevail and our Long House be pulled down to the ground, paint thy face, and dance the war-dance, and come upon the battle-way; but follow not the trail of the serpent, to steal unperceived into thy brother's land.'" A murmur of approbation followed this bold speech; but the next moment the chief continued, still addressing Proctor, and saying--
  • 52. "When thou hast thus spoken to the Mohawk, thou shalt go on to the pale-face chiefs at Albany, and to them thou shalt say, 'The children of the Stone have heard your message. They are the children of the great King. He is their father and they love him; but the Oneidas have their own laws, and are led by their own chiefs. They take the war-path against your enemies as against their own; and ye are glad in the day of battle when they fight the Frenchmen by your side. It is sweet to them that you have used no threats; and they would not have their white brother think darkly of them. They love, too, the chief, Prevost. They love his son as a brother; but one of their own children has been slain by one of yours, and their law must be fulfilled. His spirit must not be shut out from the happy hunting-grounds. They will mourn as a whole nation for Walter Prevost; but Walter Prevost must die, unless the murderer be taken. Thus says the Black Eagle, the great chief of the Oneida nation; he who has taken a hundred scalps of his enemies, and fought in fifteen battles with your foes and his. Give us up the murderer if ye would save the boy. He is in your land: you can find him. Do justly by us in this matter, and walk not in the trail of the fox to deceive us, and to save from us our captive.'" Then pausing for an instant, he somewhat lowered his voice, but spoke the succeeding words very slowly and distinctly, in order that every syllable might not only be impressed upon the mind of the man he addressed, but be clearly heard and comprehended by all the people around. "Thou shalt say, moreover, to our brethren, the pale-face chiefs at Albany, 'The Black Eagle finds that Walter Prevost has fallen into the hands of bad men, men who are not to be trusted, dealers in dark things, vultures whose heads are bare, but whose hearts are covered. The Black Eagle will take the boy from their hands, and will treat him well, and keep him in safety till the hour come. As ye have said that the Oneidas are hasty, that they do rashly, that they have not sought as they ought to seek--for six moons will Black Eagle keep the lad in peace, as his own son, to see whether ye will give
  • 53. him up the murderer of an Oneida. But, as the chief would slay his own son, if the laws of his people required it at his hands, so will he and the chiefs of his nation slay Walter Prevost, if, in six moons, ye do not give him up the murderer. He shall die the death of a warrior, with his hands unbound, and, as Black Eagle knows the spirit that is in him, he is sure he will die as a warrior should.' This thou shalt say to the English chiefs; let them look to it; the fate of the boy depends upon their counsel. Give him a roll of wampum for his reward, and let him go in peace." His commands were immediately obeyed, and the half-breed runner removed from the circle. Then, turning to the warriors without reseating himself, the chief demanded-- "Have I said well?" The usual words of approbation followed, repeated by almost every voice present; and then Black Eagle resumed, in a sterner tone, saying-- "And now, my children, what shall be done to the Honontkoh? I have already removed the captive from their hands; for they are a people without faith. They live in darkness, and they wrap themselves in a shadow. They take their paths in deceit, and we see blood and dissension follow them. Already have they raised against us the wrath of our brethren of the Five Nations; they have brought the yellow cloud of shame upon the Oneidas. They have well nigh severed the threads which hold the roll of our league together. They have laid the hatchet to the root of the tree which we and our English father planted. I say, let them go forth from amongst us. The Totem of the Tortoise casts them forth. We will not have our lodges near their lodges. They shall not dwell within our palisade. Let them betake themselves to the darkness of the forest, and to the secret holes of the rock; for darkness and secrecy are the dwelling-places
  • 54. of their hearts. Or let them go, if they will, to the deceitful Hurons, to the people beyond Horicon, and fight beside the deceitful Frenchmen. With us they shall not dwell; let them be seen no more amongst us.--Is my judgment good?" A general cry of approbation followed; the council broke up, and the warriors commenced wandering about, those who came from a distance seeking hospitality in the neighbouring lodges; for the great lodge itself could not afford room for all. To her own little chamber, Otaitsa retired at once; and, barring the door, went down upon her knees, to offer up thanksgiving and prayer--thanksgiving, for hope is ever a blessing--prayer, for danger was still before her eyes. Safe for the next six months she knew Walter would be, in the careful custody of her father; but she still prayed earnestly that her mother's God would find some way of deliverance, for the sake of Him who died to save mankind. CHAPTER XXXII. More than five months had passed, months of great trouble and anxiety to many. The usual tragedies of life had been enacted in many a house, and in many a home: the dark, ever-recurring scene of death and suffering and grief had passed through the dwellings of rich and poor. Many a farce, too, in public and private, had been exhibited to the gaze; for, in the history of each man and of all the world, the ridiculous and the grand, the sad and the cheerful, stand side by side in strange proximity.
  • 55. The woods, blazing in their autumnal crimson when last we saw them, had worn and soiled, in about a fortnight, the glorious vestments of the autumn, and cast them to the earth; and now they had put on the green garments of the summer, and robed themselves in the tender hues of youth. The rivers and the streams, bound in icy chains for many a month, now dashed wildly and impetuously along in the joy of lately-recovered freedom, and, swollen by the spring rains, in some places became torrents; in some places, slowly flooded the flat land, marching over the meadows like a vast invading army. The beasts of the forest were busy in their coverts, the birds in the brake, or on the tree-top; the light clouds skimmed along the soft blue sky; and the wind tossed the light young branches to and fro in its sport. Everything was gay and active on the earth, and over the earth; everything spoke of renewed life, and energy, and hope. To the fancy of those who have not seen it, the vast primæval forest presents an idea of monotony; and certainly, when seen from a distance, it produces that impression on the mind. Looming dark and sombre, thick and apparently impenetrable, over upland and dell, over plain and mountain, it conveys a sensation of solemnity by its very sameness; and, though the first sight is sublime, its long- continued presence is oppressive. But penetrate into its depths, and you will find infinite variety; now the dense, tangled thicket, through which the panther and the wild cat creep with difficulty, and into which the deer cannot venture; now the quaking morass, unsafe to the foot, yet bearing up the tamarach or cedar, with its rank grasses, its strangely-shaped leaves, and its rich and infinitely varied flowers; now the wide grove, extending for miles and miles, with the tall bolls of the trees rising up distinct and separate, and with little or no brushwood hiding the carpet of dry pine-spindles and cones on which they stand; then the broad savanna, with its grass knee-high, green and fresh and beautiful, and merely a tree here and there to shelter some spot from the sun, and cast a soft blue shadow on the natural meadow; and then again, in many spots, a space of ground
  • 56. where every characteristic of the forest is mingled--here thick and tangled brush, there a patch of open green, here the swamp running along the brook-side, there the sturdy oak or wide-spreading chestnut, standing far apart in reverence for each other's giant limbs, shading many a pleasant slope, or topping the lofty crag. It was under one of these large trees, on a high bank commanding the whole prospect round for many and many a mile, and in the eastern part of the province of New York, that three red men were seated in the early summer of 1758. A little distance in advance of them, and somewhat lower down the hill, was a small patch of brush, composed of fantastic-looking bushes, and one small blasted tree. It formed, as it were, a sort of screen to the Indians' resting-place from all eyes below, yet did not in the least impede their sight as it wandered over the wide forest world around them. From the elevation on which they were placed, the eye of the red man, which seems, from constant practice, to have gained the keenness of the eagle's sight, could plunge into every part of the woods around where the trees were not actually contiguous. The trail, wherever it quitted the shelter of the branches; the savanna, wherever it broke the outline of the forest; the river, where it wound along in its course to the ocean; the military road from the banks of the Hudson to the head of Lake Horicon; the smallest pond, the little stream, were all spread out to view as if upon a map. Over the wide, extensive prospect the eyes of those three Indians wandered incessantly, not as if employed in searching for some definite object, the direction of which, if not the precise position, they knew, but rather as if they were looking for anything which might afford them some object of pursuit or interest. They sat there nearly two hours in the same position; and during the whole of that time not more than four or five words passed between them. At length they began to converse, though at first in a low tone, as if the silence had its awe even for them. One of them pointed with
  • 57. his hand towards a spot to the eastward, saying, "There is something doing there." In the direction to which he called the attention of his companions was seen spread out, in the midst of the forest and hills, a small, but exquisitely beautiful lake, seemingly joined on to another, of much greater extent, by a narrow channel. Of the former, the whole extent could not be seen; for, every here and there, a spur of the mountain cut off the view, and broke in upon the beautiful waving line of the shore. The latter was more distinctly seen, spread out broad and even, with every little islet, headland, and promontory, marked clear and distinctly against the bright, glistening surface of the waters. Near the point where the two lakes seemed to meet, the Indians could descry walls, and mounds of earth, and various buildings of considerable size; nay, even what was probably the broad banner of France, though it seemed but a mere whitish spot in the distance. At the moment when the Indians spoke, coming from a distant point on the larger lake, the extreme end of which was lost to view in a sort of indistinct blue haze, a large boat or ship might be seen, with broad white sails, wafted swiftly onward by a cold north- easterly wind. Some way behind it, another moving object appeared- -a boat likewise, but much more indistinct; and, here and there nearer in shore, two or three black specks, probably canoes, were darting along upon the bosom of the lake, like water-flies upon the surface of a still stream. "The pale-faces take the war-path against each other," said another of the Indians, after gazing for a moment or two. "May they all perish!" exclaimed the third. "Why are our people so mad as to help them? Let them fight, and slay, and scalp as many of each other as they can, and then the red men tomahawk the remainder."
  • 58. The other two uttered a bitter malediction, in concert with this fierce, but not impolitic, thought; and then, after one of their long pauses, the first who had spoken, resumed the conversation, saying- - "Yet I would give one of the feathers of the White Bird to know what the pale-faces are doing. Their hearts are black against each other. Can you not tell us, Apukwa? You were on the banks of Horican yesterday, and must have heard the news from Corlear." "The news from Albany matters much more," answered Apukwa. "The Yengees are marching up with a cloud of fighting-men; and people know not where they will fall. Some think Oswego; some think Ticonderoga. I am sure that it is the place of the Singing Waters that they go against." "Will they do much in the war-path?" asked the brother of the Snake; "or will the Frenchman make himself as red as he did last year, at the south end of Horicon?" "The place of the Singing Waters is strong, brother," replied Apukwa, in a musing tone, "and the Frenchmen are great warriors; but the Yengees are many in number, and they have called for aid from the Five Nations. I told the Huron who sold me powder, where the eagles would come down; and I think he would not let the tidings slumber beneath his tongue. The great-winged canoes are coming up Corlear very quick; but I think my words must have been whispered in the French chief's ear, to cause them to fly so quickly to Ticonderoga." A faint, nearly-suppressed smile came upon the lips of his two companions as they heard of this proceeding; but the younger of the three said-- "And what will Apukwa do in the battle?" "Scalp my enemies," replied Apukwa, looking darkly round.
  • 59. "Which is thine enemy?" asked the brother of the Snake. "Both," answered the medicine-man, bitterly; "and every true Honontkoh should do as I do; follow them closely, and slay every man that flies, be his nation what it may. So long as he be white, it is enough for us. He is an enemy; let us blunt our scalping-knives on the skulls of the pale-faces. Then, when the battle is over, we can take our trophies to the conqueror, and say, 'We have been upon thy side.'" "But will he not know?" suggested the younger man; "will he listen so easily to the song?" "How should he know?" asked Apukwa, coldly. "If we took him red men's scalps, he might doubt; but all he asks is white men's scalps, and we will take them. They are all alike, and they will have no faces under them." This ghastly jest was highly to the taste of the two hearers; and, bending down their heads together, the three continued to converse for several minutes in a whisper. At length, one of them said-- "Could we not take Prevost's house as we go? How many brothers did you say would muster?" "Nine," answered Apukwa; "and our three selves make twelve." Then, after pausing for a moment or two in thought, he added, "It would be sweet as the strawberry and as easy to gather; but there may be thorns near it. We may tear ourselves, my brothers." "I fear not," returned the brother of the Snake; "so that I but set my foot within that lodge, with my rifle in my hand, and my tomahawk in my belt, I care not what follows." "The boy's to die," rejoined Apukwa; "why seek more in his lodge at thine own risk?"
  • 60. The other did not answer; but, after a moment's pause, he asked- -"Who is it has built the lodge still farther to the morning?" "One of the workers of iron," answered Apukwa, meaning the Dutch. "He is a great chief, they say, and a friend of the Five Nations." "Then no friend of ours, my brother," responded the other speaker; "for though it be the children of the Stone who have shut the door of the lodge against us, and driven us from the council-fire, the Five Nations have confirmed their saying, and made the Honontkoh a people apart. Why should we not fire that lodge too, and then steal on to the dwelling of Prevost?" "Thy lip is thirsty for something," said Apukwa. "Is it the maiden thou wouldst have?" The other smiled darkly; and, after remaining silent for a short space, answered-- "They have taken from me my captive; and my hand can never reach the Blossom I sought to gather. The boy may die, but not by my tomahawk; and, when he does die, I am no better, for I lose that which I sought to gain by his death. Are Apukwa's eyes misty, that he cannot see? The spirit of the Snake would have been as well satisfied with the blood of any other pale-face; but that would not have satisfied me." "Yet making Prevost's house red will not gather for thee the Blossom," answered Apukwa. The third and younger of the Indians laughed, saying---- "The wind changes, Apukwa, and so does the love of our brother. The maiden in the lodge of Prevost is more beautiful than the Blossom. We have seen her thrice since this moon grew big; and my
  • 61. brother calls her the Fawn, because she has become the object of his chase." "Thou knowest not my thought," said the brother of the Snake, gravely. "The maiden is fair, and she moves round her father's lodge like the sun. She shall be the light of mine, too; but the brother of the snake forgets not those who disappoint him; and the boy Prevost would rather have seen the tomahawk falling, than know that the Fawn is in his lodge." The other two uttered that peculiar humming sound by which the Indians sometimes intimate that they are satisfied; and the conversation which went on between them related chiefly to the chances of making a successful attack upon the house of Mr. Prevost. Occasionally, indeed, they turned their eyes towards the boats upon Lake Champlain, and commented upon the struggle that was about to be renewed between France and England. That each party had made vast preparations was well known, and intelligence of the extent and nature of those preparations had spread far and wide amongst the tribes, with wonderful accuracy as to many of the details, but without any certain knowledge of where the storm was to break. All saw, however, and comprehended, that a change had come over the British government; that the hesitating and doubtful policy which had hitherto characterized their military movements in America was at an end; and that the contest was now to be waged for the gain and loss of all the European possessions on the North American continent. Already was it known amongst the Five Nations, although the time for the transmission of the intelligence was incredibly small, that a large fleet and armament had arrived at Halifax, and that several naval successes over the French had cleared the way for some great enterprise in the north. At the same time, the neighbourhood of Albany was full of the bustle of military preparation; a large force was already collected under Abercrombie for some great attempt upon the lakes: and from the west news had
  • 62. been received that a British army was marching rapidly towards the French posts upon the Ohio and the Monongahela. The Indian nations roused themselves at the sound of war; for, though some few of them acted more regularly in alliance with one or the other of the contending European powers, a greater number than is generally believed cared little whom they attacked, or for whom they fought, or whom they slew; and were, in reality, but as a flock of vultures spreading their wings at the scent of battle, and ready to take advantage of the carnage, whatever was the result of the strife. CHAPTER XXXIII. We must now return to the scene in which this narrative commenced. But oh, how changed was the aspect of all things from that which the house of Mr. Prevost presented but five short months before! The father and the daughter were there alone. The brother no longer glanced about the house with his blithesome air and active energies; and the thought of him and of his fate hung continually like a dark shadow over those to whom he was so dear. They were not wholly without comfort, they were not wholly without hope; for, from time to time, renewed assurances came to them from many a quarter that Walter would still be saved. Yet time wore on, and he was not delivered. When one speaks of five months of uncertainty, it seems a long and tedious period, and it would be so if it were all one blank; but there are a thousand little incidents--incidents external and internal--
  • 63. that fill up the time, and make it pass wonderfully soon, especially if fear predominates over hope. Didst thou ever sit up, reader, with the sick or dying through the livelong night? In contemplation, it seems an awful task of long endurance to watch there with the eternal battle going on in your breast between the only two deathless passions--the only two which may be called the immortal passions of the soul--from the fading of the evening light till the breaking of another day. And yet it is wonderful how soon, how very soon, one sees the faint blue light of dawn mingling with the sickly yellow glare of the watcher's lamp. Every thought, every expectation, is an incident. The change of breathing, the restless movement, the muttered word, the whispered comfort, the moistening of the parched lip, the smoothing of the pillow,--all are events that hurry on the time. And so it was in the house of Mr. Prevost. Each day had its something; each hour; and although the object was always the same, or rarely varied, yet the rapid changes of thought and feeling made the time fly far more rapidly than might have been expected. During the winter, Lord H---- visited the house very frequently; and it is probable that, had no dark cloud overshadowed the hopes as well as the happiness of all, he would have pressed for the prize of Edith's hand without delay; but he loved not the mingling of joy and sorrow. In that, at least, his view of the world, and life, and fate, was deceitful. He was not yet convinced, although he had some experience, that such a thing as unalloyed happiness, even for a few short days, is not to be found on earth--that the only mine of gold without dross lies beneath the grave. Once, indeed, he hinted, rather than asked, that an early day might be fixed for his union with her he loved; but a tear rose in Edith's eye, and she bent down her head. Her father would have made no objection, although he still thought her very, very young to take upon her the duties of a wife. In that respect his feelings were
  • 64. not changed; but the loss of his son weighed heavily upon him, and, calling him away from the present, had projected his thoughts into the future. What might be Edith's fate, he asked himself, if he too should be taken from her? Any of the many accidents of life might leave her alone, and an orphan; and there is nothing which brings home so sensibly to our thoughts the unstable hold which we have upon all earthly things, so much as our tenderness for those we love. But Lord H---- saw that it would be painful to Edith herself to become his bride as long as Walter's late was uncertain; and he said no more. In the meantime the gathering together of the British soldiers on the Hudson and the Mohawk had, like one wave meeting another, somewhat repelled the Indian tribes. A runner, a half-breed, or one or two red men together--more frequently from the nation of the Mohawks than from any other tribe--would be seen occasionally wandering through the woods or crossing the open ground near the settler's dwelling; but they seldom approached the house; and their appearance caused no apprehension. Relations of the greatest amity had been re-established between the British authorities and the chiefs of the Five Nations; and several of the tribes were preparing to take part in the coming strife upon the side of England. Three times during the winter the house of Mr. Prevost was visited by a single Indian of the Oneida tribe. On two occasions it was a man who presented himself; and his stay was very short. On the first occasion, Edith was alone; when, without the sound of a footfall, he glided in like a dark shadow. His look was friendly, though for a moment he said nothing. Edith, well knowing Indian habits, asked if he would take food. He answered "Yes," in his own language; and she called some of the servants to supply him; but, before he ate he looked up in her face, saying-- "I am bidden to tell thee that thy brother shall be safe."
  • 65. "Whose words do you bear?" asked Edith. "Is it the Black Eagle who speaks?" "Nay, it is Otaitsa," replied the man. This was all Edith could learn; for the messenger was either ignorant of more, or affected to be so; yet still it was a comfort to her. The next who came was a woman somewhat past the middle age, and by no means beautiful. She stayed long; and, with good- humoured volubility, related all that had happened immediately after Edith's visit to the Oneida castle. She dwelt upon the attempt of the Blossom to deliver her lover as she would have expatiated upon some feat of daring courage in a warrior; and though in the end she had to tell how the maiden's bold attempt had been frustrated, she concluded by saying-- "Yet he shall be safe. They shall not slay our brother." The third time the man returned, hearing the same assurance; but, as hour after hour and day after day went by without the lad's return, or any definite news of him, hope sickened and grew faint. By this time it was known that the efforts of the Mohawks and Onondagas had been frustrated; and, moreover, it was plainly intimated by the chiefs of those two nations that they would interfere no more. "The Oneidas have reproved us," they said, "and we had no reply. We must not make the children of the Stone hiss at our children; neither must we break the bands of our alliance for the sake of one man." The scouts who had been put under the order of Woodchuck were recalled to the army early in the spring without having effected anything. All that had been heard at the forts showed that the young prisoner had been removed to the very farthest part of the Oneida territory, where it was impossible for any one Englishman to penetrate without being discovered by the Indians.
  • 66. If, in civilized times, with a country cleared in a great degree of its forests, and with a regular organization ensuring rapid intercourse between place and place, it is possible for a man to be hidden for weeks and months from the most diligent search; how much more easy was concealment in those days, when, with the exception of a few patches of maize or other grain, the whole land was one wild tangled wood, crossed, it is true, with innumerable Indian trails, but with no direct means of communication, except by one large road, and the lakes and rivers. Search would have been in vain, even if in the political state of the country it could have been attempted; but the attempt was impossible, without rendering the whole country hostile; for the Mohawks themselves showed no inclination to suffer any considerable body of men to cross their territory, except indeed a small party of soldiers, now and then, destined to strengthen the garrisons at Oswego, or any of the regular British posts. Of Woodchuck himself, nothing was heard, till the flowers began to spring up close upon the footsteps of the snow. It was believed that he was still in the forest; but even of this, no one was assured; and all that could with any accuracy be divined, was, that he had not fallen into the hands of the Oneidas, inasmuch as there was every reason to believe that, had such been the case, Walter's liberation would immediately have followed. Thus matters had gone on in the household of Mr. Prevost, till about a month before the period at which I have thought best to present to the reader the three Indians seated on the hill. The snow had melted, except in a few places, where it still lay in white patches, under shelter of the darker and thicker-leaved evergreens; here and there, too, it might be seen in the shade of a steep bank; but the general surface of the country was free, and, despite, the variable character of the American spring--one day as soft as summer, and then two or three following, with the icy fang of winter in the wind, and the sky covered with low lurid clouds--the flowers were peeping out in every covert, and mingling themselves thickly