Instant download Programming elixir 1 6 1st edition dave thomas pdf all chapter

Page 1


Programming Elixir 1 6 1st Edition Dave Thomas

Visit to download the full and correct content document: https://textbookfull.com/product/programming-elixir-1-6-1st-edition-dave-thomas/

More products digital (pdf, epub, mobi) instant download maybe you interests ...

Programming in ELIXIR language 4444th Edition Muhammad Allah Rakha

https://textbookfull.com/product/programming-in-elixirlanguage-4444th-edition-muhammad-allah-rakha/

Introducing Elixir Getting Started in Functional Programming 2nd Edition Simon St. Laurent

https://textbookfull.com/product/introducing-elixir-gettingstarted-in-functional-programming-2nd-edition-simon-st-laurent/

Programming Ecto Build database apps in Elixir for scalability and performance Darin Wilson

https://textbookfull.com/product/programming-ecto-build-databaseapps-in-elixir-for-scalability-and-performance-darin-wilson/ Business Process Management Forum: BPM Forum 2019, Vienna, Austria, September 1–6, 2019, Proceedings Thomas Hildebrandt

https://textbookfull.com/product/business-process-managementforum-bpm-forum-2019-vienna-austriaseptember-1-6-2019-proceedings-thomas-hildebrandt/

Business Process Management: 17th International Conference, BPM 2019, Vienna, Austria, September 1–6, 2019, Proceedings Thomas Hildebrandt

https://textbookfull.com/product/business-processmanagement-17th-international-conference-bpm-2019-vienna-austriaseptember-1-6-2019-proceedings-thomas-hildebrandt/

Testing Elixir Effective and Robust Testing for Elixir and its Ecosystem 1st Edition Andrea Leopardi Jeffrey Matthias

https://textbookfull.com/product/testing-elixir-effective-androbust-testing-for-elixir-and-its-ecosystem-1st-edition-andrealeopardi-jeffrey-matthias/

Testing Elixir Andrea Leopardi

https://textbookfull.com/product/testing-elixir-andrea-leopardi/

Functional Programming in R: Advanced Statistical Programming for Data Science, Analysis and Finance 1st Edition Thomas Mailund

https://textbookfull.com/product/functional-programming-in-radvanced-statistical-programming-for-data-science-analysis-andfinance-1st-edition-thomas-mailund/

SELL

6: Trust-Based Professional Selling 6th Edition Thomas N. Ingram

https://textbookfull.com/product/sell-6-trust-based-professionalselling-6th-edition-thomas-n-ingram/

Programming Elixir ≥ 1.6

FUNCTIONAL |> CONCURRENT |> PRAGMATIC |> FUN

Version: P1 0 (May 2018)

Copyright © 2018 The Pragmatic Programmers, LLC. This book is licensed to the individual who purchased it. We don't copy-protect it because that would limit your ability to use it for your own purposes. Please don't break this trust you can use this across all of your devices but please do not share this copy with other members of your team, with friends, or via file sharing services. Thanks.

Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and The Pragmatic Programmers, LLC was aware of a trademark claim, the designations have been printed in initial capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer, Pragmatic Programming, Pragmatic Bookshelf and the linking g device are trademarks of The Pragmatic Programmers, LLC.

Every precaution was taken in the preparation of this book. However, the publisher assumes no responsibility for errors or omissions, or for damages that may result from the use of information (including program listings) contained herein.

About the Pragmatic Bookshelf

The Pragmatic Bookshelf is an agile publishing company. We’re here because we want to improve the lives of developers. We do this by creating

timely, practical titles, written by programmers for programmers.

Our Pragmatic courses, workshops, and other products can help you and your team create better software and have more fun. For more information, as well as the latest Pragmatic titles, please visit us at http://pragprog.com.

Our ebooks do not contain any Digital Restrictions Management, and have always been DRM-free. We pioneered the beta book concept, where you can purchase and read a book while it’s still being written, and provide feedback to the author to help make a better book for everyone. Free resources for all purchasers include source code downloads (if applicable), errata and discussion forums, all available on the book's home page at pragprog.com. We’re here to make your life easier.

NEW BOOK ANNOUNCEMENTS

Want to keep up on our latest titles and announcements, and occasional special offers?

Just create an account on pragprog.com (an email address and a password is all it takes) and select the checkbox to receive newsletters. You can also follow us on twitter as @pragprog.

ABOUT EBOOK FORMATS

If you buy directly from pragprog.com, you get ebooks in all available formats for one price. You can synch your ebooks amongst all your devices (including iPhone/iPad, Android, laptops, etc.) via Dropbox. You get free updates for the life of the edition. And, of course, you can always come back

and re-download your books when needed. Ebooks bought from the Amazon Kindle store are subject to Amazon's polices. Limitations in Amazon's file format may cause ebooks to display differently on different devices. For more information, please see our FAQ at pragprog.com/frequently-askedquestions/ebooks. To learn more about this book and access the free resources, go to https://pragprog.com/book/elixir16, the book's homepage.

Thanks for your continued support,

Andy Hunt

The Pragmatic Programmers

The team that produced this book includes: Andy Hunt (Publisher), Janet Furlow (VP of Operations), Brian MacDonald (Managing Editor), Jacquelyn Carter (Supervising Editor), Candace Cunningham (Copy Editor), Potomac Indexing, LLC (Indexing), Gilson Graphics (Layout)

For customer support, please contact support@pragprog.com.

For international rights, please contact rights@pragprog.com.

Table of Contents

1 Foreword

2. A Vain Attempt at a Justification, Take Two

1. Acknowledgments

3 1. Take the Red Pill

1. Programming Should Be About Transforming Data

2 Installing Elixir

3. Running Elixir

4 Suggestions for Reading the Book

