100% found this document useful (4 votes)
46 views55 pages

Immediate download Julia Quick Syntax Reference: A Pocket Guide for Data Science Programming 1st Edition Antonello Lobianco ebooks 2024

Julia

Uploaded by

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

Immediate download Julia Quick Syntax Reference: A Pocket Guide for Data Science Programming 1st Edition Antonello Lobianco ebooks 2024

Julia

Uploaded by

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

Download the Full Version of textbook for Fast Typing at textbookfull.

com

Julia Quick Syntax Reference: A Pocket Guide for


Data Science Programming 1st Edition Antonello
Lobianco

https://textbookfull.com/product/julia-quick-syntax-
reference-a-pocket-guide-for-data-science-programming-1st-
edition-antonello-lobianco/

OR CLICK BUTTON

DOWNLOAD NOW

Download More textbook Instantly Today - Get Yours Now at textbookfull.com


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

Julia Quick Syntax Reference: A Pocket Guide for Data


Science Programming 1st Edition Antonello Lobianco

https://textbookfull.com/product/julia-quick-syntax-reference-a-
pocket-guide-for-data-science-programming-1st-edition-antonello-
lobianco-2/
textboxfull.com

C# 7 Quick Syntax Reference: A Pocket Guide to the


Language, APIs, and Library Mikael Olsson

https://textbookfull.com/product/c-7-quick-syntax-reference-a-pocket-
guide-to-the-language-apis-and-library-mikael-olsson/

textboxfull.com

C++17 quick syntax reference: a pocket guide to the


language, APIs and library Third Edition Olsson

https://textbookfull.com/product/c17-quick-syntax-reference-a-pocket-
guide-to-the-language-apis-and-library-third-edition-olsson/

textboxfull.com

Haskell Quick Syntax Reference: A Pocket Guide to the


Language, APIs, and Library 1st Edition Stefania Loredana
Nita
https://textbookfull.com/product/haskell-quick-syntax-reference-a-
pocket-guide-to-the-language-apis-and-library-1st-edition-stefania-
loredana-nita/
textboxfull.com
C# 7 Quick Syntax Reference: A Pocket Guide to the
Language, APIs, and Library 2nd Edition Mikael Olsson

https://textbookfull.com/product/c-7-quick-syntax-reference-a-pocket-
guide-to-the-language-apis-and-library-2nd-edition-mikael-olsson/

textboxfull.com

C++20 Quick Syntax Reference : a pocket guide to the


language, APIs, and library 4th Edition Mikael Olsson

https://textbookfull.com/product/c20-quick-syntax-reference-a-pocket-
guide-to-the-language-apis-and-library-4th-edition-mikael-olsson/

textboxfull.com

C++20 Quick Syntax Reference A Pocket Guide to the


Language, APIs, and Library. 4th Edition Mikael Olsson

https://textbookfull.com/product/c20-quick-syntax-reference-a-pocket-
guide-to-the-language-apis-and-library-4th-edition-mikael-olsson-2/

textboxfull.com

Java quick syntax reference Second Edition Olsson

https://textbookfull.com/product/java-quick-syntax-reference-second-
edition-olsson/

textboxfull.com

Java EE 6 Pocket Guide A Quick Reference for Simplified


Enterprise Java Development 1st Edition Gupta Arun

https://textbookfull.com/product/java-ee-6-pocket-guide-a-quick-
reference-for-simplified-enterprise-java-development-1st-edition-
gupta-arun/
textboxfull.com
Antonello Lobianco

Julia Quick Syntax Reference


A Pocket Guide for Data Science Programming
Antonello Lobianco
Nancy, France

Any source code or other supplementary material referenced by the


author in this book is available to readers on GitHub via the book’s
product page, located at www.​apress.​com/​9781484251898 . For more
detailed information, please visit http://​www.​apress.​com/​source-code
.

ISBN 978-1-4842-5189-8 e-ISBN 978-1-4842-5190-4


https://doi.org/10.1007/978-1-4842-5190-4

© Antonello Lobianco 2019

This work is subject to copyright. All rights are reserved by the


Publisher, whether the whole or part of the material is concerned,
specifically the rights of translation, reprinting, reuse of illustrations,
recitation, broadcasting, reproduction on microfilms or in any other
physical way, and transmission or information storage and retrieval,
electronic adaptation, computer software, or by similar or dissimilar
methodology now known or hereafter developed.

Trademarked names, logos, and images may appear in this book. Rather
than use a trademark symbol with every occurrence of a trademarked
name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no
intention of infringement of the trademark. The use in this publication
of trade names, trademarks, service marks, and similar terms, even if
they are not identified as such, is not to be taken as an expression of
opinion as to whether or not they are subject to proprietary rights.

While the advice and information in this book are believed to be true
and accurate at the date of publication, neither the authors nor the
editors nor the publisher can accept any legal responsibility for any
errors or omissions that may be made. The publisher makes no
warranty, express or implied, with respect to the material contained
herein.

Distributed to the book trade worldwide by Springer Science+Business