5. Exercises

6. Think Different(ly)

4 Part I. Conventional Programming

1. 2. Pattern Matching

1. Assignment: I Do Not Think It Means What You Think It Means.

2 More Complex Matches

3. Ignoring a Value with (Underscore)

4. Variables Bind Once (per Match)

5. Another Way of Looking at the Equals Sign

2. 3. Immutability

1 You Already Have (Some) Immutable Data

2. Immutable Data Is Known Data

3. Performance Implications of Immutability

4 Coding with Immutable Data

3. 4. Elixir Basics

1. Built-in Types

2 Value Types

3. System Types

4 Collection Types

5. Maps

6 Binaries

7. Dates and Times

8. Names, Source Files, Conventions, Operators, and So On

9. Variable Scope

10. End of the Basics

4 5. Anonymous Functions

1. Functions and Pattern Matching

2. One Function, Multiple Bodies

3. Functions Can Return Functions

4. Passing Functions as Arguments

5. Functions Are the Core

5. 6. Modules and Named Functions

1 Compiling a Module

2. The Function’s Body Is a Block

3. Function Calls and Pattern Matching

4. Guard Clauses

5. Default Parameters

6. Private Functions

7. The Amazing Pipe Operator: |>

8 Modules

9. Module Attributes

10 Module Names: Elixir, Erlang, and Atoms

11 Calling a Function in an Erlang Library

12. Finding Libraries

6. 7. Lists and Recursion

1 Heads and Tails

2. Using Head and Tail to Process a List

3 Using Head and Tail to Build a List

4. Creating a Map Function

5 Reducing a List to a Single Value

6. More Complex List Patterns

7. The List Module in Action

8. Get Friendly with Lists

7. 8. Maps, Keyword Lists, Sets, and Structs

1 How to Choose Between Maps, Structs, and Keyword Lists

2. Keyword Lists

3. Maps

4. Pattern Matching and Updating Maps

5. Updating a Map

6. Structs

7. Nested Dictionary Structures

8. Sets

9. With Great Power Comes Great Temptation

8. 9. An Aside—What Are Types?

9 10. Processing Collections—Enum and Stream

1. Enum Processing Collections

2 Streams Lazy Enumerables

3. The Collectable Protocol

4 Comprehensions

5. Moving Past Divinity

10. 11. Strings and Binaries

1. String Literals

2. The Name “strings”

3 Single-Quoted Strings Lists of Character Codes

4. Binaries

5 Double-Quoted Strings Are Binaries

6. Binaries and Pattern Matching

7 Familiar Yet Strange

11 12. Control Flow

1. if and unless

2 cond

3. case

4 Raising Exceptions

5. Designing with Exceptions

6. Doing More with Less

12

13. Organizing a Project

1. The Project: Fetch Issues from GitHub

2 Step 1: Use Mix to Create Our New Project

3. Transformation: Parse the Command Line

4 Write Some Basic Tests

5. Refactor: Big Function Alert

6. Transformation: Fetch from GitHub

7. Step 2: Use Libraries

8. Transformation: Convert Response

9. Transformation: Sort Data

10. Transformation: Take First n Items

11 Transformation: Format the Table

12. Step 3: Make a Command-Line Executable

13 Step 4: Add Some Logging

14 Step 5: Create Project Documentation

15. Coding by Transforming Data

13. 14. Tooling

1 Debugging with IEx

2. Testing

3 Code Dependencies

4. Server Monitoring

5 Source-Code Formatting

6. Inevitably, There’s More 5.

Part II. Concurrent Programming

1. 15. Working with Multiple Processes

1 A Simple Process

2. Process Overhead

3. When Processes Die

4. Parallel Map The “Hello, World” of Erlang

5. A Fibonacci Server

6. Agents A Teaser

7. Thinking in Processes

2. 16. Nodes—The Key to Distributing Services

1. Naming Nodes

2. Naming Your Processes

3. Input, Output, PIDs, and Nodes

4. Nodes Are the Basis of Distribution

3 17. OTP: Servers

1. Some OTP Definitions

2. An OTP Server

3. GenServer Callbacks

4 Naming a Process

5. Tidying Up the Interface

6. Making Our Server into a Component

4 18. OTP: Supervisors

1. Supervisors and Workers

2 Worker Restart Options

3. Supervisors Are the Heart of Reliability

5. 19. A More Complex Example

1. Introduction to Duper

2. The Duper Application

3 But Does It Work?

4. Planning Your Elixir Application

5 Next Up

6. 20. OTP: Applications

1. This Is Not Your Father’s Application

2. The Application Specification File

3. Turning Our Sequence Program into an OTP Application

4 Supervision Is the Basis of Reliability

5. Releasing Your Code

6 Distillery The Elixir Release Manager

7. OTP Is Big Unbelievably Big

7. 21. Tasks and Agents

1 Tasks

2. Agents

3 A Bigger Example

4. Agents and Tasks, or GenServer?

Part III. More Advanced Elixir

1. 22. Macros and Code Evaluation

1. Implementing an if Statement

2. Macros Inject Code

3 Using the Representation as Code

4. Using Bindings to Inject Values

5 Macros Are Hygienic

6. Other Ways to Run Code Fragments

7 Macros and Operators

8. Digging Deeper

9. Digging Ridiculously Deep

2 23. Linking Modules: Behavio(u)rs and use

1. Behaviours

2 use and using

3. Putting It Together Tracing Method Calls

4. Use use

3 24. Protocols—Polymorphic Functions

1. Defining a Protocol

2 Implementing a Protocol

3. The Available Types

4 Protocols and Structs

5. Built-in Protocols

6. Protocols Are Polymorphism

4 25. More Cool Stuff

1. Writing Your Own Sigils

2 Multi-app Umbrella Projects