Media New York, 233 Spring Street, 6th Floor, New York, NY 10013.
Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-
[email protected], or visit www.springeronline.com. Apress Media,
LLC is a California LLC and the sole member (owner) is Springer
Science + Business Media Finance Inc (SSBM Finance Inc). SSBM
Finance Inc is a Delaware corporation.
Introduction
This Julia quick syntax reference book covers the main syntax elements
of the Julia language as well as some of its more important packages.
The first chapter explains the basic skills needed to set up the
software you need to run and develop Julia programs, including
managing Julia packages.
Chapter 2 presents the many predefined types (integers, strings,
arrays, etc.) and the methods to work with them. Memory and copy
issues are also presented in this chapter, together with an important
discussion about the implementation of the various concepts
ofmissingness .
After the basic data types have been introduced, Chapter 3 deals
with how to organize them in a sequence of logical statements to
compose your program. Control flow, functions, blocks, and scope are
all discussed in this chapter.
In Chapter 4 , we extend our discussion to custom types—in Julia,
both primitive and composite types can be custom-defined—and to
their organization in the program, either using inheritance or
composition. This chapter will be of particular use to readers
accustomed to other object-oriented programs, in order to see how to
apply object-oriented concepts in Julia.
Chapter 5 explains how to retrieve the inputs needed by your
program from a given source (the terminal, a text/CSV/Excel/JSON file,
or a remote resource) and conversely, to export the outputs of your
program.
In Chapter 6 , we discuss a peculiar feature of Julia, that is, the
possibility to manipulate the code itself after it has been parsed, but
before it is compiled and run. This paves the way to powerful macro
programming. We discuss it and present the concepts ofsymbols
andexpressions in Chapter 6 .
Julia is a relatively new language, and while the package ecosystem
is developing extremely rapidly (as most packages can be written
directly in the Julia language alone), it is highly likely that you will still
need libraries for which a direct port to Julia is not yet available.
Conversely, your main workflow may be in another, slower, high-level
language and you may want to use Julia to implement some
performant-critical tasks. Chapter 7 shows how to use C, C++, Python,
and R code and their relative libraries in Julia and, conversely, embed
Julia code in Python or R programs.
The following chapter (Chapter 8 ) gives a few recommendations for
writing efficient code, with runtime performances comparable to
compiled languages. We also deal here withprogrammer’s efficiency ,
discussing profiling and debugging tools and with a short introduction
to runtime exceptions.
This completes the discussion of thecore of the language. Julia,
however, has been designed as a thin language where most features are
provided by external packages, either shipped with Julia itself (a sort of
Julia Standard Library) or provided by third parties.
Therefore, the second part of the book deals with this Julia package
ecosystem. Chapter 9 introduces the main packages for working with
numerical data: storage with data structure packages likeDataFrames
andIndexedTables ; munging withDataFramesMeta ,Query ,
andPipe ; and visualization with thePlot package.
If Chapter 9 deals with processing numerical data, Chapter 10 deals
with mathematical libraries for more theoretical work.JuMP is an
acclaimed “algebraic modeling language” for numerical optimization
(and can be in itself the primary reason to learn about Julia). We
present two complete examples with linear and non-linear models. The
second model is then rewritten to be analytically resolved withSymPy ,
which is a library for symbolic computation, e.g. the analytical
resolution of derivatives, integrals, and equations (and systems of
equations). Chapter 10 ends with a presentation ofLsqFit , a powerful
and versatile library to fit data. Finally, Chapter 11 concludes the book
with a series of tools that are of more general use, like composing
dynamic documents withWave , dealing with ZIP files withZipFile ,
and exposing a given Julia model on the web withInteract andMux .
Examples given in the text are intentionally trivial. They are minimal
working examples of the syntax for the concepts they explain. If you are
looking for recipes directly applicable to your domain, a “cookbook”
kind of book may be more convenient.
While each package has been tested specifically with Julia 1.2 and
1.3-rc4, thanks to the Julia developers’ commitment to a stable API,
they should remain relevant for the entire 1.x series. Concerning third-
party packages, we report the exact version we tested our code with.
The section entitled “Using the Package Manager” in Chapter 1 explains
how to update a package to a given version if subsequent versions of
the package break the API.
Is such cases, please report the problem to us using the form at
https://julia-book.com . We will regularly publish updates and
errata on this site, where a discussion forum focused on the book is also
available.
Acknowledgments
This work has been supported by the French National Research Agency
through the Laboratory of Excellence, ARBRE, part of the
“Investissements d’Avenir” program (ANR 11 – LABX-0002-01).
I want to thank Germá n Gonzá lez-Morris for his valuable help in
finding errors in the code and improving the description of the
language. I want to also thank Mark Powers, the Apress coordinating
editor, for his numerous “check ins” that pushed me to continue and
finish the book.
This has been possible thanks to the understanding and support of
my family.
Table of Contents
Part I: Language Core
Chapter 1:​Getting Started
1.​1 Why Julia?​
1.​2 Installing Julia
1.​3 Running Julia
1.​4 Miscellaneous Syntax Elements
1.​5 Packages
1.​5.​1 Using the Package Manager
1.​5.​2 Using Packages
1.​6 Help System
Chapter 2:​Data Types and Structures
2.​1 Simple Types (Non-Containers)
2.​1.​1 Basic Mathematic Operations
2.​1.​2 Strings
2.​2 Arrays (Lists)
2.​2.​1 Multidimensional​and Nested Arrays
2.​3 Tuples
2.​4 Named Tuples
2.​5 Dictionaries
2.​6 Sets
2.​7 Memory and Copy Issues
2.​8 Various Notes on Data Types
2.​8.​1 Random Numbers
2.​8.​2 Missing, Nothing, and NaN
Chapter 3:​Control Flow and Functions
3.​1 Code Block Structure and Variable Scope
3.​2 Repeated Iteration:​for and while Loops, List
Comprehension, Maps
3.​3 Conditional Statements:​if Blocks, Ternary Operator
3.​4 Functions
3.​4.​1 Arguments
3.​4.​2 Return Value
3.​4.​3 Multiple-Dispatch (aka Polymorphism)
3.​4.​4 Templates (Type Parameterization​)
3.​4.​5 Functions as Objects
3.​4.​6 Call by Reference/​Call by Value
3.​4.​7 Anonymous Functions (aka “Lambda” Functions)
3.​4.​8 Broadcasting Functions
3.​5 Do Blocks
3.​6 Exiting Julia
Chapter 4:​Custom Types
4.​1 Primitive Type Definition
4.​2 Structure Definition
4.​3 Object Initialization and Usage
4.​4 Abstract Types and Inheritance
4.​4.​1 Implementation of the Object-Oriented Paradigm in
Julia
4.​5 Some Useful Functions Related to Types
Chapter 5:​Input/​Output
5.​1 Reading (Input)
5.​1.​1 Reading from the Terminal
5.​1.​2 Reading from a File
5.​1.​3 Importing Data from Excel
5.​1.​4 Importing Data from JSON
5.​1.​5 Accessing Web Resources (HTTP)
5.​2 Writing (Output)
5.​2.​1 Writing to the Terminal
5.​2.​2 Writing to a File
5.​2.​3 Exporting to CSV
5.​2.​4 Exporting Data to Excel
5.​2.​5 Exporting Data to JSON
5.​3 Other Specialized IO
Chapter 6:​Metaprogramming and Macros
6.​1 Symbols
6.​2 Expressions
6.​2.​1 Creating Expressions
6.​2.​2 Evaluating Symbols and Expressions
6.​3 Macros
6.​3.​1 Macro Definition
6.​3.​2 Macro Invocation
6.​3.​3 String Macros
Chapter 7:​Interfacing Julia with Other Languages
7.​1 Julia ⇄ C
7.​2 Julia ⇄ C++
7.​2.​1 Interactive C++ Prompt
7.​2.​2 Embed C++ Code in a Julia Program
7.​2.​3 Load a C++ Library
7.​3 Julia ⇄ Python
7.​3.​1 Embed Python Code in a Julia Program
7.​3.​2 Use Python Libraries
7.​3.​3 PyJulia:​Using Julia in Python
7.​4 Julia ⇄ R
7.​4.​1 Interactive R Prompt
7.​4.​2 Embed R Code in a Julia Program
7.​4.​3 Use R Libraries
7.​4.​4 JuliaCall:​Using Julia in R
Chapter 8:​Effectively Write Efficient Code
8.​1 Performance
8.​1.​1 Benchmarking
8.​1.​2 Profiling
8.​1.​3 Type Stability
8.​1.​4 Other Tips to Improve Performance
8.​2 Code Parallelization
8.​2.​1 Adding and Removing Processes
8.​2.​2 Running Heavy Computations on a List of Items
8.​2.​3 Aggregate Results
8.​3 Debugging
8.​3.​1 Introspection Tools
8.​3.​2 Debugging Tools
8.​4 Managing Runtime Errors (Exceptions)
Part II: Packages Ecosystem
Chapter 9:​Working with Data
9.​1 Using the DataFrames Package
9.​1.​1 Installing and Importing the Library
9.​1.​2 Creating a DataFrame or Loading Data
9.​1.​3 Getting Insights About the Data
9.​1.​4 Filtering Data (Selecting or Querying Data)
9.​1.​5 Editing Data
9.​1.​6 Editing Structure
9.​1.​7 Managing Missing Values
9.​1.​8 The Split-Apply-Combine Strategy
9.​1.​9 Pivoting Data
9.​1.​10 Dataframe Export
9.​2 Using IndexedTables
9.​2.​1 Creating an IndexedTable (NDSparse)
9.​2.​2 Row Filtering
9.​2.​3 Editing/​Adding Values
9.​3 Using the Pipe Operator
9.​4 Plotting
9.​4.​1 Installation and Backends
9.​4.​2 The Plot Function
9.​4.​3 Plotting from DataFrames
9.​4.​4 Saving
Chapter 10:​Mathematical Libraries
10.​1 JuMP, an Optimization Framework
10.​1.​1 The Transport Problem:​A Linear Problem
10.​1.​2 Choosing Between Pizzas and Sandwiches, a Non-
Linear Problem
10.​2 SymPy, a CAS System
10.​2.​1 Loading the Library and Declaring Symbols
10.​2.​2 Creating and Manipulating Expressions
10.​2.​3 Solving a System of Equations
10.​2.​4 Retrieving Numerical Values
10.​3 LsqFit, a Data Fit Library
10.​3.​1 Loading the Libraries and Defining the Model
10.​3.​2 Parameters
10.​3.​3 Fitting the Model
10.​3.​4 Retrieving the Parameters and Comparing them with
the Observations
Chapter 11:​Utilities
11.​1 Weave for Dynamic Documents
11.​2 Zip Files
11.​2.​1 Writing a Zip Archive
11.​2.​2 Reading from a Zipped Archive
11.​3 Interact and Mux:​Expose Interacting Models on the Web
11.​3.​1 Importing the Libraries
11.​3.​2 Defining the Logic of the Model
11.​3.​3 Defining Controls and Layout
11.​3.​4 Providing Widgets to Web Users
Index
About the Author and About the Technical
Reviewer

About the Author


Antonello Lobianco, PhD
is a research engineer employed by a French Grande école (Polytechnic
University). He works on biophysical and economic modeling of the
forest sector and is responsible for the Lab Models portfolio. He uses
C++, Perl, PHP, Python, and Julia. He teaches environmental and forest
economics at the undergraduate and graduate levels and modeling at
the PhD level. He has been following the development of Julia as it fits
his modeling needs, and he is the author of several Julia packages
(search for sylvaticus on GitHub for more information).

About the Technical Reviewer