3. But Wait! There’s More!

7. A1. Exceptions: raise and try, catch and throw

1. Raising an Exception

2 catch, exit, and throw

3. Defining Your Own Exceptions

4. Now Ignore This Appendix

8 A2. Type Specifications and Type Checking

1. When Specifications Are Used

2 Specifying a Type

3. Defining New Types

4 Specs for Functions and Callbacks

5. Using Dialyzer

9. Bibliography

Foreword

I have always been fascinated with how changes in hardware affect how we write software.

A couple of decades ago, memory was a very limited resource. It made sense back then for our software to take hold of some piece of memory and mutate it as necessary. However, allocating this memory and cleaning up after we no longer needed it was a very error-prone task. Some memory was never freed; sometimes memory was allocated over another structure, leading to faults. At the time, garbage collection was a known technique, but we needed faster CPUs in order to use it in our daily software and free ourselves from manual memory management. That has happened most of our languages are now garbage-collected.

Today, a similar phenomenon is happening. Our CPUs are not getting any faster. Instead, our computers get more and more cores. This means new software needs to use as many cores as it can if it is to maximize its use of the machine. This conflicts directly with how we currently write software.

In fact, mutating our memory state actually slows down our software when many cores are involved. If you have four cores trying to access and manipulate the same piece of memory, they can trip over each other. This potentially corrupts memory unless some kind of synchronization is applied.

I quickly learned that applying this synchronization is manual, error prone, and tiresome, and it hurts performance. I suddenly realized that’s not how I wanted to spend time writing software in the next years of my career, and I set out to study new languages and technologies.

It was on this quest that I fell in love with the Erlang virtual machine and ecosystem.

In the Erlang VM, all code runs in tiny concurrent processes, each with its own state. Processes talk to each other via messages. And since all communication happens by messagepassing, exchanging messages between different machines on the same network is handled transparently by the VM, making it a perfect environment for building distributed software!

However, I felt there was still a gap in the Erlang ecosystem. I missed first-class support for some of the features I find necessary in my daily work things such as metaprogramming, polymorphism, and first-class tooling. From this need, Elixir was born.

Elixir is a pragmatic approach to functional programming. It values its functional foundations and it focuses on developer productivity. Concurrency is the backbone of Elixir software. As garbage collection once freed developers from the shackles of memory management, Elixir is here to free you from antiquated concurrency mechanisms and bring you joy when writing concurrent code.

A functional programming language lets us think in terms of functions that transform data. This transformation never mutates data. Instead, each application of a function potentially creates a new, fresh version of the data. This greatly reduces the need for data-synchronization mechanisms.

Elixir also empowers developers by providing macros. Elixir code is nothing more than data, and therefore can be manipulated via macros like any other value in the language.

Finally, object-oriented programmers will find many of the mechanisms they consider essential to writing good software, such as polymorphism, in Elixir.

All this is powered by the Erlang VM, a 20-year-old virtual machine built from scratch to support robust, concurrent, and distributed software. Elixir and the Erlang VM are going to change how you write software and make you ready to tackle the upcoming years in programming.

Tenczynek, Poland, October 2014

Copyright © 2018, The Pragmatic Bookshelf

A Vain Attempt at a Justification, Take Two

I’m a language nut. I love trying languages out, and I love thinking about their design and implementation. (I know; it’s sad.)

I came across Ruby in 1998 because I was an avid reader of comp.lang.misc (ask your parents). I downloaded it, compiled it, and fell in love. As with any time you fall in love, it’s difficult to explain why. It just worked the way I work, and it had enough depth to keep me interested.

Fast-forward 15 years. All that time I’d been looking for something new that gave me the same feeling.

I came across Elixir a while back, but for some reason never got sucked in. But a few months before starting on the first edition of this book, I was chatting with Corey Haines. I was bemoaning the fact that I wanted a way to show people functional programming concepts without the academic trappings those books seem to attract. He told me to look again at Elixir. I did, and I felt the same way I felt when I first saw Ruby.

So now I’m dangerous. I want other people to see just how great this is. I want to evangelize. So I write a book. But I don’t want to write another 900-page Pickaxe book. I want this book to be short and exciting. So I’m not going into all the detail, listing all the syntax, all the library functions, all the OTP options, or….

Instead, I want to give you an idea of the power and beauty of this programming model. I want to inspire you to get involved, and then point to the online resources that will fill in the gaps.

But mostly, I want you to have fun.

Fast-forward three years. Elixir has moved on. Phoenix, its connectivity framework, introduced a whole new set of developers to the joys of a functional approach. The Nerves project makes it easy to write embedded Elixir code on Linuxbased microcontrollers. The Elixir base has grown there are international, national, and regional conferences. Job ads ask for Elixir developers.

I’ve been moving on, too. But I’m still using Elixir daily. I just completed my second year as an adjunct professor at Southern Methodist University, corrupting the programmers of tomorrow with the temptations of Elixir. I’ve written an online Elixir course.

[1]

And now I’m revving this book. To be honest, I don’t really have to: Elixir 1.6 is not so different from 1.3 that the older book would not be useful. But my own thinking about Elixir has matured. I now do some things differently. And I’d like to share these things with you.

Acknowledgments

It seems to be a common thread the languages I fall in love with are created by people who are both clever and extremely nice. José Valim, the creator of Elixir, takes both of these adjectives to a new level. I owe him a massive thank-you for giving me so much fun over the last 18 months. Along with him, the whole Elixir core team has done an amazing job of cranking out an entire ecosystem that feels way more mature than its years. Thank you, all.

A conversation with Corey Haines reignited my interest in Elixir thank you, Corey, for good evenings, some interesting times in Bangalore, and the inspiration.

Bruce Tate is always an interesting sounding board, and his comments on early drafts of the book made a big difference. And I’ve been blessed with an incredible number of active and insightful beta readers who have made literally hundreds of suggestions for improvements. Thank you, all.

A big tip of the hat to Jessica Kerr, Anthony Eden, and Chad Fowler for letting me steal their tweets.

Kim Shrier seems to have been involved with my writing since before I started writing. Thanks, Kim, for another set of perceptive and detailed critiques.

Candace Cunningham again amazed me with her detailed copy editing: it’s rare to find someone who can correct both your grammar and your code. The crew at Potomac did their customary stellar job of indexing.

Dave Thomas

mailto:dave@pragdave.me Dallas, TX, April 2018

Footnotes https://codestool coding-gnome com

[1]

Copyright © 2018, The Pragmatic Bookshelf

Chapter 1

Take the Red Pill

The Elixir programming language wraps functional programming with immutable state and an actor-based approach to concurrency in a tidy, modern syntax. And it runs on the industrial-strength, high-performance, distributed Erlang VM. But what does all that mean?

It means you can stop worrying about many of the difficult things that currently consume your time. You no longer have to think too hard about protecting your data consistency in a multithreaded environment. You worry less about scaling your applications. And, most importantly, you can think about programming in a different way.

Programming Should Be About Transforming Data

If you come from an object-oriented world, then you are used to thinking in terms of classes and their instances. A class defines behavior, and objects hold state. Developers spend time coming up with intricate hierarchies of classes that try to model their problem, much as Victorian scientists created taxonomies of butterflies.

When we code with objects, we ’ re thinking about state. Much of our time is spent calling methods in objects and passing them other objects. Based on these calls, objects update their own state, and possibly the state of other objects. In this world, the class is king it defines what each instance can do, and it implicitly controls the state of the data its instances hold. Our goal is data-hiding.

But that’s not the real world. In the real world, we don’t want to model abstract hierarchies (because in reality there aren’t that many true hierarchies). We want to get things done, not maintain state.

Right now, for instance, I’m taking empty computer files and transforming them into files containing text. Soon I’ll transform those files into a format you can read. A web server somewhere will transform your request to download the book into an HTTP response containing the content.

I don’t want to hide data. I want to transform it.

COMBINE TRANSFORMATIONS WITH PIPELINES

Unix users are accustomed to the philosophy of small, focused command-line tools that can be combined in arbitrary ways. Each tool takes an input, transforms it, and writes the result in a format the next tool (or a human) can use.

This philosophy is incredibly flexible and leads to fantastic reuse. The Unix utilities can be combined in ways undreamed of by their authors. And each one multiplies the potential of the others.

It’s also highly reliable each small program does one thing well, which makes it easier to test.

There’s another benefit. A command pipeline can operate in parallel. If I write

$ grep Elixir *.pml | wc -l

the word-count program, wc, runs at the same time as the grep command. Because wc consumes grep ’ s output as it is produced, the answer is ready with virtually no delay once grep finishes.

Just to give you a taste of this, here’s an Elixir function called pmap. It takes a collection and a function, and returns the list that results from applying that function to each element of the collection. But…it runs a separate process to do the conversion of each element. Don’t worry about the details for now.

spawn/pmap1.exs

defmodule Parallel do def pmap(collection, func) do collection

|> Enum.map(&(Task.async(fn -> func.(&1) end)))

|> Enum.map(&Task.await/1) end end

We could run this function to get the squares of the numbers from 1 to 1,000.

result = Parallel pmap 1 1000, &(&1 * &1)

And, yes, I just kicked off 1,000 background processes, and I used all the cores and processors on my machine.

The code may not make much sense, but by about halfway through the book, you’ll be writing this kind of thing for yourself.

FUNCTIONS ARE DATA TRANSFORMERS

Elixir lets us solve the problem in the same way the Unix shell does. Rather than have command-line utilities, we have functions. And we can string them together as we please. The smaller more focused those functions, the more flexibility we have when combining them.

If we want, we can make these functions run in parallel Elixir has a simple but powerful mechanism for passing messages between them. And these are not your father’s boring old processes or threads we ’ re talking about the potential to run millions of them on a single machine and have hundreds of these machines interoperating. Bruce Tate commented on this paragraph with this thought: “Most programmers treat threads and processes as a necessary evil; Elixir developers feel they are an important simplification.” As we get deeper into the book, you’ll start to see what he means.

This idea of transformation lies at the heart of functional programming: a function transforms its inputs into its output. The trigonometric function sin is an example give it π/4, and you’ll get back 0.7071. An HTML templating system is a

function; it takes a template containing placeholders and a list of named values, and produces a completed HTML document.

But this power comes at a price. You’re going to have to unlearn a whole lot of what you know about programming. Many of your instincts will be wrong. And this will be frustrating, because you ’ re going to feel like a total n00b.

Personally, I feel that’s part of the fun. You didn’t learn, say, object-oriented programming overnight. You are unlikely to become a functional programming expert by breakfast, either.

But at some point things will click. You’ll start thinking about problems in a different way, and you’ll find yourself writing code that does amazing things with very little effort on your part. You’ll find yourself writing small chunks of code that can be used over and over, often in unexpected ways (just as wc and grep can be).

Your view of the world may even change a little as you stop thinking in terms of responsibilities and start thinking in terms of getting things done. And just about everyone can agree that will be fun.

Installing Elixir

This book assumes you ’ re using at least Elixir 1.6. The most upto-date instructions for installing Elixir are available at http://elixir-lang.org/install.html. Go install it now.

Running Elixir

In this book, I show a terminal session like this:

$ echo Hello, World Hello, World

The terminal prompt is the dollar sign, and the stuff you type follows. (On your system, the prompt will likely be different.) Output from the system is shown without highlighting.