Germán González-Morris
is a polyglot software architect/engineer with 20+ years in the field. He
has knowledge of Java (EE), Spring, Haskell, C, Python, and JavaScript,
among others. He works with web distributed applications. Germá n
loves math puzzles (including reading Knuth) and swimming. He has
tech reviewed several books, including an application container book
(Weblogic), as well as titles covering various programming languages
(Haskell, TypeScript, WebAssembly, Math for Coders, and RegExp, for
example). You can find more information on his blog (
https://devwebcl.blogspot.com/ ) or Twitter
account(@devwebcl) .
Part I
Language Core
© Antonello Lobianco 2019
A. Lobianco, Julia Quick Syntax Reference
https://doi.org/10.1007/978-1-4842-5190-4_1

1. Getting Started
Antonello Lobianco1

(1) Nancy, France

1.1 Why Julia?


With so many programming languages available, why create yet
another one? Why invest the time to learn Julia? Is it worth it?
One of the main arguments in favor of using Julia is that it
contributes to improving a trade-off that has long existed in
programming—fast coding versus fast execution.
On the one side, Julia allows the developer to code in a dynamic,
high-level language similar to Python, R, or MATLAB, interacting with
the code and having powerful expressivity (see Chapter 6, for example).
On the other side, with minimum effort, developers can write
programs in Julia that run (almost) as fast as programs written in C or
FORTRAN.
Wouldn’t it be better, though, to optimize existing languages, with
their large number of libraries and established ecosystems, rather than
create a new language from scratch?
Well, yes and no. Attempts to improve runtime execution of dynamic
languages are numerous. PyPy (https://pypy.org), Cython
(https://cython.org), and Numba
(https://numba.pydata.org) are three notable examples for the
Python programming language. They all clash with one fact: Python
(and, in general, all the current dynamic languages) was designed
before the recent development of just-in-time (JIT) compilers, and
hence it offers features that are not easy to optimize. The optimization
tools either fail or require complex workarounds in order to work.
Conversely, Julia has been designed from the ground up to work
with JIT compilers, and the language features—and their internal
implementations—have been carefully considered in order to provide
the programmer with the expected productivity of a modern language,
all while respecting the constraints of the compiler. The result is that
Julia-compliant code is guaranteed to work with the underlying JIT
compiler, producing in the end highly optimized compiled code.

The Shadow Costs of Using a New Language

If it is true that the main “costs” of using a new language relate to


learning the language and having to abandon useful libraries and
comfortable, feature-rich development editors that you are
accustomed to, it is also true that in the Julia case these costs are
mitigated by several factors:
The language has been designed to syntactically resemble
mainstream languages (you’ll see it in this book!). If you already
know a programming language, chances are you will be at ease
with the Julia syntax.
Julia allows you to easily interface your code with all the major
programming languages (see Chapter 7, “Interfacing Julia with
Other Languages”), hence reusing their huge sets of libraries
(when these are not already ported to Julia).
The development environments that are available—e.g., Juno
(https://junolab.org), IJulia Jupiter kernel
(https://github.com/JuliaLang/IJulia.jl), and
VSCode Julia plugin
(https://github.com/JuliaEditorSupport/julia-
vscode)—are frankly quite cool, with many common features
already implemented. They allow you to be productive in Julia
from the first time you code with it.
Apart from the breakout in runtime performances from traditional
high-level dynamic languages, the fact that Julia was created from
scratch means it uses the best, most modern technologies, without
concerns over maintaining compatibility with existing code or internal
architectures. Some of the features of Julia that you will likely
appreciate include built-in Git-based package manager, full code
introspection, multiple dispatches, in-core high-level methods for
parallel computing, and Unicode characters in variable names (e.g.,
Greek letters).
Thanks to its computational advantages, Julia has its natural roots in
the domain of scientific, high-performance programming, but it is
becoming more and more mature as a general purpose programming
language. This is why this book does not focus specifically on the
mathematical domain, but instead develops a broad set of simple,
elementary examples that are accessible even to beginner
programmers.

1.2 Installing Julia


Julia code can be run by installing the Julia binaries for your system
available in the download section
(http://julialang.org/downloads/) of the Julia Project
website (https://julialang.org).
The binaries ship with a Julia interpreter console (aka, the “REPL”—
Read, Eval, Print, Loop), where you can run Julia code in a command-
line fashion.
For a better experience, check out an Integrated Development
Environment, for example, Juno (http://junolab.org/) an IDE
based on the Atom (https://atom.io) text editor, or IJulia
(https://github.com/JuliaLang/IJulia.jl), the Julia
Jupiter (http://jupyter.org/) backend.
Detailed setup instructions can be found on their respective sites,
but in a nutshell, the steps are pretty straightforward.
For Juno:
Install the main Julia binaries first.
Download, install, and open the Atom text editor
(https://atom.io).
From within Atom, go to the Settings ➤ Install panel.
Type uber-juno into the search box and press Enter. Click the
Install button on the package with the same name.
For IJulia:
Install the main Julia binaries first.
Install the Python-based Jupyter Notebook server using the
favorite tools of your OS (e.g., the Package Manager in Linux, the
Python spip package manager, or the Anaconda distribution).
From a Julia console, type using Pkg;
Pkg.update();Pkg.add("IJulia");Pkg.build("IJuli
a").
The IJulia kernel is now installed. Just start the notebook server
and access it using a browser.
You can also choose, at least to start with, not to install Julia at all,
and try instead one of the online computing environments that support
Julia. For example, JuliaBox (https://juliabox.com/), CoCalc
(https://cocalc.com/doc/software-julia.html),
Nextjournal (https://nextjournal.com), and Binder
(https://mybinder.org).

Some tricks for Juno and IJulia

Juno can:
Enable block selection mode with .
Run a selection of code by selecting it and either selecting Run
Block or typing on Windows and Linux or
on Mac.
Comment/uncomment a block of code with
(Windows and Linux) or (Mac) .

IJulia:
Check out the many keyboard shortcuts available from Help ➤
Keyboard Shortcuts.
Need to run Julia in a computational environment for a team or
a class? Use JupyterHub
(https://github.com/jupyterhub/jupyterhub), the
multi-user solution based on Jupyter.

1.3 Running Julia


There are many ways to run Julia code, depending on your needs:
1. Julia can run interactively in a console. Start julia to obtain the
REPL console, and then type the commands there (type exit() or
use CTRL+D when you are finished).

2. Create a script, i.e. a text file ending in .jl, and let Julia parse and
run it with julia myscript.jl [arg1, arg2,..].Script
files can also be run from within the Julia console. Just type
include("myscript.jl").

3. In Linux or on MacOS, you can instead add at the top of the script
the location of the Julia interpreter on your system, preceded by #!
and followed by an empty row, e.g. #!/usr/bin/julia (You can
find the full path of the Julia interpreter by typing which julia
in a console.). Be sure that the file is executable (e.g., chmod +x
myscript.jl).
You can then run the script with ./myscript.jl.

4. Use an Integrated Development Environment (such as those


mentioned), open a Julia script, and use the run command specific
to the editor.

You can define a global (for all users of the computer) and local (for
a single user) Julia file that will be executed at any startup, where you
can for example define functions or variables that should always be
available. The location of these two files is as follows:
Global Julia startup file:
[JULIA_INSTALL_FOLDER]\etc\julia\startup.jl (where
JULIA_INSTALL_FOLDER is where Julia is installed)
Local Julia startup file:
[USER_HOME_FOLDER]\.julia\config\startup.jl (where
USER_HOME_FOLDER is the home folder of the local user, e.g.
%HOMEPATH% in Windows and ~ in Linux)
Remember to use the path with forward slashes ( / ) with Linux.
Note that the local config folder may not exist. In that case, just create
the config folder as a .julia subfolder and start the new
startup.jl file there.

Julia keeps all the objects created within the same work session
in memory. You may sometimes want to free memory or “clean up”
your session by deleting no longer needed objects. If you want to do
this, just restart the Julia session (you may want to use the trick
mentioned at the end of Chapter 3) or use the Revise.jl
(https://github.com/timholy/Revise.jl) package for
finer control.

You can determine which version of Julia you are using with the
versioninfo() option (within a Julia session).

1.4 Miscellaneous Syntax Elements


Julia supports single-line ( # ) and multi-line ( #= [...] =# )
comments. Multi-line comments can be nested and appear anywhere in
the line:

println("Some code..") JULIA


#=
Multiline comment
#= nested multiline comment =#
Still a comment
=#
println(#= A comment in the middle of the line =#
"This is a code") # Normal single-line comment
You don’t need to use semicolons to indicate the end of a statement.
If they’re used, semicolons will suppress the command output (this is
done automatically in scripting mode). If the semicolon is used alone in
the REPL, it allows you to switch to the OS command shell prompt in
order to launch a system-wide command.
Blocks don’t need to be surrounded by parentheses, but they do
require the keyword end at the close.

While indentation doesn’t carry any functional meaning in the


language, empty spaces sometimes are important. For example,
function calls must uses parentheses with the inputs strictly
attached to the function name, e.g.:

println (x) # rise an ERROR TEXT

println(x) # OK

In Julia, variable names can include a subset of Unicode symbols,


allowing a variable to be represented, for example, by a Greek letter.
In most Julia development environments (including the console), to
type a Greek letter, you use a LaTeX-like syntax. This involves typing \,
then the LaTeX name for the symbol (e.g. \alpha for α), and then
pressing Tab to confirm. Using LaTeX syntax, you can also add
subscripts, superscripts, and decorators.
, α, y1,
All the following are valid, if not crazy, variable names: x1, x̃
y(a+b), y2, , and .
Note, however, that while you can use y2 as a variable name, you
can’t use 2y, as the latter is automatically interpreted as 2 * y.
Together with Unicode, this greatly simplifies the transposition in
computer code of mathematical equations.
If you come from a language that follows a zero-indexing standard
(such as C or Python), one important point to remember is that Julia
arrays are one-based indexed (counting starts from 1 and not 0). There
are ways to override this behavior, but in many cases doing so probably
would do more harm than good.

1.5 Packages
Julia developers have chosen an approach where the core of Julia is
relatively light, and additional functionality is usually provided by
external “packages”.
Julia binaries ship with a set of these packages (think to it as a
“Standard Library”) and a powerful package manager that is able to
download (typically directly from GitHub repositories), pre-compile,
update, and solve dependencies, all with a few simple commands.
While registered packages can be installed simply by using their
name, unregistered packages need their source location to be specified.
At the time of this writing, over 2,400 registered packages have been
published.
Knowing how packages work is essential to efficiently working in
Julia, and this is why I have chosen to introduce package management
early in the book and complement the book with a discussion of some
common packages.

1.5.1 Using the Package Manager


There are two ways to access package management features,
interactively and as an API from within other Julia code:
The interactive way is to type ] in the REPL console to enter a
“special” pkg mode. The prompt will then change from julia> to
(vX.Y) pkg>, where vX.Y is the current Julia version.
You can then run any package manager commands or go back to
the normal interpreter mode with BACKSPACE.
The API way is to import the pkg module into your code (using
Pkg) and then run Pkg.command(ARGS). Obviously, nothing
inhibits you from using the API approach in an interactive session,
but the special package mode has tab completion and other goodies
that make it more comfortable to use.
Note that the two interfaces are not 100% consistent, with the API
interface being slightly more stringent.
Some of the useful package commands are explained in the
following list:
status: Retrieves a list (name and version) of the locally installed
packages.
update: Updates the local index of packages and all the local
packages to the latest version.
add pkgName: Automatically downloads and installs a given
package. For multiple packages use add Pkg1 Pkg2 or
Pkg.add(["Pkg1","Pkg2"]).
add pkgName#master, add pkgName#branchName, or add
pkgName#vX.Y.Z: Checks out the master branch of a given
package, a specific branch, or a specific release, respectively.
free pkgName: Returns the package to the latest release.
rm pkgName: Removes a package and all its dependent packages
that have been installed automatically only for it.
add [email protected]:userName/pkgName.jl.git: Checks
out a non-registered package from a Git repository (here, it’s GitHub).

1.5.2 Using Packages


To access the functionalities of a package, you need to either use or
import it. The difference is as follows:
Using a package allows you to access the package functions directly.
Just include a using mypackage statement in the console or at the
beginning of the script.
Importing a package does the same, but helps in keeping the
namespace clean, as you need then to refer to the package functions
using their full names, as myPkg.myFunction. You can use aliases
or choose to import only a subset of functions (that you can then
access directly).
For example, to access the function plot(), which is available in
the package Plots, you can do the following (see the “Plotting” section
in Chapter 9 for specific plotting issues):
Access the package function directly with using myPackage :

using Plots JULIA


plot(rand(4,4))
Access the package functions using their full names with import
myPackage :

import Plots JULIA


const pl = Plots # This (optionally) creates an
an alias, equivalent to Python `import Plots as
pl`. Declaring it constant may improves the
performances.
pl.plot(rand(4,4)) # `Equivalent to
Plots.plot(rand(4,4))`
Access the package functions directly with import
myPackage:myfunction :

import Plots: plot # We can import


multiplefunctions at once using commas JULIA
plot(rand(4,4))

Finally, you can also include any Julia source files using this line:

include("MyFile.jl") :

When that line runs, the included file is completely ran (not only
parsed) and any symbol defined there becomes available in the scope
(the region of code within which a variable is visible) relative to where
the include was called.
You can read more about packages in the relevant section
(https://julialang.github.io/Pkg.jl/v1/) of the Julia
documentation, or by typing help or help COMMAND in pkg mode to
get more details on the package manager commands.

Across this book, I refer to several packages, either in the


standard library or third-party packages. When I state that a given
function belongs to a given package, remember to add using
PackageName in order to run the code in the examples (I will not
repeat this each time).

1.6 Help System


Julia comes with an integrated help system that retrieves usage
information for most functions directly from the source code. This is
true also for most third-party packages.
Typing ? in the console leads to the Julia help system, and the
prompt changes to help?>. From there, you can search for the
function’s API.

In non-interactive environment like IJulia notebooks, you can use


?search_term to access the documentation.

In Juno, you can right-click to open the contextual menu and choose
Show Documentation to bring up documentation for the object.

If you don’t remember the function name exactly, Julia is kind


enough to return a list of similar functions.

While the actual content returned may vary, you can expect to see
the following information for each function you query:
Its signature
One-line description
Argument list
Hints to similar or related functions
One or more usage examples
A list of methods (for functions that have multiple implementations)
© Antonello Lobianco 2019
A. Lobianco, Julia Quick Syntax Reference
https://doi.org/10.1007/978-1-4842-5190-4_2

2. Data Types and Structures


Antonello Lobianco1

(1) Nancy, France

Julia natively provides a fairly complete and hierarchically organized


set of predefined types (especially the numerical ones). These are
either scalar—like integers, floating-point numbers, and chars,—or
container-like structures able to hold other objects—like
multidimensional arrays, dictionaries, sets, etc.
In this chapter, we discuss them, and in the Chapter 4, where we
cover Julia custom types, we consider their hierarchical organization.
Every value (even the primitive ones) has its own unique type. By
convention types start with a capital letter, such as Int64 or Bool.
Sometimes (such as for all container-like structures and some non-
container ones), the name of the type is followed by other parameters
inside curly brackets, like the types of the contained elements or the
number of dimensions. For example, Array{Int64,2} would be used
for a two-dimensional array of integers.
In Julia terminology, these are referred as to parametric types. In
this book, we will use T as a placeholder to generically indicate a type.
There is no division between object and non-object values. All
values in Julia are true objects having a type. Only values, not variables,
have types. Variables are simply names bound to values. The ::
operator can be used to attach type annotations to expressions and
variables in programs. There are two primary reasons to do this:
As an assertion to help confirm that your program works the way you
expect.
Discovering Diverse Content Through
Random Scribd Documents
any kind worth the name until the white man came. So he learned to
use little sticks for his fire, and built his house of skins stretched over
small poles.
“It is hard for us to realize that cutting down a tree was about the
hardest task an Indian could ever attempt. Why the strongest Indian
in the tribe, working as hard as he could with the best tool he could
find, couldn’t cut down a tree as quickly as you could with your
hunting knife. He could break rocks to pieces by striking them with
other rocks, and he could dig caves in the earth; but when it came to
cutting down a tree he was stumped. The big trees simply stood up
and laughed at him. No wonder he worshipped the forests and the
tree gods!
“Of course when the white man came and supplied axes,
hatchets, and knives, he solved the problem of fire-wood for the
Indian. But he never changed the Indian’s idea about small fires. Too
many thousand generations of Indian ancestors had been making
that kind of a fire all their lives; and the Indian is a great fellow to
stick to fixed habits. He adopted the steel hatchet and the knife, but
he stuck to his round fire and his round tepee.
“And yet, although he had never seen a steel hatchet until the
white man gave him one, he improved the design of the white man’s
axe right away. The white man’s hatchet was a broad-bladed, clumsy
thing, heavy to carry and hard to handle. The Indian designed a thin,
narrow-bladed, light hatchet—the tomahawk—that would bite deeper
into the wood and so cut faster than the white man’s thick hatchet.
And every woodsman now knows that for fast chopping, with little
work, a hatchet made on the lines of the tomahawk beats out the
other kind.”
The old man took his own hunting axe from the sheath at his belt
and held it up for inspection.
“You see it’s just a modified tomahawk,” he said, “with long blade
and thin head, and only a little toy axe, to look at. But it has cut down
many good-sized trees when I needed them, all the same. And the
axe you were using this afternoon, as you probably noticed, is simply
a bigger brother of this little fellow, exactly the same shape. It’s the
kind the trappers use in the far North, because it will do all the work
of a four-pound axe, and is only half as heavy. We’ve got some of
those big axes over there under the tarpaulin, but we’ll leave them
behind when we hit the trail, and take that small one with us.”
While they were talking Martin had been getting out a parcel
containing clothing and odds and ends, and now he sat down before
the fire to “do some work” as he expressed it.
“If you’re not too sleepy to listen,” he said, “I’ll tell you a story that I
know about a little Algonquin Indian boy.”
Larry was never too tired to listen to Martin’s stories; and so he
curled up on a blanket before the fire, while the old man worked and
talked.
CHAPTER V
THE STORY OF WEEWAH THE HUNTER
It had been a hard day’s work for both of them, and strange as
everything was to Larry, and awful as the black woods seemed as he
peeped out beyond the light of the fire, he had a strange feeling of
security and contentment. It might be that there were terribly hard
days of toil and danger and privations ahead, but he was too cozily
situated now to let that worry him.
Besides he was feeling the satisfaction that every boy feels in the
knowledge that he has done something well. And even the exacting
old Martin, always slow to praise or even commend, had told him
over his cup of tea and his soup at supper, that he “would make a
hunter of him some day.” And what higher praise could a boy hope
for?
“Nobody knows just how old Weewah was when he became a
mighty hunter,” Martin began presently, without looking up from his
sewing, “because Indians don’t keep track of those things as we
white folks do. But he couldn’t have been any older than you are,
perhaps not quite so old.
“He was old enough to know how to handle his bow and arrows,
though, to draw a strong enough bow to shoot an arrow clean
through a woodchuck or a muskrat, or even a beaver, although he
had never found the chance to try at the beaver. He carried his own
tomahawk, too—a new one that the factor at Hudson Bay Post had
given him,—and was eager to show his prowess with it on larger
game.
“But the hunting was done by the grown up men of the village,
who thought Weewah too small to hunt anything larger than rabbits.
Yet there were other boys of his own age who found more favor in
the hunters’ eyes because they were larger than he. ‘Some day you
will be a hunter,’ they told him, ‘but now you are too small.’
“Weewah’s heart was big, even if his body was small. And so one
day he took all his long arrows, his strongest bow, and his tomahawk
and resolved to go into the big woods at some distance from the
village, and do something worthy of a hunter.
“It was winter time, and the snow on the ground was knee-deep
with just a little crust on it. On his snow-shoes Weewah glided
through the forest, noticing everything he passed and fixing it in his
memory instinctively so that he could be sure of finding the back trail.
For this day he meant to go deep, deep into the spruce swamp in his
hunting. There he would find game worthy of the bow of the mighty
hunter he intended to prove himself.
“The tracks of many animals crossed his path, little wood dwellers
such as rabbits and an occasional mink. But these did not interest
him to-day. He had brought his snares, of course, for he always
carried them; but to-day his heart was too full of a mighty ambition to
allow such little things as rabbit snares to interrupt his plans.
“Once he did stop when he saw, just ahead of him on the snow, a
little brown bunch of fur with two big brown eyes looking at him
wonderingly. In an instant he had drawn the poised arrow to his
cheek and released it with a twang. And a moment later the little
brown bunch of fur was in Weewah’s pouch, ready for making into
rabbit stew in the evening.
“Weewah took it as a good omen that he had killed the rabbit on
the very edge of the spruce swamp that he had selected for his
hunting ground. Soon he would find game more worthy of his arrows
or his axe. And so he was not surprised, even if his heart did give an
extra bound, when presently he came upon the track of a lynx. It was
a fresh track, too, and the footprints were those of a very big lynx.
“Weewah knew all this the moment he looked at the tracks, just as
he knew a thousand other things that he had learned in the school of
observation. He knew also that in all probability the animal was not
half a mile away, possibly waiting in some tree, or crouching in some
bushes looking for ptarmigan or rabbit. He was sure, also, that he
could run faster on his snow-shoes than the lynx could in that deep
soft snow.
“So for several minutes he stood and thought as fast as he could.
What a grand day for him it would be if he could come back to the
village dragging a great lynx after him! No one would ever tell him
again that he was too small to be a hunter.
“But while he was sorely tempted to rush after the animal with the
possibility of getting a shot, or a chance for a blow of his axe, he
knew that this was not the surest way to get his prey. He had
discovered the hunting ground of the big cat, and he knew that there
was no danger of its leaving the neighborhood so long as the supply
of rabbits held out. By taking a little more time, then, Weewah knew
he could surely bring the fellow into camp. And so he curbed his
eagerness.
“Instead of rushing off along the trail, bow bent and arrow on the
string, he opened his pouch and took out a stout buckskin string—a
string strong enough to resist the pull of the largest lynx. In one end
of this he made a noose with a running knot. Next he cut a stout stick
three inches thick and as tall as himself. Then he walked along the
trail of the lynx for a little distance, looking sharply on either side,
until he found a low-hanging, thick bunch of spruce boughs near
which the animal had passed. Here the boy stopped and cut two
more strong sticks, driving them into the ground about two feet apart,
so that they stood three feet above the snow and right in front of a
low-hanging bunch of spruce boughs.
“At the top of each he had left a crotch, across which he now laid
his stick with the looped string dangling from the center. The
contrivance when completed looked like a great figure H, from the
cross-bar of which hung the loop just touching the top of the snow.
“Now Weewah carefully opened the loop of the noose until it was
large enough for the head of any lynx to pass through, and fastened
it deftly with twigs and blades of dead grass, so as to hold it in place
firmly. From its front the thing looked like a miniature gallows—
which, indeed, it was.
“Next Weewah took the rabbit from his pouch, and creeping under
the thicket carefully so as not to disturb his looped string, he placed
the still warm body an arm’s length behind the loop, propping the
head of the little animal up with twigs, to look as lifelike as possible.
In an hour, at most, the rabbit would freeze and stiffen, and would
then look exactly like a live rabbit crouching in the bushes.
“Then the little Indian broke off branches, thrusting them into the
snow about the rabbit, until he had formed a little bower facing the
snare. Any animal attempting to seize it would thrust its own head
right through the fatal hangman’s loop.
“When Weewah had finished this task he gathered up his
tomahawk and bow and arrows, and started back along his own trail.
He made no attempt to cover up the traces of his work, as he would
if trapping a fox; for the lynx is a stupid creature, like all of his
cousins of the cat family, and will blunder into a trap of almost any
kind.
“The little Indian hurried along until he reached the point from
which he had first crossed the lynx tracks. Here he turned sharply,
starting a great circle, which would be about a mile in diameter. He
did this to make sure that the lynx had not gone on farther than he
thought. If he found no sign of fresh tracks he could feel certain that
the animal was still close at hand.
“This took him several hours, and it was almost dark when he
pulled back the flap and entered his home lodge in the village. He
was tired, too, but his eyes shone with suppressed emotion.
“As soon as he entered his mother set before him a smoking bowl
of broth without a word of comment or a question as to what his luck
might have been in his rabbit hunting. His father was there, gorging
himself on fat beaver meat that he had just brought in; but neither
he, nor Weewah’s brothers and sisters, offered any comment at the
little boy’s entrance.
“It is not correct etiquette, in Algonquin families, to ask the hunter
what luck he has had until he has eaten. Even then a verbal question
is not asked. But when the repast is finished the Indian woman takes
a pouch of the hunter and turns its contents out upon the floor.
“The emptiness of Weewah’s pouch spoke for itself, for he had
flung it upon the floor on entering, where it lay flat. His father
scowled a little when he noticed it; for he wanted his son to be a
credit to him as a hunter. But his scowl turned into a merry twinkle
when he saw how radiant his son’s face was despite his ill luck, and
what a small, delicately formed little fellow he was. Besides the old
warrior was in an unusually good humor. Had he not killed a fat
beaver that day? And was not beaver tail the choicest of all foods?
“In a few hours Weewah’s brothers and sisters, rolled in their
warm Hudson Bay blankets, were breathing heavily, and his father
and mother were far away in dreamland. Weewah was in dreamland,
too; but not the land that comes with sleep. He was in the happy
state of eager expectation that comes when to-morrow is to be a
great day in one’s life. And so he lay, snugly wrapped in his blanket,
his black eyes shining as he watched the embers of the fire in the
center of the tepee slowly grow dim and smoulder away. Meanwhile
the very thing he was dreaming about was happening out in the dark
spruce swamp.
“The great lynx, whose tracks Weewah had seen, started out just
at dusk on his nightly rabbit and grouse hunt. He had spent the day
curled up under the protecting boughs of a drooping spruce almost
within sound of Weewah’s hatchet where the snare was being set.
Now he took his way leisurely along his former trail, sniffing the air,
and examining every likely looking nook that might hide the material
for his supper. His great, fur-padded feet gave out no sound as he
glided along over the now frozen crust, and he was the embodiment
of stealth as he glided forward with ears erect, and stubby tail
straight out.
“Suddenly he stopped, raised his head and distended his nostrils,
drinking in the familiar odor wafted to him from some point near at
hand. Then he dropped low, his long fur dragging noiselessly on the
snow crust, as he wormed snake-like along toward a clump of low-
hanging spruces. His keen, yellow eyes had caught sight of the
crouching rabbit held in place at first by the twigs that Weewah had
placed there, but now stiff and rigid as iron.
“Closer and closer crept the lynx, until he was within six feet of his
victim. And still the rabbit did not move. The great body, quivering
with suppressed energy, now slowly lowered itself and the hind legs
were carefully drawn under for the spring. Then like a flash the gray
body shot forward and with a snarl the dagger-like teeth closed upon
the bunch of fur.
“At the same time the lynx felt a violent tug at his throat, and a
heavy club dealt him a sharp blow across the back as it fell from
overhead. In amazement the great brute dropped the rabbit,
springing violently backward as he did so. But the leather thong
about his neck and the club attached to it followed him in the spring,
the noose tightening about his neck.
“With a scream of rage he pulled violently to free himself, bracing
with his great fore feet against the club as he did so. But instead of
freeing himself he felt a quick tightening of the noose at his throat.
Frantic with rage and fright he continued to jerk and pull, sometimes
changing his attack to viciously biting the stick. But the only effect
produced was to gradually tighten the noose, which was now tangled
with the thick throat hair, and did not relax.
“Time and again he returned furiously to the attack, bracing his
feet against the stick, and pulling with all his strength. Inevitably he
would have choked himself to death, as Weewah had planned he
should, but for the fact that the little Indian had made the loop a little
too long, so that the pulling produced a violent but not fatal choking.
Many a lynx commits suicide in this way just as the trapper plans it.
“For hours the lynx wrestled vainly to free itself, varying the
attacks on the club by trying to run away from it. But running away
from it was quite as much out of the question as tearing it loose. For
when the animal attempted to run the club was jerked about its
limbs, tripping it, and frequently becoming entangled in brush and
bushes. At last, exhausted, and thoroughly sulky, the great cat
laboriously climbed a tree, and extended itself along one of the lower
limbs, the club still dangling at one side from its neck. In all its
struggles it had not gone more than two hundred yards from where
the trap had been set.
“An hour before daylight the next morning, Weewah, who had
been waiting for the first indications of morning, stole silently out of
the tepee without awakening even the light-sleeping members of his
family. He carried with him his own tomahawk, and his bow and
arrow; but also he carried the heavy axe that his mother used for
cutting the wood for the fire. She would miss it, he knew, and also he
knew that he would be in for a solid whack from the first stick that lay
handy when he returned; but he was willing to brave all this. The axe
must be had at any cost.
“The sun was just pushing its blood red rim above the low hills in
the east when he reached the edge of the spruce swamp. And it was
still only an oval, fire red ball when the little Indian approached the
place where he had set the snare the day before. He had swung
along lightly and swiftly over the beginning of the trail, but now as he
approached the goal his heart beat hard against his chest, just as
any white boy’s would have done under the circumstances. But long
before he actually reached the spot where the trap had been left he
knew that he had been successful. Successful, at least, in having
lured the prey into his snare.
“He could tell this by the condition of the snow, which had been
dug up and thrown about by the wild struggle of the lynx. He
loosened his tomahawk, therefore, held his arrow in readiness on the
string, and approached the scene of turmoil.
“One glance at the trampled snow, the dead rabbit still lying where
the lynx had dropped it, and the broad twisting trail leading further
into the swamp, told him the story of what had taken place more
completely than any white man could write it. And almost without
pausing he began following this trail cautiously forward, his arrow still
poised; for one never knows what a captive animal may do when
driven to desperation.
“Suddenly the little Indian stopped, his eyes snapping as he drew
the arrow to the head with every ounce of strength in his arms and
back. There, crouching on an upper limb of a tree perhaps a foot in
diameter, was the huge lynx, watching him with curling lips,
crouching ready to spring.
“Weewah’s first impulse was to send the finishing shaft through
the great body on the limb. It would be a great triumph for Weewah
—the little Indian boy, too small yet to be a hunter—to drag into his
father’s tepee early that morning a great forest cat killed with his own
bow and arrow. But after all, would a really great hunter feel much
pride in killing a captive lynx from a safe distance with an arrow?
“He knew very well that doing such a thing would not mark him as
a great hunter. And he was determined that he should be called a
great hunter before he was a day older.
“So he lowered his arrow, removed it from the string, and laid the
bow down beside the tree. He loosened his own tomahawk, also,
and laid that close at hand near the tree trunk. Then he seized the
big axe of his mother that he had brought with him and began
chopping at the trunk, making the chips fly rapidly under his skillful
aim.
“At the first blow of the axe against the trunk the lynx had half
risen, giving a fierce growl of rage. For a moment it hesitated, ready
to spring on the boy. But that moment of hesitancy was decisive. And
as the strokes of the axe continued uninterruptedly the great animal
gradually settled down sulkily on the branch, cowed by its fruitless
battle with the cord and stick.
“Meanwhile Weewah was swinging his axe to good purpose. Nor
was he directing his blows in a haphazard manner. With practiced
eye he had selected a clear spot where he wished the tree to fall,
and now by cutting half way through the trunk on the side facing in
that direction, and then cutting on exactly the opposite side a little
higher up he knew that the tree would fall precisely as he wished.
“Presently the tree began to waver slightly. It was sufficient,
however, to make the great cat on the bough crouch and whine with
fright. A few more sharp blows of the axe made the top limbs tremble
ominously. A puff of wind now would have toppled it over; but there
was not a breath of air stirring. Another axe stroke or two and it
would bring it to the ground.
“But before delivering the finishing strokes Weewah paused long
enough to replace his snow-shoes which he had removed before he
began chopping. He also picked up his tomahawk and thrust it half
way into his belt, where he could seize it instantly. Then he took the
axe and gave three vigorous, carefully directed finishing blows.
“And still the lynx did not leap. When the creature felt the limb
quivering beneath it, it rose as if to jump; then, confused and
uncertain, it crouched low again, clinging tightly to the branch as if
for protection. Just before the limb reached the ground, however, it
sprang far out into the snow, making violent leaps with the club
whirling about it, and quickly becoming entangled.
“Weewah, with tomahawk raised, was close upon its heels.
Another stride and he would have buried the blade in the animal’s
skull. But at that moment the lynx wheeled suddenly, dodging the
blow aimed at its head, and sprang toward its pursuer. Its great
claws as it struck at him cat fashion, scratched Weewah’s cheek,
and cut two deep grooves in his shoulder. It was a blow that would
have been disastrous had not the entangled club jerked the animal
to one side.
“With a yell the little Indian sprang toward the crouching, snarling
animal, thrusting out his right snow-shoe as he did so. Instantly the
frame and lacings of the shoe were crushed in the savage jaws of
the lynx. But at the same moment the tomahawk blade flashed
through the air and buried itself deep in the thick skull.
“Without a sound the great fur-covered body relaxed, quivered,
and then lay still with the teeth still buried in the snow-shoe frame
only an inch from Weewah’s foot.
“The little Indian stood for a few moments looking at his victim.
Then he reached down and tried to pry loose the fixed jaws. It was
no easy task. For the muscles had set in the last convulsive death
grip and it was only with the aid of his tomahawk blade that they
could finally be relaxed.
“Weewah now lashed the forepaws to the dead animal’s lower jaw
to prevent them from catching against things as he dragged the body
over the snow. Then he unfastened the strap from the club, and
taking the line over his shoulder started for home, scuffing along as
best he could on his broken snow-shoe, towing the big cat after him.
“All that morning Weewah’s mother had scolded about the missing
axe. Weewah was missing too, but she felt no solicitude about that.
With the axe it was different: people who took away axes were not
always particular about returning them, whereas boys always came
back. It hadn’t occurred to her that the boy and the axe had gone
away together.
“She had grumblingly gathered wood for the fire without the aid of
her usual implement, and now was busily engaged in boiling roots
and meat in a great pot, while her husband smoked his pipe, paying
no attention to his spouse’s complaints. Some of the smaller children
were playing noisy games, running in and out of the tepee, shouting
and laughing like a pack of white school children.
“Presently one of Weewah’s younger sisters, squatted on a stump,
raised a shrill cry, ‘Weewah, Weewah is coming!’
“The playing stopped at once, the children gathering in front of the
tepee to gaze in mute astonishment at their older brother. Tired as
he was from dragging the load, and leg weary from stumbling along
with his broken snow-shoe, he now held his head erect and his chin
high. Without a word he strode into the open flap of the tepee,
dragging the dead lynx after him. In front of his father he stopped
and dropped his burden; then he drew the blood-stained tomahawk
from his belt and laid it beside the dead animal, and stood silently
before his parent with folded arms.
“For several minutes the warrior smoked his pipe in silence. Then
he gave a grunt of satisfaction, laid his pipe aside, and ran his hand
deliberately over the body of the dead animal. He found no arrow
holes. Next he turned the great head and examined the clean
wound, and then the blood-stained blade of the tomahawk, and the
tightened cord of buckskin about the neck.
“His examination told him the story of what had happened out
there in the woods. He knew that Weewah had first caught the lynx
in his snare, and then had killed it with a blow from his tomahawk
instead of shooting it with an arrow. And he was proud of his son.
But no one but an Indian would have known it.
“With another grunt of satisfaction, however, he drew his hunting
knife from the sheath in his belt. By a few deft strokes he severed
two toes from the forepaw of the lynx, with the long curved claws
protruding, leaving a strip of fur at the back. Then he quickly
fashioned a loop in the skin so that the claws hung as a pendant
from it. When this was finished to his satisfaction he stood up and
beckoned to the boy; and when Weewah stepped forward the old
Indian placed the fur string about his neck with the lynx claws
suspended in front.
“Then he placed his hands on the little fellow’s shoulders and
looked sharply into his eyes, the little Indian returning the gaze with
quiet dignity.
“‘Weewah, the mighty hunter,’ the old Indian said slowly.
“Then he seated himself and resumed his pipe as if nothing had
happened.”
Martin knocked the ashes out of his pipe and threw an extra
chunk of wood on the fire.
“Time we were turning in,” he said.
“But tell me,” Larry asked; “did Weewah’s mother give him the
beating for taking her axe?”
“What, beat a mighty hunter like Weewah?” Martin asked in
feigned surprise. “No indeed! No more beatings for him. From that
day on no woman, not even his mother, would ever give him a blow.
And his father would now take him with him on his hunting trips,
even into the most dangerous places, just as he would any other
hunter. For he had proved his title, you see.”
Then the old man took his pipe from his lips, and said to the boy
earnestly:
“You see I am the old Indian and you are Weewah in this case.
Only you haven’t had a chance to kill your lynx yet. But we are going
right into that country where the lynx lives, and sooner or later you’ll
have a chance to show your metal. When that time comes remember
the story of little Weewah.
“And now you must turn in for the night.”
CHAPTER VI
FINAL PREPARATIONS
Sometime in the middle of the night Larry was awakened by flakes
of snow driven into his face, and by the sound of the storm howling
around the tent. The flakes sputtered in the fire which still flared and
struggled to keep burning. The boy was warm and comfortable in the
fur bag, however, and after pulling the flap over his head to keep out
the snow, he was soon sleeping soundly. When he opened his eyes
again it was daylight, and Martin was plodding about in the storm,
building a fire close to the tent where the wind struck it least. The
snow was still falling and was even then a foot deep on the level.
The old hunter was in high spirits: he had been hoping for the
storm, and the fact that it was a roaring blizzard made no difference
to him so long as the snow kept falling.
The inside of the tent was warm and the boy crawled out of the fur
bag reluctantly and reached for his shoes.
“Not that pair,” old Martin said; “there are your things over at the
foot of your bed. No more city clothes from now on. I nearly worked
my fingers off last night getting things ready for you.”
Larry wondered how much time the old hunter had found for sleep
when he examined the pile of clothing the hunter had laid out for
him. For most of the pieces had been altered in some way to make
them so that the boy could wear them, cut down from some of the
larger garments from the hunting outfit. Sleeves and trouser-legs had
been cut off or turned up, and buttons set over to take up the slack of
the bagging jacket in a way that showed how handy the old hunter
was with the needle. His most laborious task had been in reducing
the size of a pair of moose-skin moccasins, although he had
simplified this operation by taking in the back seam. At that they
were at least three sizes too large, as Larry pointed out.
“But when you have on two, or three, or four pairs of thick German
socks,” Martin assured him, “you won’t notice a little thing like that.
And you’ll fill out the rest of the clothes with underwear the same
way.”
Beside the pile of clothing Martin had placed some other things
which he told the boy were to be his personal belongings that were
to be carried with him all the time except when he slept. But the
hunter told him not to put them away until after they had had
breakfast, and made things a little more secure about the tent. So
Larry left the things as he found them, and went to help Martin.
He soon discovered the difference between his new clothes and
the “city” ones he had discarded. Even the fury of the blizzard could
not force the piercing cold through the thick, soft Mackinaw cloth;
and with the exception of the end of his nose, he was as warm as
toast as he worked under the hunter’s directions.
One side and the back of their tent was protected from the wind
by the wall of rock, and the fire checked the fury of the storm from
the front; but the snow drifted in on them from the unprotected side,
and they remedied this by stretching a piece of canvas across the
gap. It was no easy task, and several times the wind tore it away
before they could get it anchored securely, but when it was finally
made storm proof the enclosure before the roaring fire was almost
as warm and comfortable as a house.
“Now for your equipment,” Martin announced, when everything
was secured to his complete satisfaction.
Larry found that a light hunting hatchet and a stout hunting knife
had been added to his belt of cartridges, suspended in leather
sheaths from loops slipped over the belt. The belt itself was passed
through the loops in the jacket, so that the weight came upon his
shoulders instead of his waist, and when buckled, drew the coat
snugly around him. The gun in its sheath was slung over his
shoulder and hung at his left side. His fur mittens were fastened with
leather strings to the coat sleeves so that there was no possibility of
losing them even when slipped off.
There was a pocket compass in a hunting case about the size of a
watch which fitted into an upper pocket of his jacket which had a
button flap for holding it. As an additional precaution against losing it
a leather string reached from the inside of the pocket and was
fastened to the ring. And Larry found that his watch was secured in
his watch-pocket in a similar manner.
“We can’t take a chance on losing anything,” the hunter explained;
“for there are no jewelry stores along the road that we are going to
travel.”
Larry found that there were three water-proof match boxes to be
distributed in his trousers’ pockets, and a pocket knife that combined
several kinds of useful tools. The matches seemed to be the ordinary
parlor kind. But Martin surprised him by taking one, dipping it in a
cup of water, and then after wiping it off, lighting it like an ordinary
dry match. Even after a match had been floating in the water for
several minutes it would light and burn readily.
“They’ve all been dipped in shellac,” Martin explained. “The
shellac forms a water-proof coating that keeps out moisture but
doesn’t interfere with lighting or burning. So even if your match safe
leaks you won’t have to go without a fire.”
In one box which Larry thought contained matches he found six
little cubes looking like wax run into little square aluminum cups.
Martin explained their use by a simple demonstration. He placed one
of them on the ground where he had scraped away the snow, laid a
handful of sticks over it, struck a match and touched the wax-like
substance. It burst into a bright flame at once, and continued to burn
fiercely for several minutes, igniting the sticks about it and helping to
keep their struggling flames going until enough heat had been
generated to make a steady fire.
“That’s a new fangled thing called ‘solid alcohol,’ used to start a
tenderfoot’s fire when he is wet and cold and has no little dry twigs at
hand,” said Martin. “An old woodsmen like me ought to throw the
stuff away and scorn to use it; and forty years ago I would have done
so. But I am wiser now, I hope, and I don’t despise some of the new
things as I did then. And I remember two different occasions when I
came near losing my life in the snow because my hands were so
cold and numb, and the small wood was so scarce, that I came near
not getting my fire started at all. So now I am going to take along a
few packages of these cubes, and you must do the same. We’ll
never use it except as a last resort; but sometime it may come in
handy for starting a fire or boiling a cup of tea.
“You know we will only use two matches a day after we leave here
—one match to start our fire at noon and at night. There will be coals
from the night next morning to cook our breakfast by. It’s a mark of
bad woodsmanship to have to use more than one match to start a
fire, no matter what kind of weather is going.”
“But how about your pipe?” Larry asked. For the old man smoked
almost continually during his waking hours.
Old Martin sighed and shook his head. “No more pipe for me after
we leave here,” he said, with a little laugh. “The weight in pemmican
that I’ll take instead of the tobacco may be just the amount that will
decide the question of our getting through alive. Smoking isn’t a
necessity, but eating is.”
Larry looked at the old man to see if he were not joking; but he
saw that he was thoroughly in earnest. It made the boy realize the
serious nature of the task before them to know that the old man was
going to sacrifice the greatest solace of his life. But it roused his
determination, and his spirits were too buoyant to be long
depressed.
All day long Martin kept him busy helping at various things that
must be completed before their departure. The toboggans were
hauled into the canvas enclosure, where he and the old man packed
and unpacked the loads, adding something here, or leaving out
something there, working in the glow of the warm fire. Dog
harnesses had to be altered and extra ones tucked away on the
sleds, snow-shoe lacings examined and re-lashed, and a dozen
things attended to that Larry recognized as important when Martin
pointed them out. The fire, too, needed considerable tending to keep
a huge kettle of beans cooking which Martin declared must simmer
all day if they were to be cooked properly.
Toward night the wind subsided, and the clouds cleared away, so
that by the time they had finished their heaping plates of pork and
beans the stars were out glistening like steel points in the frosty air.
Later in the evening they heard howling in the distance—terrifying
sounds to the boy, made by a pack of big timber wolves out on a
hunt, as Martin explained. And for fear the dogs might start an
independent wolf hunt on their own account, Martin tied up the big
malamoots after he had fed them.
During the day Martin had brought several armfuls of packages
into the tent from the stores under the tarpaulin as he went back and
forth at his work. Now that supper was over and the dishes cleaned
he lighted his pipe and and seated himself beside the packages. He
was always talkative when working by the evening fire, and seemed
to find great pleasure in imparting bits of information to the boy from
his inexhaustible store of woodland experiences.
To-night as he began fumbling among the packages, he asked:
“Larry, have you decided what you are going to carry in your ditty
bag?”
“Ditty bag?” Larry repeated; “I’d know better what I was going to
carry in it if I knew what a ‘ditty bag’ was.”
“What, a veteran forest pilot like you not know what a ditty bag is!”
Martin asked in mock astonishment. “Then it’s high time for you to
learn. A ditty bag is the thing that does for the woodsman what all
the pockets in a suit of clothes do for a boy—it carries the forty and
one indispensable things that can’t be carried in some other place.
You’d better sit over here beside me and make yours up to-night
while I am fitting out mine.”
So the boy moved over to the little pile of packages ready for
instructions.
The hunter handed him a little bag made of tough water-proof
material with a string at the top for tying securely. Then he
rummaged through the packages, taking out what he wanted and
placing them in the bag. At his suggestion Larry duplicated this
selection of things for his own bag, so that in case one bag should
be lost they would still have the other. “But,” said Martin, “you must
put in some little thing for luck—anything that strikes your fancy, after
the other things are in. That’s a hunter’s superstition, like the Indian’s
‘medicine.’”
The first useful article selected was a neat Red Cross package
containing a few useful medicines and surgical dressings for an
emergency. Next came needles of all sizes, with several skeins of
thread, and a wooden handle in which were several awls, neatly
stored in a hollow bobbin on which was wound many lengths of
strong waxed cord. A can of gunoil found a place, and a small
whetstone, rough on one side for sharpening the axes, and smooth
on the other for the knives. A tool case, containing a “good-sized
carpenter shop,” as Martin explained and made of aluminum after
Mr. Ware’s own design, found especial favor; and a broken shell
extractor was considered indispensable.
Buttons and skeins of twine of various sizes went into the bag as
a matter of course; but when the old hunter selected three packages,
each containing a dozen yards of the kind of twisted wire used for
hanging pictures of different sizes, the boy burst out laughing and
rolled on the blankets. He suspected Martin of trying to play off a
quiet hoax on him, and did not intend to be caught in the trap.
Nothing was farther from Martin’s thoughts, however, as Larry
discovered when the use of the wire was explained. It was to be
used for making the snares for catching small animals, particularly
rabbits, the hunter said, and for that purpose was unequaled. And
the old man assured him that for securing food on the march in a
snow-bound country snares were far more useful than rifles. Indian
families in many northern regions depended almost entirely upon
their snares for their supply of winter food.
“Rabbits are the bread and butter of the woodsman in the winter,”
Martin said. “The rabbits make little narrow paths in the snow—
thousands of them, running in all directions—and when they are not
disturbed and going about their business, they always follow these
paths. Now when the rabbit comes to a fallen limb lying across his
path a few inches above the ground, he likes to go under the limb
rather than hop over it. This simplifies matters for the Indian. He
simply hangs his snare in front of the hole under the limb, and is
almost sure to catch the first rabbit that comes hopping along that
particular path.
“The snare is just a simple slip-noose made large enough to let
the rabbit’s head pass through easily. If the wind is blowing the snare
can be held open and in place by tying it with blades of dead grass,
which are strong enough to hold it in place until the rabbit gets his
head through.
“The other end of the snare string is tied to a limb that is bent
down and fastened in a notch cut in a stick or a small sapling if it
happens to be in the right place. The notch is cut deep enough to
hold the bent limb, but not firmly enough but what it can be jerked
loose pretty easily.
“Now when the rabbit comes hopping along the path and starts to
go under the limb, he runs his head through the snare. When he
feels something around his neck he pulls back to get out of its way;
but that tightens the noose about his neck, and he begins leaping
about frantically to get loose. In this way he jerks the bent limb out of
the notch that holds it down, the limb flies back, and swings him up
into the air where he smothers in short order.
“Of course if the snare was simply fastened to the limb over the
path the rabbit would choke himself to death for a certainty, because
he never stops pulling and tugging at the noose while he has a kick
left in him. But then some fox or weasel would probably come along
and get him. But neither of them will get him if he is dangling in the
air: the weasel can’t reach him, and the fox is such a crafty fellow,
always looking out for traps and tricks, that he won’t go near a dead
rabbit hanging on a string, even if he is starving.
“Now that the snow has stopped falling the rabbits will be out to-
night making paths, and to-morrow night we’ll put out some snares
just for practice. I’ll teach you a dozen ways to make snares for
different kinds of game, but the principle of all of them is the same as
the one for catching Mr. Rabbit. And he’s the boy we’re interested in
mostly.”
The old hunter rose and went out to “have a look at the snow,” as
he put it. He came back well pleased with his inspection.
“The crust will form and set hard to-night,” he said to Larry, “and
to-morrow you’ll begin your hardest and most important lesson—
learning to walk on snow-shoes. You can look forward to taking
some of the grandest headers you have ever taken in your life,” he
added, grinning.
“But—” Larry began, and then stopped.
“‘But’ what?” Martin asked.
“Oh, nothing,” Larry answered evasively. “I was just thinking of
those headers that I am going to take to-morrow, that’s all.”
“Well, go to bed and dream about them then,” the old hunter
instructed.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like