IEX—INTERACTIVE ELIXIR

To test that your Elixir installation was successful, let’s start an interactive Elixir session. At your regular shell prompt, type iex.

$ iex

Erlang/OTP 20 [erts-9.1] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]h

Interactive Elixir (x.y.z) - press Ctrl+C to exit (type h() ENTER for h elp)

iex(1)>

(The various version numbers you see will likely be different I won’t bother to show them on subsequent examples.)

Once you have an IEx prompt, you can enter Elixir code and you’ll see the result. If you enter an expression that continues over more than one line, IEx will prompt for the additional lines with an ellipsis (…).

iex(1)> 3 + 4

7

iex(2)> String.reverse "madamimadam" "madamimadam"

iex(3)> 5 *

...(3)> 6

30

iex(4)>

The number in the prompt increments for each complete expression executed. I’ll omit the number in most of the examples that follow.

There are several ways of exiting from IEx none are tidy. The easiest two are typing Ctrl - C twice or typing Ctrl - G followed by q and Return . On some systems, you can also use a single Ctrl - \ .

IEx Helpers

IEx has a number of helper functions. Type h (followed by Return ) to get a list:

iex> h

IEx Helpers

Welcome to Interactive Elixir. You are currently seeing the documentation for the module IEx.Helpers which provides many helpers to make Elixir's shell more joyful to work with.

This message was triggered by invoking the helper h(), usually referred to as h/0 (since it expects 0 arguments).

You can use the h/1 function to invoke the documentation for any Elixir module or function:

iex> h(Enum)

iex> h(Enum.map)

iex> h(Enum.reverse/1)

You can also use the i/1 function to introspect any value you have in the shell:

iex> i("hello")

There are many other helpers available, here are some examples:

• b/1 - prints callbacks info and docs for a given module

• c/1 - compiles a file into the current directory

• c/2 - compiles a file to the given path

• cd/1 - changes the current directory

• clear/0 - clears the screen

• exports/1 - shows all exports (functions + macros) in a module

• flush/0 - flushes all messages sent to the shell

• h/0 - prints this help message

• h/1 - prints help for the given module, function or macro

• i/0 - prints information about the last value

• i/1 - prints information about the given term

• ls/0 - lists the contents of the current directory

• ls/1 - lists the contents of the specified directory

• open/1 - opens the source for the given module or function in your editor

• pid/1 - creates a PID from a string

• pid/3 - creates a PID with the 3 integer arguments passed

• ref/1 - creates a Reference from a string

• ref/4 - creates a Reference with the 4 integer arguments passed

• pwd/0 - prints the current working directory

• r/1 - recompiles the given module's source file

• recompile/0 - recompiles the current project

• runtime info/0 - prints runtime info (versions, memory usage, stats)

• v/0 - retrieves the last value from the history

• v/1 - retrieves the nth value from the history

Help for all of those functions can be consulted directly from the command line using the h/1 helper itself. Try:

iex> h(v/0)

To list all IEx helpers available, which is effectively all exports (functions and macros) in the IEx.Helpers module:

iex> exports(IEx.Helpers)

This module also includes helpers for debugging purposes, see IEx break!/4 for more information.

To learn more about IEx as a whole, type h(IEx).

In the list of helper functions, the number following the slash is the number of arguments the helper expects.

Probably the most useful is h itself. With an argument, it gives you help on Elixir modules or individual functions in a module. This works for any modules loaded into IEx (so when we talk

Another random document with no related content on Scribd:

1.

October 1, 1811. Cavalry.

General Total, including serjeants, 58263 sabres and bayonets in the field

January 8, 1812.—Cavalry.

General Total, including sergeants, 56239 sabres and bayonets in the field.

Note The abuses and desertions in the Portuguese cavalry had been so great that one division was suppressed

5, 1812.—Cavalry.

Note. The heavy German cavalry were in the rear at Estremos, and two Portuguese regiments were in Abrantes

Hamilton’s division 4685

Light division 858

Third division 976

Fourth division 2384

Fifth division 1845 10748

Total 21,784 , 1812.

Cavalry under general Hill Left Wing

British 783

Portuguese 347 1130

Infantry ditto.

British 6156 Portuguese 2385 8541 Total under general Hill 9671

Cavalry under general Graham Right Wing

British 3517 Portuguese 3517

Infantry ditto.

British 10154 Portuguese 5896 16050

Total under general Graham 19567

General Total of the covering army, exclusive of the artillerymen and the heavy German cavalry, who remained in the rear at

Estremos, 29238 sabres and bayonets

2.

- , 1812.

.

Fourth division.

Fifth division.

FOOTNOTE:

[3] These regiments were attached by companies to the third, fourth, and fifth divisions.

Total Portuguese loss at the assault.

British loss during the whole siege. Officers. Sergeants. Soldiers. Total. 60 45 715 killed }

the whole siege.

Under arms. Detached. Absent. Effective.

Observation In September 1811 an army of reserve, consisting of two divisions of infantry and one of cavalry, with artillery, in all 20,287 under arms, was formed for the armée du midi.

1st August, 1811

Under arms. Detached. Effective. Men. Horses. Men. Horses. Hosp. Men. Horses. 1,195 }

15th August, 1811.

.

16th May, 1811. Fifth battalion. 2,887 239 361 ” 380

239 1st March, 1812. 4,893 44 ” ”

.

15th December, 1811

Return of numbers, by armies, 1st October, 1811

Under arms. Detached. Absent. Effective. Men. Horses. Men. Horses. Hosp. Pris. Men. Horses. 9,251 }

15th April, 1812.

T. W . B O O N E ,

29, NEW BOND STREET.

A REPLY TO VARIOUS OPPONENTS, PARTICULARLY TO “STRICTURES ON COLONEL NAPIER’S HISTORY OF THE WAR IN THE PENINSULA:”

Together with OBSERVATIONS ILLUSTRATING SIR JOHN MOORE’S CAMPAIGNS

BY COLONEL NAPIER.

8vo price 2s

COL. NAPIER’S JUSTIFICATION OF HIS THIRD VOLUME,

FORMING A SEQUEL TO HIS REPLY TO VARIOUS OPPONENTS, AND CONTAINING SOME NEW AND CURIOUS FACTS RELATIVE TO THE BATTLE OF ALBUERA.

“There was a man in Islington, And he was wondrous wise, He jumped into a quickset hedge And scratched out both his eyes ”

8vo price 1s 6d

The above are printed uniformly with the History

“In comprehensiveness, breadth, vigour, originality, and penetration, the first place among military historians must be conceded to Napier; and it is now established beyond all dispute, that his historical honesty is equal to his intellectual power and professional erudition. Indeed, the marvel is, that in a work treating of a subject so eminently disputable, and in a manner, too, which could not fail to provoke the bitterest hostility, so little has been challenged; and it is still more wonderful, that of that little, nothing of any importance has been proved to be substantially erroneous.”——Caledonian Mercury.

HISTORY OF THE WAR IN THE PENINSULA, AND IN THE SOUTH OF FRANCE;

From the Year 1807 to the Year 1814.

B W F P NAPIER, C B

Colonel Forty-Third Regiment; Member of the Royal Swedish Academy of Military Sciences.

New Editions, with plans, of Volumes I. II. and III. price 20s. each.

SKETCHES IN SPAIN,

During the Years 1829-30-31 and 32;

Containing Notices of some Districts very little known; of the Manners of the People, Government, Recent Changes, Commerce, Fine Arts, and Natural History.

Two vol 8vo price 21s

“Volumes of great value and attraction; we would say, in a word, they afford us the most complete account of Spain in every respect which has issued from the press.”——Literary Gazette.

“The value of the book is in its matter and its facts. If written upon any country it would have been useful, but treating of one like Spain, about which we know almost nothing, but of which it is desirable to know so much, Captain Cook’s Sketches must be considered an acquisition to the library.”——Spectator

MEMOIR

BY GENERAL SIR HEW DALRYMPLE, BART. OF HIS PROCEEDINGS

AS CONNECTED WITH THE AFFAIRS OF SPAIN, AND THE COMMENCEMENT OF THE PENINSULAR WAR.

In one vol. 8vo. price 9s. boards.

“The care bestowed upon this subject by Sir Hew Dalrymple is evident in the publication before us, which is unquestionably a most dignified, clear, and satisfactory vindication of Sir Hew’s motives and conduct, and forms, with the documents in the Appendix, a very valuable and authentic addition to the materials for the history of the period in question. Without a participation in the facts it discloses, the records of the war, as far as regards this particular subject, are, in fact, incomplete or distorted.”——United Service Journal.

“These volumes, the work of a gentleman of high and varied accomplishments, whose opportunities of observation have been unusually extensive and well-improved, will command and repay attention. They contain by far the best account of Spain which has yet issued from the press.”——United Service Gazette.

ADVENTURES IN THE RIFLE BRIGADE IN THE

P E N I N S U L A , F R A N C E , AND

THE NETHERLANDS,

From the Year 1809 to 1815; B CAPTAIN JOHN KINCAID, F B.

One vol. post 8vo. price 10s. 6d. boards.

“We do not recollect one, among the scores of personal narratives, where the reader will find more of the realities of a Soldier’s Life, or of the horrors that mark it; all is told gaily, but not unfeelingly.”——New Monthly Magazine, July

“His book has one fault, the rarest fault in books, it is too short.”——Monthly Magazine, April.

“His book is one of the most lively histories of Soldiers’ Adventures which have yet appeared; their entire freedom from affectation will sufficiently recommend them to a numerous class of readers.”——Athenæum.

“Kincaid’s Adventures in the Rifle Brigade is written with all the frankness and freedom from study which bespeaks the gallant soldier, one to whom the sword is more adapted than the pen, but who, as now cedunt arma togæ, has, in these ‘piping times’ of peace determined ‘to fight all his battles over again,’ and he fights them in a style interesting and graphic. The remarks on the decisive termination of the Battle of Waterloo are striking and convincing; and to them and the whole book we refer our readers for much amusement and information.”——The Age.

THE HISTORY OF THE

K I N G ’ S G E R M A N L E G I O N ,

FROM THE PERIOD OF ITS ORGANIZATION IN 1803, TO THAT OF ITS DISSOLUTION IN 1816.

Compiled from Manuscript Documents.

B N. LUDLOW BEAMISH, Esq. F.R.S.late Major unattached.

Vol. I. 8vo. with coloured plates; price 20s. boards; to be completed in two volumes.

“Of the late war we have had histories, partial or complete, in countless abundance; but we have not seen one, displaying more moderation, more diligence in investigating the truth, or more shrewdness in deciding between conflicting statements. Though professedly merely a history of the services of the German Legion, it is, in fact, a history of the entire war; for, from ‘what glorious and well-foughten field,’ can we record the absence of German Chivalry? The work is not like others we could name—a mere compilation from newspapers and magazines. Major Beamish has left no source of information unexplored; and the access he obtained to manuscript journals has enabled him to intersperse his general narrative with interesting personal anecdotes, that render this volume as delightful for those who read for amusement, as those who read for profit.”——Athenæum.

“We are altogether much pleased with the volume, and heartily recommend it to the British public.”——Literary Gazette.

AN ESSAY ON THE

AND THE PASSAGE OF RIVERS IN MILITARY OPERATIONS. BY MAJOR-GENERAL SIR HOWARD DOUGLAS, BART K S C , D C L , F R S , &c &c

The Second Edition, containing much additional Matter and Plates, 8vo. price 20s. boards.

N AVA L E V O L U T I O N S ; A MEMOIR,

B MAJOR-GENERAL SIR HOWARD DOUGLAS, BART K.S.C. &c. &c.

Refuting Mr C’ claims to the manœuvre of breaking the Line during Lord Rodney’s Engagement on the 12th of April, 1782.

Also,

REMARKS ON MR. CLERK’S WORK ON NAVAL TACTICS, AND ON NAVAL EVOLUTIONS IN GENERAL. In 8vo. with plates, price 10s.

TRACTS ON VAULTS AND BRIDGES; CONTAINING

OBSERVATIONS ON THE VARIOUS FORMS OF VAULTS, ON THE TAKING DOWN AND REBUILDING LONDON BRIDGE; And ON THE PRINCIPLES OF ARCHES:

Illustrated by extensive Tables of Bridges. Also, containing the PRINCIPLES OF PENDANT BRIDGES,

With reference to the Properties of the Catenary, applied to the Menai Bridge, and a Theoretical Investigation of the Catenary. BY SAMUAL WARE.

With 20 copper-plates and 10 wood-cuts, royal 8vo. price 20s. boards.

This book will be found of the highest importance to Military as well as Civil Engineers, being the only practical work on the subject of Suspension Bridges.

A DESIGN TUNNEL THAMES, from Horslydown to St. Katharine’s, with Letter-press Description. Price 3s.

ALSO, BY THE SAME AUTHOR,

REMARKS THEATRES; and on the Propriety of Vaulting them with Brick and Stone: with Observations on the C D; and the Vaults of the Free and Accepted Masons. With 3 copper-plates, royal 8vo. sewed, price 6s.

HAVERHILL;

OR,

MEMOIRS

OFFICER ARMY

Three vol. post 8vo. price £1: 11: 6 boards.

WOLFE

“The author of Haverhill is evidently an informed man, an original thinker, an acute observer, and a vigorous writer He is no imitator; he thinks for himself; he puts his trust in his own feelings, and writes as he thinks and feels; he is no mere literary echo. The fruit with which he presents us is indigenous, and bears the aroma, fresh and fragrant, of its own native soil. Those portions of the book which are really matters of history cannot well be surpassed. They teem with ‘thoughts that breathe and words that burn.’ We recommend it to all that desire to admire, and be instructed as well as amused.”——Athenæum.

“It is to the full as earnest and impressive, and conceived in nearly as philosophical a spirit as Lawrie Todd, while it is more full of adventure, character, and historical details.”—— Atlas.

AT T I L A , A Tragedy;

A N D O T H E R P O E M S ,

Post 8vo. price 10s. 6d. boards.

“This is a volume of very sweet poetry.”——Metropolitan.

“The eminent qualities which it exhibits of dramatic poetry, and the probability which it affords that the same talents stimulated by the prospect of a fair estimate on the stage,

might add to the rich store of our permanent acting drama.”——Old England.

“The Author of Attila is a man who has seen much, and has brought to aid him, in writing the above, talents of a high character, much observation, and keen insight into the characters of men, and vigorous powers of imagination.”——Weekly Visitor.

L A C

O Q U E T T E R I E ; OR,

SKETCHES OF SOCIETY IN FRANCE AND BELGIUM.

“La Coquetterie? c’est ce que les hommes méprisent et ce qui les attire.”——D G

Three vol. post 8vo. price £1: 7: 0 boards.

“To delineate continental character and domestic manners has been the chief aim of the Author of La Coquetterie; and a long residence abroad, and intimacy with his subject, have enabled him to complete the picture which he sketched in imagination. We have seldom met with a work in which the characters converse, and act, and live with more elegance and genteel ease. The work is certainly clever.”——Athenæum.

“It is decidedly original, and not in style only, but in plot, character, and incidents. There is a lively and earnest tone pervading the book, and an interest thrown into the persons and actions of nearly all the dramatis personæ, that pleases us far more than most novels of this class. We like and recommend the work, both for its purpose, its moral, and its characters, with some of whom we had well nigh fallen in love.”——National Omnibus.

LENT LECTURES.

I. On the Life of Christ. II. On the Life of St. Paul. III. On the Lord’s Prayer. IV. On the Liturgy of the Church of England.

V On the Creeds and Sacraments of the Church of England.

Preached in the Church of St. Mary, Bryanston Square, B REVEREND

T F DIBDIN, D D RECTOR

Chaplain in Ordinary to His Majesty, and Editor of the Sunday Library. Two vols, post 8vo. price 1l. 1s. bound in cloth.

“These lectures, some of them the earliest pulpit productions of the Author, display much ability and often eloquence. In principle Dr. Dibdin shews himself to be a true and loyal son of the church, whose excellencies he warmly defends, while he allows that, as in every earthly thing, evils may have crept in which it would be wise to reform, especially at this crisis now threatened by clamour, misrepresentation, and violence.”——Literary Gazette.

B A M P T O N L E C T U R E S .

The Analogy of Revelation and Science established in a Series of Lectures delivered before the University of Oxford in the Year 1833.

Vicar of Prittlewell, Essex, and formerly Student of Exeter College, Oxford.

One thick volume 8vo. price 15s.

BY THE SAME AUTHOR. THE TIME OF THE

INVESTIGATED;

One vol. 8vo. price 8s. boards.

SUPPLEMENT TO AN INQUIRY INTO THE

INTEGRITY OF THE GREEK VULGATE;

OR,

RECEIVED TEXT OF THE NEW TESTAMENT; Containing the Vindication of the Principles employed in its Defence.

A

HARMONICAL GRAMMAR OF THE GREEK LANGUAGE.

8vo. sewed, price 4s.

Ditto of the Latin 8vo price 4s

Ditto of the French. 8vo. price 4s.

Ditto of the Italian 8vo price 4s

Ditto of the Spanish. 8vo. price 4s.

Printed verbatim from a Harmonical Grammar of the principal ancient and modern languages. Each language is treated upon a uniform plan, and analyzed on new and simple principles; short and comprehensive rules are given, for attaining a just pronunciation, for determining the gender, and inflecting the noun and verb; together with a Syntax and Prosody, fully exemplified, and a classed vocabulary of the most useful and necessary words.

T EXPECTATIONS FORMED ASSYRIANS, GREAT DELIVERER WOULD APPEAR, T L’ A, . 8vo. price 10s. boards.

And all the other Works of the same Author.

MOMENTS OF IDLENESS;

A PEEP INTO THE WORLD WE CALL “OURS

“Il y en a qui ne font rien,—il y en a d’autres qui font des riens.”

In 1 vol. foolscap 8vo. neatly bound in cloth, price 7s.

“Will prove a pleasant source of mental employment at a leisure hour.”——Monthly Review.

“The author is clever and thinks, which is what very few people actually achieve.”—— New Monthly Magazine.

“He is worth any man’s perusal (we have read him every bit); and, besides many striking reflections, gives numerous evidences of a benevolent and social disposition.”——True Sun.

“This is a very remarkable volume, and it is one of great merit; and he who devotes to it his ‘Moments of Idleness’ will be idle no longer, or then it will be his own fault. We have seldom met, indeed, with a volume containing so many and such substantial materials for thinking, in so small a compass, and combining at the same time so much intellectual employment with so much literary amusement.”——Liverpool Chronicle.

WALTER;

OR,

A WORD MORE TO THE WISE

“Still he comes, Summer or winter, frost or rain. I’ve seen The snow upon a level with the hedge, Yet there was Master Walter.”

Hunchback, Act 1. Scene 2.

BY THE AUTHOR OF “MOMENTS OF IDLENESS.”

In 1 vol. foolscap 8vo. neatly bound in cloth, price 7s.

A TREATISE ON THE

G A M E O F W H I S T,

Author of Voyages and Discoveries in the Pacific, &c.

Second Edition. 18mo. boards, price 2s.

“The kind of play recommended in this Treatise is on the most plain, and what the Author considers the most safe principles. I have limited my endeavours to the most necessary instructions, classing them as much as the subject enabled me, under separate heads, to facilitate their being rightly comprehended and easily remembered. For the greater encouragement of the learner, I have studied brevity; but not in a degree to have prevented my endeavouring more to make the principles of the game, and the rationality of them intelligible, than to furnish a young player with a set of rules to get by rote, that he might go blindly right.”

TRANSCRIBER’S NOTE

Footnote [3] has two anchors on page 587

Obvious typographical errors and punctuation errors have been corrected after careful comparison with other occurrences within the text and consultation of external sources.

Some hyphens in words have been silently removed, some added, when a predominant preference was found in the original book.

To save space in the wide tables in Note IX of the Appendix, the heading ‘Hospital.’ has been abbreviated to ‘Hosp.’.

In those sections of the Appendix that are French documents, some corrections to accents have been made silently; primarily é for e, and e for é. Incorrect grammar and spelling have been left unchanged.

Except for those changes noted below, all misspellings in the text, and inconsistent or archaic usage, have been retained.

Table of Contents:

Pg iii: ‘on the Orbigo’ replaced by ‘on the Orvigo’.

Pg iii: ‘General Leval’ replaced by ‘General Laval’.

Pg v: ‘the mili ary force’ replaced by ‘the military force’.

Main text:

Pg 5: ‘by sea to St. Ander’ replaced by ‘by sea to Santander’.

Pg 13: ‘he surprized some’ replaced by ‘he surprised some’.

Pg 33: ‘embarrasments thus’ replaced by ‘embarrassments thus’.

Pg 48: ‘and Legre rivers’ replaced by ‘and Segre rivers’.

Pg 51: ‘to war down’ replaced by ‘to wear down’.

Pg 61: ‘Promothean touch’ replaced by ‘Promethean touch’.

Pg 135: ‘commucating with the alledged’ replaced by ‘communicating with the alleged’.

Pg 141: ‘were they all’ replaced by ‘where they all’.

Pg 162: ‘the admistration’ replaced by ‘the administration’.

Pg 164: ‘Mr. Suart and’ replaced by ‘Mr. Stuart and’.

Pg 169: ‘acknowleged that’ replaced by ‘acknowledged that’.

Pg 169: ‘a proponderance to’ replaced by ‘a preponderance to’.

Pg 170: ‘Rio Janeiro’ replaced by ‘Rio de Janeiro’.

Pg 196: ‘aid-du-camp’ replaced by ‘aide-de-camp’.

Pg 231: ‘Miunte reports of’ replaced by ‘Minute reports of’.

Pg 243: ‘Aldea Ponte’ replaced by ‘Aldea de Ponte’.

Pg 245: ‘behind the Soita’ replaced by ‘behind Soita’.

Pg 268: ‘which caanot now’ replaced by ‘which cannot now’.

Pg 296, image caption: ‘The Seige’ replaced by ‘The Siege’.

Pg 309: ‘also an artifical’ replaced by ‘also an artificial’.

Pg 310: ‘and Catalayud to’ replaced by ‘and Calatayud to’.

Pg 314: ‘were straightened’ replaced by ‘were straitened’.

Pg 319: ‘a confidental’ replaced by ‘a confidential’.

Pg 319: ‘the Guadalquiver’ replaced by ‘the Guadalquivir’.

Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.