100% found this document useful (1 vote)
53 views

Download ebooks file Functional and Concurrent Programming Core Concepts and Features 1 / converted Edition Michel Charpentier all chapters

Functional

Uploaded by

mladkulm42
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 (1 vote)
53 views

Download ebooks file Functional and Concurrent Programming Core Concepts and Features 1 / converted Edition Michel Charpentier all chapters

Functional

Uploaded by

mladkulm42
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/ 65

Download Full Version ebook - Visit ebookmeta.

com

Functional and Concurrent Programming Core


Concepts and Features 1 / converted Edition Michel
Charpentier

https://ebookmeta.com/product/functional-and-concurrent-
programming-core-concepts-and-features-1-converted-edition-
michel-charpentier/

OR CLICK HERE

DOWLOAD NOW

Discover More Ebook - Explore Now at ebookmeta.com


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

Start reading on any device today!

Concurrent Programming Algorithms Principles and


Foundations 1st Edition Michel Raynal

https://ebookmeta.com/product/concurrent-programming-algorithms-
principles-and-foundations-1st-edition-michel-raynal/

ebookmeta.com

Get Programming with JavaScript Next New features of


ECMAScript 2015 2016 and beyond 1 / converted Edition Jd
Isaacks
https://ebookmeta.com/product/get-programming-with-javascript-next-
new-features-of-ecmascript-2015-2016-and-beyond-1-converted-edition-
jd-isaacks/
ebookmeta.com

Functional Analysis Fundamentals and Applications 2nd


Edition Michel Willem

https://ebookmeta.com/product/functional-analysis-fundamentals-and-
applications-2nd-edition-michel-willem/

ebookmeta.com

Fundamental and Advanced Fetal Imaging Ultrasound and MRI


2nd Edition Beth Kline-Fath

https://ebookmeta.com/product/fundamental-and-advanced-fetal-imaging-
ultrasound-and-mri-2nd-edition-beth-kline-fath/

ebookmeta.com
A Colorful Home Create Lively Palettes for Every Room
Susan Hable

https://ebookmeta.com/product/a-colorful-home-create-lively-palettes-
for-every-room-susan-hable/

ebookmeta.com

Zeven Ways to Kill Your Lover Shannon

https://ebookmeta.com/product/zeven-ways-to-kill-your-lover-shannon/

ebookmeta.com

Heartsblood Omnibus 1st Edition Fenech Selina A

https://ebookmeta.com/product/heartsblood-omnibus-1st-edition-fenech-
selina-a/

ebookmeta.com

SQL Server 2022 Administration Inside Out 1st Edition


Randolph West

https://ebookmeta.com/product/sql-server-2022-administration-inside-
out-1st-edition-randolph-west/

ebookmeta.com

The Android Malware Handbook Qian Han

https://ebookmeta.com/product/the-android-malware-handbook-qian-han/

ebookmeta.com
The Afterlife of Ottoman Europe Muslims in Habsburg Bosnia
Herzegovina Stanford Studies on Central and Eastern Europe
1st Edition Amzi-Erdogdular
https://ebookmeta.com/product/the-afterlife-of-ottoman-europe-muslims-
in-habsburg-bosnia-herzegovina-stanford-studies-on-central-and-
eastern-europe-1st-edition-amzi-erdogdular/
ebookmeta.com
Functional, Object-Oriented, and
Concurrent Programming

Michel Charpentier
Table of Contents

Foreword
Preface
Acknowledgements
About the Author

Part I: Functional Programming

Chapter 1. Concepts of Functional Programming

Chapter 2. Functions in Programming Languages

Chapter 3. Immutability

Chapter 4. Case Study: Active–Passive Sets

Chapter 5. Pattern Matching and Algebraic Data Types

Chapter 6. Recursive Programming

Chapter 7. Recursion on Lists

Chapter 8. Case Study: Binary Search Trees

Chapter 9. Higher-Order Functions

Chapter 10. Standard Higher-Order Functions

Chapter 11. Case Study: File Systems as Trees

Chapter 12. Lazy Evaluation


Chapter 13. Handling Failures

Chapter 14. Case Study: Trampolines

A Brief Interlude

Chapter 15. Types (and Related Concepts)

Part II: Concurrent Programming

Chapter 16. Concepts of Concurrent Programming

Chapter 17. Threads and Nondeterminism

Chapter 18. Atomicity and Locking

Chapter 19. Thread-Safe Objects

Chapter 20. Case Study: Thread-Safe Queue

Chapter 21. Thread Pools

Chapter 22. Synchronization

Chapter 23. Common Synchronizers

Chapter 24. Case Study: Parallel Execution

Chapter 25. Futures and Promises

Chapter 26. Functional-Concurrent Programming

Chapter 27. Minimizing Thread Blocking

Chapter 28. Case Study: Parallel Strategies

Appendix A. Features of Java and Kotlin

Glossary
Contents

Foreword
Preface
Why Scala?
Target Audience
How to Read This Book
Additional Resources
Acknowledgements
About the Author

Part I: Functional Programming

Chapter 1. Concepts of Functional Programming


1.1 What Is Functional Programming?
1.2 Functions
1.3 From Functions to Functional Programming Concepts
Summary

Chapter 2. Functions in Programming Languages


2.1 Defining Functions
2.2 Composing Functions
2.3 Functions Defined as Methods
2.4 Operators Defined as Methods
2.5 Extension Methods
2.6 Local Functions
2.7 Repeated Arguments
2.8 Optional Arguments
2.9 Named Arguments
2.10 Type Parameters
Summary

Chapter 3. Immutability
3.1 Pure and Impure Functions
3.2 Actions
3.3 Expressions Versus Statements
3.4 Functional Variables
3.5 Immutable Objects
3.6 Implementation of Mutable State
3.7 Functional Lists
3.8 Hybrid Designs
3.9 Updating Collections of Mutable/Immutable Objects
Summary

Chapter 4. Case Study: Active–Passive Sets


4.1 Object-Oriented Design
4.2 Functional Values
4.3 Functional Objects
Summary

Chapter 5. Pattern Matching and Algebraic Data Types


5.1 Functional Switch
5.2 Tuples
5.3 Options
5.4 Revisiting Functional Lists
5.5 Trees
5.6 Illustration: List Zipper
5.7 Extractors
Summary

Chapter 6. Recursive Programming


6.1 The Need for Recursion
6.2 Recursive Algorithms
6.3 Key Principles of Recursive Algorithms
6.4 Recursive Structures
6.5 Tail Recursion
6.6 Examples of Tail Recursive Functions
Summary

Chapter 7. Recursion on Lists


7.1 Recursive Algorithms as Equalities
7.2 Traversing Lists
7.3 Returning Lists
7.4 Building Lists from the Execution Stack
7.5 Recursion on Multiple/Nested Lists
7.6 Recursion on Sublists Other Than the Tail
7.7 Building Lists in Reverse Order
7.8 Illustration: Sorting
7.9 Building Lists Efficiently
Summary

Chapter 8. Case Study: Binary Search Trees


8.1 Binary Search Trees
8.2 Sets of Integers as Binary Search Trees
8.3 Implementation Without Rebalancing
8.4 Self-Balancing Trees
Summary

Chapter 9. Higher-Order Functions


9.1 Functions as Values
9.2 Currying
9.3 Function Literals
9.4 Functions Versus Methods
9.5 Single-Abstract-Method Interfaces
9.6 Partial Application
9.7 Closures
9.8 Inversion of Control
Summary

Chapter 10. Standard Higher-Order Functions


10.1 Functions with Predicate Arguments
10.2 map and foreach
10.3 flatMap
10.4 fold and reduce
10.5 iterate, tabulate, and unfold
10.6 sortWith, sortBy, maxBy, and minBy
10.7 groupBy and groupMap
10.8 Implementing Standard Higher-Order Functions
10.9 foreach, map, flatMap, and for-Comprehensions
Summary

Chapter 11. Case Study: File Systems as Trees


11.1 Design Overview
11.2 A Node-Searching Helper Function
11.3 String Representation
11.4 Building Trees
11.5 Querying
11.6 Navigation
11.7 Tree Zipper
Summary

Chapter 12. Lazy Evaluation


12.1 Delayed Evaluation of Arguments
12.2 By-Name Arguments
12.3 Control Abstraction
12.4 Internal Domain-Specific Languages
12.5 Streams as Lazily Evaluated Lists
12.6 Streams as Pipelines
12.7 Streams as Infinite Data Structures
12.8 Iterators
12.9 Lists, Streams, Iterators, and Views
12.10 Delayed Evaluation of Fields and Local Variables
12.11 Illustration: Subset-Sum
Summary

Chapter 13. Handling Failures


13.1 Exceptions and Special Values
13.2 Using Option
13.3 Using Try
13.4 Using Either
13.5 Higher-Order Functions and Pipelines
Summary

Chapter 14. Case Study: Trampolines


14.1 Tail-Call Optimization
14.2 Trampolines for Tail-Calls
14.3 Tail-Call Optimization in Java
14.4 Dealing with Non-Tail-Calls
Summary

A Brief Interlude

Chapter 15. Types (and Related Concepts)


15.1 Typing Strategies
15.2 Types as Sets
15.3 Types as Services
15.4 Abstract Data Types
15.5 Type Inference
15.6 Subtypes
15.7 Polymorphism
15.8 Type Variance
15.9 Type Bounds
15.10 Type Classes
Summary

Part II: Concurrent Programming

Chapter 16. Concepts of Concurrent Programming


16.1 Non-sequential Programs
16.2 Concurrent Programming Concepts
Summary

Chapter 17. Threads and Nondeterminism


17.1 Threads of Execution
17.2 Creating Threads Using Lambda Expressions
17.3 Nondeterministic Behavior of Multithreaded Programs
17.4 Thread Termination
17.5 Testing and Debugging Multithreaded Programs
Summary

Chapter 18. Atomicity and Locking


18.1 Atomicity
18.2 Non-atomic Operations
18.3 Atomic Operations and Non-atomic Composition
18.4 Locking
18.5 Intrinsic Locks
18.6 Choosing Locking Targets
Summary

Chapter 19. Thread-Safe Objects


19.1 Immutable Objects
19.2 Encapsulating Synchronization Policies
19.3 Avoiding Reference Escape
19.4 Public and Private Locks
19.5 Leveraging Immutable Types
19.6 Thread-Safety
Summary

Chapter 20. Case Study: Thread-Safe Queue


20.1 Queues as Pairs of Lists
20.2 Single Public Lock Implementation
20.3 Single Private Lock Implementation
20.4 Applying Lock Splitting
Summary

Chapter 21. Thread Pools


21.1 Fire-and-Forget Asynchronous Execution
21.2 Illustration: Parallel Server
21.3 Different Types of Thread Pools
21.4 Parallel Collections
Summary

Chapter 22. Synchronization


22.1 Illustration of the Need for Synchronization
22.2 Synchronizers
22.3 Deadlocks
22.4 Debugging Deadlocks with Thread Dumps
22.5 The Java Memory Model
Summary

Chapter 23. Common Synchronizers


23.1 Locks
23.2 Latches and Barriers
23.3 Semaphores
23.4 Conditions
23.5 Blocking Queues
Summary

Chapter 24. Case Study: Parallel Execution


24.1 Sequential Reference Implementation
24.2 One New Thread per Task
24.3 Bounded Number of Threads
24.4 Dedicated Thread Pool
24.5 Shared Thread Pool
24.6 Bounded Thread Pool
24.7 Parallel Collections
24.8 Asynchronous Task Submission Using Conditions
24.9 Two-Semaphore Implementation
Summary

Chapter 25. Futures and Promises


25.1 Functional Tasks
25.2 Futures as Synchronizers
25.3 Timeouts, Failures, and Cancellation
25.4 Future Variants
25.5 Promises
25.6 Illustration: Thread-Safe Caching
Summary

Chapter 26. Functional-Concurrent Programming


26.1 Correctness and Performance Issues with Blocking
26.2 Callbacks
26.3 Higher-Order Functions on Futures
26.4 Function flatMap on Futures
26.5 Illustration: Parallel Server Revisited
26.6 Functional-Concurrent Programming Patterns
Summary

Chapter 27. Minimizing Thread Blocking


27.1 Atomic Operations
27.2 Lock-Free Data Structures
27.3 Fork/Join Pools
27.4 Asynchronous Programming
27.5 Actors
27.6 Reactive Streams
27.7 Non-blocking Synchronization
Summary

Chapter 28. Case Study: Parallel Strategies


28.1 Problem Definition
28.2 Sequential Implementation with Timeout
28.3 Parallel Implementation Using invokeAny
28.4 Parallel Implementation Using CompletionService
28.5 Asynchronous Implementation with Scala Futures
28.6 Asynchronous Implementation with CompletableFuture
28.7 Caching Results from Strategies
Summary

Appendix A Features of Java and Kotlin


A.1 Functions in Java and Kotlin
A.2 Immutability
A.3 Pattern Matching and Algebraic Data Types
A.4 Recursive Programming
A.5 Higher-Order Functions
A.6 Lazy Evaluation
A.7 Handling Failures
A.8 Types
A.9 Threads
A.10 Atomicity and Locking
A.11 Thread-Safe Objects
A.12 Thread Pools
A.13 Synchronization
A.14 Futures and Functional-Concurrent Programming
A.15 Minimizing Thread Blocking

Glossary
Foreword

This content is currently in development.


Preface

Before you start reading this book, it is important to think about the
distinction between programming languages and programming language
features. I believe that developers benefit from being able to rely on an
extensive set of programming language features, and that a solid
understanding of these features—in any language—will help them be
productive in a variety of programming languages, present or future.
The world of programming languages is varied, and continues to evolve all
the time. As a developer, you are expected to adapt, and to repeatedly
transfer your programming skills from one language to another. Learning
new programming languages is made easier by mastering a set of core
features that today’s languages often share, and that many of tomorrow’s
languages are likely to use as well.
Programming language features are illustrated in this book with numerous
code examples, primarily in Scala (for reasons that are detailed later). The
concepts, however, are relevant—with various degrees—to other popular
languages like Java, C++, Kotlin, Python, C#, Swift, Rust, Go, JavaScript,
and whatever languages might pop up in the future to support strong typing
as well as functional and/or concurrent programming.
As an illustration of the distinction between languages and features,
consider the following programming task:
Shift every number from a given list by a random amount between −10 and 10. Return a list of
shifted numbers, omitting all values that are not positive.

A Java programmer might implement the desired function as follows:


Java

List<Integer> randShift(List<Integer> nums, Random rand) {


var shiftedNums = new java.util.ArrayList<Integer>(nums.size()
for (int num : nums) {
for (int num : nums) {
int shifted = num + rand.nextInt(-10, 11);
if (shifted > 0) shiftedNums.add(shifted);
}
return shiftedNums;
}

A Python programmer might write this instead:


Python

def rand_shift(nums, rand):


shifted_nums = []
for num in nums:
shifted = num + rand.randrange(-10, 11)
if shifted > 0:
shifted_nums.append(shifted)
return shifted_nums

Although they are written in two different languages, both functions follow
a similar strategy: Create a new empty list to hold the shifted numbers, shift
each original number by a random amount, and add the new values to the
result list only when they are positive. For all intents and purposes, the two
programs are the same.
Other programmers might choose to approach the problem differently. Here
is one possible Java variant:
Java

List<Integer> randShift(List<Integer> nums, Random rand) {


return nums.stream()
.map(num -> num + rand.nextInt(-10, 11))
.filter(shifted -> shifted > 0)
.toList();
}

The details of this implementation are not important for now—it relies on
functional programming concepts that will be discussed in Part I. What
matters is that the code is noticeably different from the previous Java
implementation.
You can write a similar functional variant in Python:
Python

def rand_shift(nums, rand):


return list(filter(lambda shifted: shifted > 0,
map(lambda num: num + rand.randrange(-10,

This implementation is arguably closer to the second Java variant than it is


to the first Python program.
These four programs demonstrate two different ways to solve the original
problem. They contrast an imperative implementation—in Java or in
Python—with a functional implementation—again, in Java or in Python.
What fundamentally distinguishes the programs is not the languages—Java
versus Python—but the features being used— imperative versus functional.
The programming language features used in the imperative variant
(assignment statements, loops) and in the functional variant (higher-order
functions, lambda expressions) exist independently from Java and Python;
indeed, they are available in many programming languages.
I am not saying that programming languages don’t matter. We all know that,
for a given task, some languages are a better fit than others. But I want to
emphasize core features and concepts that extend across languages, even
when they appear under a different syntax. For instance, an experienced
Python programmer is more likely to write the example functional program
in this way:

def rand_shift(nums, rand):


return [shifted for shifted in (num + rand.randrange(-10, 11
if shifted > 0]
This code looks different from the earlier Python code—and the details are
again unimportant. Notice that functions map and filter are nowhere to be
seen. Conceptually, though, this is the same program, but written using a
specific Python syntax known as list comprehension, instead of map and
filter.

The important concept to understand here is the use of map and filter (and
more generally higher-order functions, of which they are an example), not
list comprehension. You benefit from this understanding in two ways. First,
more languages support higher-order functions than have a comprehension
syntax. If you are programming in Java, for instance, you will have to write
map and filter explicitly (at least for now). Second, if you ever face a
language that uses a somewhat unusual syntax, as Python does with list
comprehension, it will be easier to recognize what is going on once you
realize that it is just a variation of a concept you already understand.
The preceding code examples illustrate a contrast between a program
written in plain imperative style, and one that leverages the functional
programming features available in many languages. I can make a similar
argument with concurrent programming. Languages (and libraries) have
evolved, and there is no reason to write today’s concurrent programs the
way we did 20 years ago. As a somewhat extreme example, travel back not
quite 20 years to 2004, the days of Java 1.4, and consider the following
problem:
Given two tasks that each produce a string, invoke both tasks in parallel, and return the first
string that is produced.

Assume a type StringComputation with a string-producing method compute.


In Java 1.4, the problem can be solved as follows (do not try to understand
the code; it is rather long, and the details are unimportant):
Java

String firstOf(final StringComputation comp1, final StringComputa


throws InterruptedException {
class Result {
private String value = null;

public synchronized void setValue(String str) {


if (value == null) {
if (value == null) {
value = str;
notifyAll();
}
}

public synchronized String getValue() throws InterruptedExcep


while (value == null)
wait();
return value;
}
}

final Result result = new Result();


Runnable task1 = new Runnable() {
public void run() {
result.setValue(comp1.compute());
}
};
Runnable task2 = new Runnable() {
public void run() {
result.setValue(comp2.compute());
}
};
new Thread(task1).start();
new Thread(task2).start();
return result.getValue();
}

This implementation uses features with which you may not be familiar (but
which are covered in Part II of the book).1 Here are the important points to
notice:
1 One reason such old-fashioned features are still covered in this book is that I believe they help
us understand the richer and fancier constructs that we should be using in practice. The other reason
is that the concurrent programming landscape is still evolving, and recent developments, such as
virtual threads in the Java Virtual Machine, have the potential to make these older concepts relevant
again.

• The code is about 30 lines long.


• It relies on synchronized methods, a form of locking available in the
Java Virtual Machine (JVM).
• It uses methods wait and notifyAll, which implement a basic
synchronization scheme on the JVM.
• It starts its own two threads to run the two tasks in parallel.
Fast forward to today’s Java, and reimplement the program:
Java

String firstOf(StringComputation comp1, StringComputation comp2,


throws InterruptedException, ExecutionException {
var result = new CompletableFuture<String>();
result.completeAsync(comp1::compute, threads);
result.completeAsync(comp2::compute, threads);
return result.get();
}

Again, ignore the details, and observe these points:


• The code is much shorter.
• Class Result is gone. It implemented a poor man’s form of a future, but
futures are now available is many languages, including Java.
• Synchronized methods are gone. The code does not rely on locks
anywhere.
• Methods wait and notifyAll are gone. Instead, CompletableFuture
implements its own synchronization, correctly and efficiently.
• No thread is created explicitly. Instead, threads are passed as an
argument in the form of an Executor, and can be shared with the rest of
the application.
There is one more difference between the two variants that I want to
emphasize. In the newer code, the two Runnable classes have disappeared.
They have been replaced with an odd-looking syntax that did not exist in
Java 1.4: comp1::compute. You may find this syntax puzzling because
method compute seems to be missing its parentheses. Indeed, this code does
not invoke compute, but rather uses the method itself as an argument to
completeAsync. It could be written as a lambda expression instead:
comp1::compute is the same as () -> comp1.compute(). Passing functions as
arguments to functions is a fundamental concept of functional
programming, which is explored at length in Part I, but finds frequent uses
in writing concurrent code as well.
Here’s the point of this illustration: You can still write the first version of
the program in today’s Java, but you shouldn’t. It is notoriously difficult to
get multithreaded code correct, and even more difficult to get it correct and
make it efficient. Instead, you should leverage what is available in the
language, and use it effectively. Are you making the most of the
programming languages you are using today?
As a trend, programming languages have become more abstract and richer
in features, a shift that makes many programming tasks less demanding.
There are more concepts to understand in Java 19 than there were in Java 1,
but it is easier to write correct and efficient programs with Java 19 than it
was with Java 1. Feature-rich programming languages can be harder to
learn, but they are also more powerful once mastered.
Of course, what you find hard or easy depends a lot on your programming
background, and it is important not to confuse simplicity with familiarity.
The functional variants of the Java and Python programs presented earlier
are not more complicated than the imperative variants, but for some
programmers, they can certainly be less familiar. Indeed, it is more difficult
for a programmer to shift from an imperative to a functional variant (or vice
versa) within Java or Python than it is to shift from Java to Python (or vice
versa) within the same imperative or functional style. The latter transition is
mostly a matter of syntax, while the first requires a paradigm shift.
Most of the advantages of current, feature-rich, programming languages
revolve around functional programming, concurrency, and types—hence the
three parts of this book. A common trend is to provide developers with
abstractions that allow them to dispense with writing nonessential
implementation details, and code that is not written is bug-free code.
Jumps and gotos, for instance, were long ago discarded in high-level
programming languages in favor of structured loops. But many loops can
themselves be replaced with functional alternatives that instead use a
standard set of higher-order functions. Similarly, writing concurrent
programs directly in terms of threads and locks can be very challenging.
Relying on thread pools, futures, and other mechanisms instead can result in
simpler patterns. In many scenarios, you have no more reason to use loops
and locks than you have to write your own hash map or sorting method: It’s
unnecessary work, it’s error-prone, and it’s unlikely to achieve the
performance of existing implementations. As for types, the age-old
dichotomy between safety—being able to catch errors thanks to types—and
flexibility—not being overly constrained in design choices because of types
— is often being resolved in favor of safe and flexible type systems, albeit
complicated ones.
This book is not a comprehensive guide to everything you need to know
about functional and concurrent programming, or about types. But to
leverage modern language constructs in your everyday programming, you
need to become familiar with the abstract concepts that underlie these
features. There is more to applying functional patterns than being aware of
the syntax for lambda expressions, for instance. This book introduces only
enough concepts as are needed to use language features effectively. There is
a lot more to functional and concurrent programming and to types than
what the book covers. (There is also a lot more to Scala.) Advanced topics
are left for you to explore through other resources.

Why Scala?
As mentioned earlier, most of the code illustrations in this book are written
in Scala. This may not be the language you are most familiar with, or the
language in which you plan to develop your next application. It is a fair
question to wonder why I chose it instead of a more mainstream language.
Scala is a programming language that aims to combine object-oriented and
functional programming, with good support for concurrency as well.2 It is a
hybrid language—also called a multi-paradigm language. In fact, all three
versions of the random shifting program already written in Java and in
Python can be written in Scala:
2Different incarnations of Scala exist. This book uses the most common flavor of Scala, namely,
the one that runs on the JVM and leverages the JVM’s support for concurrency.
Scala
def randShift(nums: List[Int], rand: Random): List[Int] = {
val shiftedNums = List.newBuilder[Int]
for (num <- nums) {
val shifted = num + rand.between(-10, 11)
if (shifted > 0) {
shiftedNums += shifted
}
}
shiftedNums.result()
}

def randShift(nums: List[Int], rand: Random): List[Int] =


nums.view
.map(num => num + rand.between(-10, 11))
.filter(shifted => shifted > 0)
.toList

def randShift(nums: List[Int], rand: Random): List[Int] =


for {
num <- nums
shifted = num + rand.between(-10, 11)
if shifted > 0
} yield shifted

The first function is imperative, based on an iteration and a mutable list.


The next variant is functional, and uses map and filter explicitly. The last
variant relies on Scala’s for-comprehension, a mechanism similar to (but
more powerful than) Python’s list comprehension.
You can also use Scala to write a concise solution to the concurrency
problem. It uses futures and thread pools, like the earlier Java program:
Scala

def firstOf(comp1: StringComputation, comp2: StringComputation)


(using ExecutionContext): String = {
val future1 = Future(comp1.compute())
val future2 = Future(comp2.compute())
Await.result(Future.firstCompletedOf(Set(future1, future2)), t
}
Given the book’s objectives, there are several benefits to using Scala for
code illustrations. First, this language is feature-rich, making it possible to
illustrate many concepts without switching languages. Many of the standard
features of functional and concurrent programming exist in Scala, which
also has a powerful type system. Second, Scala was introduced fairly
recently, and was carefully (and often beautifully) designed. Compared to
some older languages, there is less historical baggage in Scala that can get
in the way when discussing underlying concepts. Finally, Scala syntax is
quite conventional and easy to follow for most programmers without prior
exposure to the language.
Nevertheless, it is important to keep in mind that programming language
features, rather than Scala per se, are the focus of this book. Although I
personally like it as a teaching language, I am not selling Scala, and this is
not a Scala book. It just happens that I need a programming language that is
clean and simple in all areas of interest, and I believe Scala meets these
requirements.

Target Audience
The target audience is programmers with enough experience to not be
distracted by simple matters of syntax. I assume prior Java experience, or
enough overall programming experience to read and understand simple Java
code. Concepts such as classes, methods, objects, types, variables, loops,
and conditionals are assumed to be familiar. A rudimentary understanding
of program execution—execution stack, garbage collection, exceptions—is
also assumed, as well as basic exposure to data structures and algorithms.
For other key terms, covered in depth in the book, the glossary provides a
basic definition, and indicates the appropriate chapter or chapters where the
concept is presented.
No prior knowledge of functional or concurrent programming is assumed.
No prior knowledge of Scala is assumed. Presumably, many readers will
have some understanding of functional or concurrent concepts, such as
recursion or locks, but no such knowledge is required. For instance, I do not
expect you to necessarily understand the functional Python and Java
programs discussed earlier, or the two Java concurrent programs, or the last
two Scala functions. Indeed, I would argue that if these programs feel
strange and mysterious, this book is for you! By comparison, the imperative
variant of the number-shifting program should be easy to follow, and I
expect you to understand the corresponding code, whether it is written in
Java, Python, or Scala. You are expected to understand simple Scala syntax
when it is similar to that of other languages, and to pick up new elements as
they are introduced.
The syntax of Scala was inspired by Java’s syntax—and that of Java by C’s
syntax— which should make the transition fairly straightforward for most
programmers. Scala departs from Java in ways that will be explained as
code examples are introduced. For now, I’ll highlight just three differences:
• Semicolon inference. In Scala, terminating semicolons are inferred by
the compiler and rarely used explicitly. They may still appear
occasionally—for instance, as a way to place two statements on the
same line.
• No “return” needed. Although a return keyword exists in Scala, it is
seldom used. Instead, a function implicitly returns the value of the last
expression evaluated in its body.
• Significant indentation. The curly braces used to define code blocks
can often be inferred from indentation, and are optional. The first Scala
randShift variant can been written:
Scala

def randShift(nums: List[Int], rand: Random): List[Int] =


val shiftedNums = List.newBuilder[Int]
for (num <- nums) do
val shifted = num + rand.between(-10, 11)
if shifted > 0 then shiftedNums += shifted
end for
shiftedNums.result()

end randShift

When indentation is used to create blocks, markers can be added to


emphasize block endings, but they are optional. An even shorter version of
the randShift function takes the following form:
Scala

def randShift(nums: List[Int], rand: Random): List[Int] =


val shiftedNums = List.newBuilder[Int]
for (num <- nums) do
val shifted = num + rand.between(-10, 11)
if shifted > 0 then shiftedNums += shifted
shiftedNums.result()

In this book, code illustrations rely on indentation instead of curly braces


when possible, and omit most end markers for the sake of compactness. I
expect readers to be able to read imperative Scala code in this form, like the
preceding function.

How to Read This Book


I believe that the primary value of this book lies in its code illustrations. To
a large extent, the text is there to support the code, more than the other way
around. The code examples tend to be short and focused on the concepts
they aim to illustrate. In particular, very few examples are designed to
perform the specific tasks you need to solve in your daily programming
activities. This is not a cookbook.
Furthermore, concepts are introduced from the ground up, starting with the
fundamentals, and expanding and abstracting toward the application level.
The code that you might find to be the most applicable is found in the later
chapters in each part of the book. I have found this progression to be most
conducive to a solid understanding of features, which can then be translated
into languages other than Scala. If you feel that the early topics are well
known and the pace too slow, please be patient.
This book is designed to be read in order, from beginning to end. Most
chapters—and their code illustrations—depend on ideas and programs
presented in earlier chapters. For instance, several solutions to the same
problem are often presented in separate chapters as a way to illustrate
different sets of programming language features. It is also the case that Part
II on concurrent programming uses concepts from Part I on functional
programming.
While this makes it near impossible to proceed through the contents in a
different order, you are free to speed through—or even skip—sections that
cover features with which you are already familiar. Material from this book
has been to used to teach undergraduate and graduate students, who are told
that, as long as the code makes sense, they are ready to move on to the next
part. It is when code starts to look puzzling that it is time to slow down and
pay closer attention to the explanations in the text.
There are several ways you can safely skip certain parts of the contents:
• Chapter 15 on types can be skipped entirely. Elsewhere in the book,
several code examples make simplifying assumptions to avoid intricate
concepts such as type bounds and type variance. A basic understanding
of Java types, including generics (but not necessarily with wildcards)
and polymorphism, is sufficient.
• Any “aside” can be safely ignored. These are designed as
complementary discussions that you may expect to find, given the
book’s topics (and I would not want to disappoint you!), and can
sometimes be lengthy. They are rarely referred to in the main text, and
any of these references can be ignored.
• Any “case study” chapter can be skipped. I would not necessarily
recommend that you do so, however, because the case study code is
where features are put together in the most interesting ways. However,
no concept or syntax needed in a later part of the book is ever
introduced in a case study. The main text does not refer to code from
the case studies, with one minor exception: Section 10.8 refers to a
binary search tree implementation developed in Chapter 8.

Additional Resources
The book’s companion website is hosted at https://fcpbook.org. It
contains additional resources, a list of errata, and access to the code
illustrations, which are available from GitHub. The code examples were
compiled and tested using Scala 3.2. The author welcomes comments and
discussions, and can be reached at author@fcbbook.org.
Acknowledgements

This content is currently in development.


Another Random Document on
Scribd Without Any Related Topics
Pollock, C. B. We are all of opinion that the declaration cannot be
supported, and that the defendant is entitled to judgment. I do not
think it necessary to point out the reasons by which I have come to
that conclusion; because it follows from the decision of this Court
(Priestley v. Fowler, 3 M. & W. 1) that the mere relation of master
and servant does not create any implied duty on the part of the
master to take more care of the servant than he may reasonably be
expected to do of himself. That decision has been followed by several
cases,[167] and is now established law, though I believe the principle
was not recognized until recent times. The reason for the rule is that
the servant undertakes to run all the ordinary risks of service,
including those arising from the negligence of his fellow-servants.
The rule applies to all the members of a domestic establishment, so
that the master is not in general liable to a servant for injury
resulting from the negligence of a fellow-servant; neither can one
servant maintain an action against another for negligence whilst
engaged in their common employment. The same principle applies to
the case of a visitor at a house; whilst he remains there he is in the
same position as any other member of the establishment, so far as
regards the negligence of the master or his servants, and he must
take his chance with the rest.
Alderson, B. I am of the same opinion.
Bramwell, B. I agree with Mr. Gray to this extent, that where a
person is in the house of another, either on business or for any other
purpose, he has a right to expect that the owner of the house will take
reasonable care to protect him from injury; for instance, that he will
not allow a trap-door to be open through which the visitor may fall.
But in this case my difficulty is to see that the declaration charges
any act of commission. If a person asked another to walk in his
garden, in which he had placed spring-guns or men-traps, and the
latter, not being aware of it, was thereby injured, that would be an
act of commission. But if a person asked a visitor to sleep at his
house, and the former omitted to see that the sheets were properly
aired, whereby the visitor caught cold, he could maintain no action,
for there was no act of commission, but simply an act of omission.
This declaration merely alleges that “by and through the mere
carelessness, negligence, default, and improper conduct of the
defendant,” the glass fell from the door. That means a want of care,—
a default in not doing something. The words are all negatives, and
under these circumstances the action is not maintainable. I doubted
whether the words “carelessness, negligence, and improper conduct,”
&c., might not mean something equivalent to actual commission, but
on the best consideration which I can give the subject, it appears to
me that they do not mean that, but merely point to a negative. If I
misconstrue the declaration it is the fault of those who so framed it.
Judgment for the defendant.[168]

BEEHLER v. DANIELS
Supreme Court, Rhode Island, May 1, 1894.
Reported in 18 Rhode Island Reports, 563.

Trespass on the Case. Certified from the Common Pleas Division


on demurrer to the declaration.
Stiness, J. The plaintiff seeks to recover for injury caused by
falling into an elevator well in the defendants’ building, which he
entered in the discharge of his duty, as a member of the fire
department of the city of Providence, in answering a call to
extinguish a fire. The negligence alleged in the first count is a failure
to guard and protect the well; and in the second count such a packing
of merchandise as to guide and conduct one to the unguarded and
unprotected well. The defendants demur to the declaration, alleging
as grounds of demurrer that they owed no duty to the plaintiff; that
he entered their premises in the discharge of a public duty and
assumed the risks of his employment; that he was in the premises
without invitation from them; and that they are not liable for
consequences which they could not and were not bound to foresee.
The decisive question thus raised is, Did the defendants, under the
circumstances, owe to the plaintiff a duty, for failure in which they
are liable to him in damages? The question is not a new one, and we
think it is safe to say that it has never been answered otherwise than
in favor of the defendants. The plaintiff argues that it was his duty to
enter the premises, and, consequently, since an owner may
reasonably anticipate the liability of a fire, a duty arises from the
owner to the fireman to keep his premises guarded and safe. An
extension of this argument to its legitimate result, as a rule of law, is
sufficiently startling to show its unsoundness. The liability to fire is
common to all buildings and at all times. Hence every owner of every
building must at all times keep every part of his property, in such
condition, that a fireman, unacquainted with the place, and groping
about in darkness and smoke, shall come upon no obstacle, opening,
machine or anything whatever which may cause him injury. This
argument was urged in Woodruff v. Bowen, 136 Ind. 431; but the
court said: “We are of the opinion that the owner of a building in a
populous city does not owe it as a duty at common law, independent
of any statute or ordinance, to keep such building safe for firemen or
other officers, who, in a contingency, may enter the same under a
license conferred by law.”
Undoubtedly the plaintiff in this case had the right to enter the
defendants’ premises, and the character of his entry was that of a
licensee. Cooley on Torts, *313. But no such duty as is averred in this
declaration is due from an owner to a licensee. This question is
discussed in the case just cited, as also in many others. For example,
in Reardon v. Thompson, 149 Mass. 267, Holmes, J., says: “But the
general rule is that a licensee goes upon land at his own risk, and
must take the premises as he finds them. An open hole, which is not
concealed otherwise than by the darkness of the night, is a danger
which a licensee must avoid at his peril.” So in Mathews v. Bensel, 51
N. J. Law, 30, Beasley, C. J., says: “The substantial ground of
complaint laid in the count is, that the defendants did not properly
construct their planer, and, being a dangerous instrument, did not
surround it with proper safeguards. But there is no legal principle
that imposes such a duty as this on the owner of property with
respect to a mere licensee. This is the recognized rule. In the case of
Holmes v. Northeastern Railway Co., L. R. 4 Exch. 254, 256, Baron
Channell says: ‘That where a person is a mere licensee he has no
cause of action on account of the dangers existing in the place he is
permitted to enter.’” In Parker v. Portland Publishing Co., 69 Me.
173, this question is fully examined, the court holding it to be well
settled, if the plaintiff was at the place where the injury was received
by license merely, that the defendant would owe him no duty and
that he could not recover. See also Indiana, etc., Railway Co. v.
Barnhart, 115 Ind. 399; Gibson v. Leonard, 37 Ill. App. 344; Bedell v.
Berkey, 76 Mich. 435.
There is a clear distinction between a license and an invitation to
enter premises, and an equally clear distinction as to the duty of an
owner in the two cases. An owner owes to a licensee no duty as to the
condition of premises, unless imposed by statute, save that he should
not knowingly let him run upon a hidden peril or wilfully cause him
harm; while to one invited he is under obligation for reasonable
security for the purposes of the invitation. The plaintiff’s declaration
does not set out a cause of action upon either of these grounds, and
the cases cited and relied on by him fall within the two classes of
cases described, and mark the line of duty very clearly. Parker v.
Barnard, 135 Mass. 116, was the case of a police officer who had
entered a building, the doors of which were found open in the night
time, to inspect it according to the rules of the police department,
and fell down an unguarded elevator well. A statute required such
wells to be protected by railings and trap-doors. Judgment having
been given for the defendant at the trial, a new trial was ordered
upon the ground of a violation of statute. The court says: “The owner
or occupant of land or a building is not liable, at common law, for
obstructions, pitfalls, or other dangers there existing, as, in the
absence of any inducement or invitation to others to enter, he may
use his property as he pleases. But he holds his property ‘subject to
such reasonable control and regulation of the mode of keeping and
use as the legislature, under the police power vested in them by the
Constitution of the Commonwealth, may think necessary for the
preventing of injuries to the rights of others and the security of the
public health and welfare.’” Then, likening the plaintiff to a fireman,
the court also says: “Even if they must encounter the danger arising
from neglect of such precautions against obstructions and pitfalls as
those invited or induced to enter have a right to expect, they may
demand, as against the owners or occupants, that they observe the
statute in the construction and management of their building.” In
Learoyd v. Godfrey, 138 Mass. 315, a police officer fell down an
uncovered well in or near a passageway to a house where he was
called to quell a disturbance of the peace. A verdict for the plaintiff
was sustained upon the ground that the jury must have found that
the officer was using the passageway by the defendant’s invitation
and that the evidence warranted the finding. Gordon v. Cummings,
152 Mass. 513, was the case of a letter carrier who fell into an elevator
well, in a hallway where he was accustomed to leave letters in boxes
put there for that purpose. The court held that there was an implied
invitation to the carrier to enter the premises. In Engel v. Smith, 82
Mich. 1, the plaintiff fell through a trap-door left open in a building
where he was employed. The question of duty is not discussed in the
case but simply the fact of negligence. In Bennett v. Railroad Co., 102
U. S. 577, the plaintiff, a passenger, fell through a hatch hole in the
depot floor. The court construed the declaration as setting out facts
which amounted to an invitation to the plaintiff to pass over the
route which he took through the shed depot where the hatch hole
was.
In the present case the plaintiff sets out no violation of a statute, or
facts which amount to an invitation, and, consequently, under the
well-settled rule of law, the defendants were under no liability to him
for the condition of their premises or the packing of their
merchandise. The demurrer to the declaration must therefore be
sustained.[169]
Section VII
Liability to Third Persons of Maker or Vendor of a
Chattel

WINTERBOTTOM v. WRIGHT
In the Exchequer, June 6, 1842.
Reported in 10 Meeson & Welsby, 109.

Case. The declaration stated, that the defendant was a contractor


for the supply of mail-coaches, and had in that character contracted
for hire and reward with the Postmaster-General, to provide the
mail-coach for the purpose of conveying the mail-bags from
Hartford, in the county of Chester, to Holyhead: That the defendant,
under and by virtue of the said contract, had agreed with the said
Postmaster-General that the said mail-coach should, during the said
contract, be kept in a fit, proper, safe, and secure state and condition
for the said purpose, and took upon himself, to wit, under and by
virtue of the said contract, the sole and exclusive duty, charge, care,
and burden of the repairs, state, and condition of the said mail-
coach; and it had become and was the sole and exclusive duty of the
defendant, to wit, under and by virtue of his said contract, to keep
and maintain the said mail-coach in a fit, proper, safe, and secure
state and condition for the purpose aforesaid: That Nathaniel
Atkinson and other persons, having notice of the said contract, were
under contract with the Postmaster-General to convey the said mail-
coach from Hartford to Holyhead, and to supply horses and
coachmen for that purpose, and also not, on any pretence whatever,
to use or employ any other coach or carriage whatever than such as
should be so provided, directed, and appointed by the Postmaster-
General: That the plaintiff, being a mail-coachman, and thereby
obtaining his livelihood, and whilst the said several contracts were in
force, having notice thereof, and trusting to and confiding in the
contract made between the defendant and the Postmaster-General,
and believing that the said coach was in a fit, safe, secure, and proper
state and condition for the purpose aforesaid, and not knowing and
having no means of knowing to the contrary thereof, hired himself to
the said Nathaniel Atkinson and his co-contractors as mail-
coachman, to drive and take the conduct of the said mail-coach,
which but for the said contract of the defendant he would not have
done. The declaration then averred, that the defendant so improperly
and negligently conducted himself, and so utterly disregarded his
aforesaid contract, and so wholly neglected and failed to perform his
duty in this behalf, that heretofore, to wit, on the 8th of August,
1840, whilst the plaintiff, as such mail-coachman so hired, was
driving the said mail-coach from Hartford to Holyhead, the same
coach, being a mail-coach found and provided by the defendant
under his said contract, and the defendant then acting under his said
contract, and having the means of knowing and then well knowing all
the aforesaid premises, the said mail-coach being then in a frail,
weak, infirm, and dangerous state and condition, to wit, by and
through certain latent defects in the state and condition thereof, and
unsafe and unfit for the use and purpose aforesaid, and from no
other cause, circumstance, matter, or thing whatsoever gave way and
broke down, whereby the plaintiff was thrown from his seat, and, in
consequence of injuries then received, had become lamed for life.
To this declaration the defendant pleaded several pleas, to two of
which there were demurrers; but, as the Court gave no opinion as to
their validity, it is not necessary to state them.
Peacock, who appeared in support of the demurrers, having
argued against the sufficiency of the pleas,—
Byles, for the defendant, objected that the declaration was bad in
substance. This is an action brought, not against Atkinson and his
co-contractors, who were the employers of the plaintiff, but against
the person employed by the Postmaster-General, and totally
unconnected with them or with the plaintiff. Now it is a general rule,
that wherever a wrong arises merely out of the breach of a contract,
which is the case on the face of this declaration, whether the form in
which the action is conceived be ex contractu or ex delicto, the party
who made the contract alone can sue: Tollit v. Sherstone, 5 M. & W.
283. If the rule were otherwise, and privity of contract were not
requisite, there would be no limit to such actions. If the plaintiff may,
as in this case, run through the length of three contracts, he may run
through any number or series of them; and the most alarming
consequences would follow the adoption of such a principle. Levy v.
Langridge, 4 M. & W. 337, will probably be referred to on the other
side. But that case was expressly decided on the ground that the
defendant, who sold the gun by which the plaintiff was injured,
although he did not personally contract with the plaintiff, who was a
minor, knew that it was bought to be used by him. Here there is no
allegation that the defendant knew that the coach was to be driven by
the plaintiff. There, moreover, fraud was alleged in the declaration,
and found by the jury: and there, too, the cause of injury was a
weapon of a dangerous nature, and the defendant was alleged to
have had notice of the defect in its construction. Nothing of that sort
appears upon this declaration.
Peacock, contra. This case is within the principle of the decision in
Levy v. Langridge. Here the defendant entered into a contract with a
public officer to supply an article which, if imperfectly constructed,
was necessarily dangerous, and which, from its nature and the use
for which it was destined, was necessarily to be driven by a
coachman. That is sufficient to bring the case within the rule
established by Levy v. Langridge. In that case the contract made by
the father of the plaintiff with the defendant was made on behalf of
himself and his family generally, and there was nothing to show that
the defendant was aware even of the existence of the particular son
who was injured. Suppose a party made a contract with government
for a supply of muskets, one of which, from its misconstruction,
burst and injured a soldier: there it is clear that the use of the
weapon by a soldier would have been contemplated, although not by
the particular individual who received the injury, and could it be
said, since the decision in Levy v. Langridge, that he could not
maintain an action against the contractor? So, if a coachmaker,
employed to put on the wheels of a carriage, did it so negligently that
one of them flew off, and a child of the owner were thereby injured,
the damage being the natural and immediate consequence of his
negligence, he would surely be responsible. So, if a party entered into
a contract to repair a church, a workhouse, or other public building,
and did it so insufficiently that a person attending the former, or a
pauper in the latter, were injured by the falling of a stone, he could
not maintain an action against any other person than the contractor;
but against him he must surely have a remedy. It is like the case of a
contractor who negligently leaves open a sewer, whereby a person
passing along the street is injured. It is clear that no action could be
maintained against the Postmaster-General: Hall v. Smith, 2 Bing.
156; Humphreys v. Mears, 1 Man. & R. 187; Priestly v. Fowler. But
here the declaration alleges the accident to have happened through
the defendant’s negligence and want of care. The plaintiff had no
opportunity of seeing that the carriage was sound and secure.
[Alderson, B. The decision in Levy v. Langridge proceeds upon the
ground of the knowledge and fraud of the defendant.] Here also
there was fraud: the defendant represented the coach to be in a
proper state for use, and whether he represented that which was false
within his knowledge, or a fact as true which he did not know to be
so, it was equally a fraud in point of law, for which he is responsible.
Lord Abinger, C. B. I am clearly of opinion that the defendant is
entitled to our judgment. We ought not to permit a doubt to rest
upon this subject, for our doing so might be the means of letting in
upon us an infinity of actions. This is an action of the first
impression, and it has been brought in spite of the precautions which
were taken, in the judgment of this Court in the case of Levy v.
Langridge, to obviate any notion that such an action could be
maintained. We ought not to attempt to extend the principle of that
decision, which, although it has been cited in support of this action,
wholly fails as an authority in its favor; for there the gun was bought
for the use of the son, the plaintiff in that action, who could not make
the bargain himself, but was really and substantially the party
contracting. Here the action is brought simply because the defendant
was a contractor with a third person; and it is contended that
thereupon he became liable to everybody who might use the carriage.
If there had been any ground for such an action, there certainly
would have been some precedent of it; but with the exception of
actions against innkeepers, and some few other persons, no case of a
similar nature has occurred in practice. That is a strong
circumstance, and is of itself a great authority against its
maintenance. It is however contended, that this contract being made
on the behalf of the public by the Postmaster-General, no action
could be maintained against him, and therefore the plaintiff must
have a remedy against the defendant. But that is by no means a
necessary consequence,—he may be remediless altogether. There is
no privity of contract between these parties; and if the plaintiff can
sue, every passenger, or even any person passing along the road, who
was injured by the upsetting of the coach, might bring a similar
action. Unless we confine the operation of such contracts as this to
the parties who entered into them, the most absurd and outrageous
consequences, to which I can see no limit, would ensue. Where a
party becomes responsible to the public, by undertaking a public
duty, he is liable, though the injury may have arisen from the
negligence of his servant or agent. So, in cases of public nuisances,
whether the act was done by the party as a servant, or in any other
capacity, you are liable to an action at the suit of any person who
suffers. Those, however, are cases where the real ground of the
liability is the public duty, or the commission of the public nuisance.
There is also a class of cases in which the law permits a contract to be
turned into a tort; but unless there has been some public duty
undertaken, or public nuisance committed, they are all cases in
which an action might have been maintained upon the contract.
Thus, a carrier may be sued either in assumpsit or case; but there is
no instance in which a party, who was not privy to the contract
entered into with him, can maintain any such action. The plaintiff in
this case could not have brought an action on the contract; if he
could have done so, what would have been his situation supposing
the Postmaster-General had released the defendant? That would, at
all events, have defeated his claim altogether. By permitting this
action, we should be working this injustice, that after the defendant
had done everything to the satisfaction of his employer, and after all
matters between them had been adjusted, and all accounts settled on
the footing of their contract, we should subject them to be ripped
open by this action of tort being brought against him.
Alderson, B. I am of the same opinion. The contract in this case
was made with the Postmaster-General alone; and the case is just the
same as if he had come to the defendant and ordered a carriage, and
handed it at once over to Atkinson. If we were to hold that the
plaintiff could sue in such a case, there is no point at which such
actions would stop. The only safe rule is to confine the right to
recover to those who enter into the contract: if we go one step
beyond that, there is no reason why we should not go fifty. The only
real argument in favor of the action is, that this is a case of hardship;
but that might have been obviated, if the plaintiff had made himself a
party to the contract. Then it is urged that it falls within the principle
of the case of Levy v. Langridge. But the principle of that case was
simply this, that the father having bought the gun for the very
purpose of being used by the plaintiff, the defendant made
representations by which he was induced to use it. There, a distinct
fraud was committed on the plaintiff; the falsehood of the
representation was also alleged to have been within the knowledge of
the defendant who made it, and he was properly held liable for the
consequences. How are the facts of that case applicable to those of
the present? Where is the allegation of misrepresentation or fraud in
this declaration? It shows nothing of the kind. Our judgment must
therefore be for the defendant.
Gurney, B., concurred.
Rolfe, B. The breach of the defendant’s duty, stated in this
declaration, is his omission to keep the carriage in a safe condition;
and when we examine the mode in which that duty is alleged to have
arisen, we find a statement that the defendant took upon himself, to
wit, under and by virtue of the said contract, the sole and exclusive
duty, charge, care, and burden of the repairs, state, and condition of
the said mail-coach, and, during all the time aforesaid, it had become
and was the sole and exclusive duty of the defendant, to wit, under
and by virtue of his said contract, to keep and maintain the said mail-
coach in a fit, proper, safe, and secure state and condition. The duty,
therefore, is shown to have arisen solely from the contract; and the
fallacy consists in the use of that word “duty.” If a duty to the
Postmaster-General be meant, that is true; but if a duty to the
plaintiff be intended (and in that sense the word is evidently used),
there was none. This is one of those unfortunate cases in which there
certainly has been damnum, but it is damnum absque injuria; it is,
no doubt, a hardship upon the plaintiff to be without a remedy, but,
by that consideration we ought not to be influenced. Hard cases, it
has been frequently observed, are apt to introduce bad law.
Judgment for the defendant.[170]

BLOOD BALM COMPANY v. COOPER


Supreme Court, Georgia, October 14, 1889.
Reported in 83 Georgia Reports, 857.

Action by Cooper against Blood Balm Company in the City Court


of Atlanta. Verdict for plaintiff. Defendants brought error.[171]
Blandford, J. The main question in this case arises upon the
refusal of the Court below to award a nonsuit, and the solution of this
question depends upon whether, where one prepares what is known
as a proprietary or patent medicine, and puts it upon the market and
recommends it to the world as useful for the cure of certain diseases,
the bottle containing it having therewith a prescription made by the
proprietor of the medicine, in which he states that it is to be taken in
certain quantities, and such medicine, accompanied with this
prescription, is sold by the proprietor to a druggist for the purpose of
being resold to persons who might wish to use it, and the druggist
sells the same to a person who uses it in the quantity thus prescribed,
and it being shown that the same contains a certain article known as
the iodide of potash in such quantity as proves harmful to the person
thus using, the proprietor is liable. The plaintiff in error insists that
there is no liability on the part of the proprietor, (1) because it was
not sold by the proprietor to the person injured, but by a druggist
who had purchased the same from the proprietor; and several cases
are cited to sustain this position; (2) because the drug thus sold was
not imminently hurtful or poisonous.
1. We are not aware of any decision of this Court upon this
question, indeed there is none; and we have searched carefully not
only the authorities cited by counsel in this case, but others, and we
find no question like the one which arises in this record determined
by any Court. In the case of Thomas v. Winchester, 6 N. Y. (2 Seld.)
397, 57 Am. Dec. 455, 1 Thompson, Neg. 224, referred to by counsel
in this case, the question decided was, that a dealer in drugs and
medicines who carelessly labels a deadly poison as a harmless
medicine, and sends it so labelled into market, is liable to all persons
who, without fault on their part, are injured by using it as such
medicine in consequence of the false label. This comes nearer the
present case than any we have been able to find, and it is relied upon
by both parties as an authority; and in the notes thereto by Mr.
Freeman in the American Decisions, the cases relied upon by counsel
in this case are embraced and referred to, and to some extent
considered. It is not denied by counsel in this case that the doctrine
of the case cited (Thomas v. Winchester) is sound and correct law,
but the present case differs from that case, and mainly in this: there
the drug sold was a deadly poison, and the wrong consisted in
putting a label upon the same which indicated that it was a harmless
medicine; whereas in this case the medicine sold was not a deadly
poison, and no label was put upon it which was calculated to deceive
any one in this respect. But accompanying this medicine was a
prescription of the proprietor stating the quantity to be taken, and
the evidence tended to show that the quantity thus prescribed
contained iodide of potash to such an extent as, when taken by the
plaintiff, produced the injury and damage complained of. The
liability of the plaintiff in error to the person injured arises, not by
contract, but for a wrong committed by the proprietor in the
prescription and direction as to the dose that should be taken.
We can see no difference whether the medicine was directly sold to
the defendant in error by the proprietor, or by an intermediate party
to whom the proprietors had sold it in the first instance for the
purpose of being sold again. It was put upon the market by the
proprietor, not alone for the use of druggists to whom they might sell
it, but to be used by the public in general who might need the same
for the cure of certain diseases for which the proprietor set forth in
his label the same was adapted. This was the same thing as if the
proprietor himself had sold this medicine to the defendant in error,
with his instructions and directions as to how the same should be
taken. In all the cases cited by the plaintiff in error there is no case in
which the proprietor prescribed the doses and quantities to be taken
of the medicine sold by him. If this medicine contained the iodide of
potassium in sufficient quantity to produce the injurious
consequences complained of to the defendant in error, and if the
same was administered to him, either by himself or any other person,
as prescribed in the label accompanying the medicine, he could, in
our judgment, recover for any injury he may have sustained on
account of the poisonous effect thereof. It was a wrong on the part of
the proprietor to extend to the public generally an invitation to take
the medicine in quantities sufficient to injure and damage persons
who might take it.
A medicine which is known to the public as being dangerous and
poisonous if taken in large quantities, may be sold by the proprietor
to druggists and others, and if any person, without more, should
purchase and take the same so as to cause injury to himself, the
proprietor would not be liable. But if the contents of a medicine are
concealed from the public generally, and the medicine is prepared by
one who know its contents, and he sells the same, recommending it
for certain diseases and prescribing the mode in which it shall be
taken, and injury is thereby sustained by the person taking the same,
the proprietor would be liable for the damage thus sustained. These
proprietary or patent medicines are secret, or intended by the
proprietors to be secret, as to their contents. They expect to derive a
profit from such secrecy. They are therefore liable for all injuries
sustained by any one who takes their medicine in such quantities as
may be prescribed by them. There is no way for a person who uses
the medicine to ascertain what its contents are, ordinarily, and in
this case the contents were only ascertained after an analysis made
by a chemist,—which would be very inconvenient and expensive to
the public; nor would it be the duty of a person using the medicine to
ascertain what poisonous drugs it may contain. He has a right to rely
upon the statement and recommendation of the proprietor, printed
and published to the world; and if thus relying, he takes the medicine
and is injured on account of some concealed drug of which he is
unaware, the proprietor is not free from fault, and is liable for the
injury thereby sustained. It appears from the analysis made by the
chemist in this case that this medicine contained 25 grains of the
iodide of potash to two tablespoonfuls of the medicine. The
testimony of the plaintiff, by witnesses learned in the profession of
medicine, was that iodide of potash in this quantity would produce
the effects upon a person using it shown by the condition of the
defendant in error. The prescription accompanying the bottle
directed the taking of one to two tablespoonfuls of the medicine, and
this was done by the defendant in error, and he was thereby greatly
injured and damaged.
This is not like the case of a dangerous machine or a gun sold to a
person and by him given or sold to another, as in some of the cases
referred to. Mr. Freeman, in his notes to the case above referred to
(Thomas v. Winchester), alludes to all those cases; and Mr.
Thompson, in his work on Negligence, refers to the same cases, and
they are there fully discussed.
Judgment affirmed.

[Remainder of opinion omitted.]


HUSET v. J. I. CASE THRESHING MACHINE CO.
Circuit Court of Appeals, Eighth Circuit, February 26, 1903.
Reported in 120 Federal Reporter, 865.

Sanborn, Circuit Judge:[172]


Is a manufacturer or vendor of an article or machine which he
knows, when he sells it, to be imminently dangerous, by reason of a
concealed defect therein, to the life and limbs of any one who shall
use it for the purpose for which it was made and intended, liable to a
stranger to the contract of sale for an injury which he sustains from
the concealed defect while he is lawfully applying the article or
machine to its intended use?
The argument of this question has traversed the whole field in
which the liability of contractors, manufacturers, and vendors to
strangers to their contracts for negligence in the construction or sale
of their articles has been contested. The decisions which have been
cited are not entirely harmonious, and it is impossible to reconcile all
of them with any established rule of law. And yet the underlying
principle of the law of negligence, that it is the duty of every one to so
act himself and to so use his property as to do no unnecessary
damage to his neighbors, leads us fairly through the maze. With this
fundamental principle in mind, if we contemplate the familiar rules
that every one is liable for the natural and probable effects of his
acts; that negligence is a breach of a duty; that an injury that is the
natural and probable consequence of an act of negligence is
actionable, while one that could not have been foreseen or
reasonably anticipated as the probable effect of such an act is not
actionable, because the act of negligence in such a case is the remote,
and not the proximate, cause of the injury; and that, for the same
reason, an injury is not actionable which would not have resulted
from an act of negligence except from the interposition of an
independent cause (Chicago, St. Paul, Minneapolis & Omaha R. Co.
v. Elliott, 55 Fed. 949, 5 C. C. A. 347, 20 L. R. A. 582)—nearly all the
decisions upon this subject range themselves along symmetrical
lines, and establish rational rules of the law of negligence consistent
with the basic principles upon which it rests.
Actions for negligence are for breaches of duty. Actions on
contracts are for breaches of agreements. Hence the limits of liability
for negligence are not the limits of liability for breaches of contracts,
and actions for negligence often accrue where actions upon contracts
do not arise, and vice versa. It is a rational and fair deduction from
the rules to which brief reference has been made that one who makes
or sells a machine, a building, a tool, or an article of merchandise
designed and fitted for a specific use is liable to the person who, in
the natural course of events, uses it for the purpose for which it was
made or sold, for an injury which is the natural and probable
consequence of sale. But when a contractor builds a house or a
bridge, or a manufacturer constructs a car or a carriage, for the
owner thereof under a special contract with him, an injury to any
other person than the owner for whom the article is built and to
whom it is delivered cannot ordinarily be foreseen or reasonably
anticipated as the probable result of the negligence in its
construction. So, when a manufacturer sells articles to the wholesale
or retail dealers, or to those who are to use them, injury to third
persons is not generally the natural or probable effect of negligence
in their manufacture, because (1) such a result cannot ordinarily be
reasonably anticipated, and because (2) an independent cause—the
responsible human agency of the purchaser—without which the
injury to the third person would not occur, intervenes, and, as
Wharton says, “insulates” the negligence of the manufacturer from
the injury to the third person. Wharton on Law of Negligence (2d
ed.) § 134. For the reason that in the cases of the character which
have been mentioned the natural and probable effect of the
negligence of the contractor or manufacturer will generally be
limited to the party for whom the article is constructed, or to whom it
is sold, and, perhaps more than all this, for the reason that a wise
and conservative public policy has impressed the courts with the
view that there must be a fixed and definite limitation to the liability
of manufacturers and vendors for negligence in the construction and
sale of complicated machines and structures which are to be
operated or used by the intelligent and the ignorant, the skilful and
the incompetent, the watchful and the careless, parties that cannot
be known to the manufacturers or vendors, and who use the articles
all over the country hundreds of miles distant from the place of their
manufacture or original sale, a general rule has been adopted and
has become established by repeated decisions of the courts of
England and of this country that in these cases the liability of the
contractor or manufacturer for negligence in the construction or sale
of the articles which he makes or vends is limited to the persons to
whom he is liable under his contracts of construction or sale. The
limits of the liability for negligence and for breaches of contract in
cases of this character are held to be identical. The general rule is
that a contractor, manufacturer, or vendor is not liable to third
parties who have no contractual relations with him for negligence in
the construction, manufacture, or sale of the articles he handles.
Winterbottom v. Wright, 10 M. & W. 109; Longmeid v. Holliday, 6
Exch. 764, 765; Blakemore v. Ry. Co., 8 El. & Bl. 1035; Collis v.
Selden, L. R. 3 C. P. 495, 497; Bank v. Ward, 100 U. S. 195, 204, 25 L.
Ed. 621; Bragdon v. Perkins-Campbell Co., 87 Fed. 109, 30 C. C. A.
567; Goodlander v. Standard Oil Co., 63 Fed. 400, 406, 11 C. C. A.
253, 259, 27 L. R. A. 583; Loop v. Litchfield, 42 N. Y. 351, 359, 1 Am.
Rep. 513; Losee v. Clute, 51 N. Y. 494, 10 Am. Rep. 623; Curtain v.
Somerset, 140 Pa. 70, 21 Atl. 244, 12 L. R. A. 322, 23 Am. St. Rep.
220; Heizer v. Kingsland & Douglass Mfg. Co., 110 Mo. 605, 615, 617,
19 S. W. 630, 15 L. R. A. 821, 33 Am. St. Rep. 481; Daugherty v.
Herzog, 145 Ind. 255, 44 N. E. 457, 32 L. R. A. 837, 57 Am. St. Rep.
204; Burke v. De Castro, 11 Hun, 354; Swan v. Jackson, 55 Hun, 194,
7 N. Y. Supp. 821; Barrett v. Mfg. Co., 31 N. Y. Super. Ct. 545; Carter
v. Harden, 78 Me. 528, 7 Atl. 392; McCaffrey v. Mfg. Co., (R. I.) 50
Atl. 651, 55 L. R. A. 822; Marvin Safe Co. v. Ward, 46 N. J. Law, 19;
Burdick v. Cheadle, 26 Ohio St. 393, 20 Am. Rep. 767; Davidson v.
Nichols, 11 Allen, 514; J. I. Case Plow Works v. Niles & Scott Co.,
(Wis.) 63 N. W. 1013.
In these cases third parties, without any fault on their part, were
injured by the negligence of the manufacturer, vendor, or furnisher
of the following articles, while the parties thus injured were
innocently using them for the purposes for which they were made or
furnished, and the courts held that there could be no recovery,
because the makers, vendors, or furnishers owed no duty to
strangers to their contracts of construction, sale, or furnishing. A
stage-coach, Winterbottom v. Wright, 10 M. & W. 109; a leaky lamp,
Longmeid v. Holliday, 6 Exch. 764, 765; a defective chain furnished
one to lead stone, Blakemore v. Ry Co., 8 El. & Bl. 1035; an
improperly hung chandelier, Collis v. Selden, L. R. 3 C. P. 495, 497;
an attorney’s certificate of title, Bank v. Ward, 100 U. S. 195, 204, 25
L. Ed. 621; a defective valve in an oil car, Goodlander v. Standard Oil
Co., 63 Fed. 401, 406, 11 C. C. A. 253, 259, 27 L. R. A. 583; a porch on
a hotel, Curtain v. Somerset, 140 Pa. 70, 21 Atl. 244, 12 L. R. A. 322,
23 Am. St. Rep. 220; a defective side saddle, Bragdon v. Perkins-
Campbell Co., 87 Fed. 109, 30 C. C. A. 567; a defective rim in a
balance wheel, Loop v. Litchfield, 42 N. Y. 351, 359, 1 Am. Rep. 513; a
defective boiler, Losee v. Clute, 51 N. Y. 494, 10 Am. Rep. 623; a
defective cylinder in a threshing machine, Heizer v. Kingsland &
Douglass Mfg. Co., 110 Mo. 605, 615, 617, 19 S. W. 630, 15 L. R. A.
821, 33 Am. St. Rep. 481; a defective wall which fell on a pedestrian,
Daugherty v. Herzog, 145 Ind. 255, 44 N. E. 457, 32 L. R. A. 837, 57
Am. St. Rep. 204; a defective rope on a derrick, Burke v. Refining
Co., 11 Hun, 354; a defective shelf for a workman to stand upon in
placing ice in a box, Swan v. Jackson, 55 Hun, 194, 7 N. Y. Supp. 821;
a defective hoisting rope of an elevator, Barrett v. Mfg. Co., 31 N. Y.
Super. Ct. 545; a runaway horse, Carter v. Harden, 78 Me. 528, 7 Atl.
392; a defective hook holding a heavy weight in a drop press,
McCaffrey v. Mfg. Co., (R. I.) 50 Atl. 651, 55 L. R. A. 822; a defective
bridge, Marvin Safe Co. v. Ward, 46 N. J. Law, 19; shelves in a dry
goods store, whose fall injured a customer, Burdick v. Cheadle, 26
Ohio St. 393, 20 Am. Rep. 767; a staging erected by a contractor for
the use of his employees, McGuire v. McGee, (Pa.) 13 Atl. 551;
defective wheels, J. I. Case Plow Works v. Niles & Scott Co., (Wis.) 63
N. W. 1013.
In the leading case of Winterbottom v. Wright this rule is placed
upon the ground of public policy, upon the ground that there would
be no end of litigation if contractors and manufacturers were to be
held liable to third persons for every act of negligence in the
construction of the articles or machines they make after the parties
to whom they have sold them have received and accepted them. In
that case the defendant had made a contract with the Postmaster-
General to provide and keep in repair the stage-coach used to convey
the mail from Hartford to Holyhead. The coach broke down,
overturned, and injured the driver, who sued the contractor for the
injury resulting from his negligence. Lord Abinger, C. B., said:
“There is no privity of contract between these parties; and, if the
plaintiff can sue, every passenger, or even any person passing along
the road, who was injured by the upsetting of the coach, might bring
a similar action. Unless we confine the operation of such contracts as
this to the parties who entered into them, the most absurd and
outrageous consequences, to which I can see no limit, would ensue.”
Baron Alderson said:
“I am of the same opinion. The contract in this case was made with
the Postmaster-General alone; and the case is just the same as if he
had come to the defendant and ordered a carriage, and handed it at
once over to Atkinson. If we were to hold that the plaintiff could sue
in such a case, there is no point at which such actions would stop.
The only safe rule is to confine the right to recover to those who enter
into the contract. If we go one step beyond that, there is no reason
why we should not go fifty.”
The views expressed by the judges in this case have prevailed in
England and in the United States, with the exception of two decisions
which are in conflict with the leading case and with all the decisions
to which reference has been made. Those cases are Devlin v. Smith,
89 N. Y. 470, 42 Am. Rep. 311, in which Smith, a painter, employed
Stevenson, a contractor, to build a scaffold 90 feet in height, for the
express purpose of enabling the painter’s workmen to stand upon it
to paint the interior of the dome of a building, and the Court of
Appeals of New York held that Stevenson was liable to a workman of
Smith, the painter, who was injured by a fall, caused by the
negligence of Stevenson in the construction of the scaffold upon
which he was working; and Schubert v. J. R. Clark Co., 49 Minn. 331,
51 N. W. 1103, 15 L. R. A. 818, 32 Am. St. Rep. 559, in which a painter
purchased of a manufacturer a stepladder, and one of the painter’s
employees, who was injured by the breaking of a step caused by the
negligence of the manufacturer, was permitted to recover of the
latter for the injuries he had sustained. The decision in Devlin v.
Smith may, perhaps, be sustained on the ground that the workmen of
Smith were the real parties in interest in the contract, since
Stevenson was employed and expressly agreed to construct the
scaffold for their use. But the case of Schubert v. J. R. Clark Co. is in
direct conflict with the side saddle case, Bragdon v. Perkins-
Campbell Co., 87 Fed. 109, 30 C. C. A. 567; the porch case, Curtain v.
Somerset, 140 Pa. 70, 21 Atl. 244, 12 L. R. A. 322, 23 Am. St. Rep.
220; the defective cylinder case, Heizer v. Kingsland & Douglass Mfg.
Co., 110 Mo. 617, 19 S. W. 630, 15 L. R. A. 821, 33 Am. St. Rep. 481;
the defective hook case, McCaffrey v. Mfg. Co., (R. I.) 50 Atl. 651, 55
L. R. A. 822; and with the general rule upon which all these cases
stand.
It is, perhaps, the more remarkable that the current of decisions
throughout all the courts of England and the United States should be
so uniform and conclusive in support of this rule, and that there
should, in the multitude of opinions, be but one or two in conflict
with it, than it is that such sporadic cases should be found. They are
insufficient in themselves, or in the reasoning they contain, to
overthrow or shake the established rule which prevails throughout
the English-speaking nations.
But while this general rule is both established and settled, there
are, as is usually the case, exceptions to it as well defined and settled
as the rule itself. There are three exceptions to this rule.
The first is that an act of negligence of a manufacturer or vendor
which is imminently dangerous to the life or health of mankind, and
which is committed in the preparation or sale of an article intended
to preserve, destroy, or affect human life, is actionable by third
parties who suffer from the negligence. Dixon v. Bell, 5 Maule & Sel.
198; Thomas v. Winchester, 6 N. Y. 397, 57 Am. Dec. 455; Norton v.
Sewall, 106 Mass. 143, 8 Am. Rep. 298; Elkins v. McKean, 79 Pa.
493, 502; Bishop v. Weber, 139 Mass. 411, 1 N. E. 154, 52 Am. Rep.
715; Peters v. Johnson, (W. Va.) 41 S. E. 190, 191, 57 L. R. A. 428. The
leading case upon this subject is Thomas v. Winchester, 6 N. Y. 397,
57 Am. Dec. 455. A dealer in drugs sold to a druggist a jar of
belladonna, a deadly poison, and labelled it “Extract of Dandelion.”
The druggist filled a prescription of extract of dandelion, prepared by
a physician for his patient. The patient took the prescription thus
filled, and recovered of the wholesale dealer for the injuries she
sustained. In Norton v. Sewall, 106 Mass. 143, 8 Am. Rep. 298, a
recovery was had by a third party for the sale of laudanum as
rhubarb; in Bishop v. Weber, for the furnishing of poisonous food for
wholesome food; in Peters v. Johnson, for the sale of saltpetre for
epsom salts; and in Dixon v. Bell, for placing a loaded gun in the
hands of a child. In all these cases of sale the natural and probable
result of the act of negligence—nay, the inevitable result of it—was
not an injury to the party to whom the sales were made, but to those
who, after the purchasers had disposed of the articles, should
consume them. Hence these cases stand upon two well-established
principles of law: (1) That every one is bound to avoid acts or
omissions imminently dangerous to the lives of others, and (2) that
an injury which is the natural and probable result of an act of
negligence is actionable. It was the natural and probable result of the
negligence in these cases that the vendees would not suffer, but that
those who subsequently purchased the deleterious articles would
sustain the injuries resulting from the negligence of the
manufacturers or dealers who furnished them.
The second exception is that an owner’s act of negligence which
causes injury to one who is invited by him to use his defective
appliance upon the owner’s premises may form the basis of an action
against the owner. Coughtry v. Globe Woolen Co., 56 N. Y. 124, 15
Am. Rep. 387; Bright v. Barnett & Record Co., (Wis.) 60 N. W. 418,
420, 26 L. R. A. 524; Heaven v. Pender, L. R. 11 Q. B. Div. 503;
Roddy v. Railway Co., 104 Mo. 234, 241, 15 S. W. 1112, 12 L. R. A.
746, 24 Am. St. Rep. 333. In Coughtry v. Globe Woolen Co., 56 N. Y.
124, 15 Am. Rep. 387, the owner of a building employed Osborn &
Martin to construct a cornice, and agreed with them to furnish a
scaffold upon which their men could perform the work. He furnished
the scaffold and one of the employees of the contractors was injured
by the negligence of the owner in constructing the scaffold. The court
held that the act of the owner was an implied invitation to the
employees of Osborn & Martin to use the scaffold and imposed upon
him a liability for negligence in its erection. The other cases cited to
this exception are of a similar character.
The third exception to the rule is that one who sells or delivers an
article which he knows to be imminently dangerous to life or limb to
another without notice of its qualities is liable to any person who
suffers an injury therefrom which might have been reasonably
anticipated, whether there were any contractual relations between
the parties or not. Langridge v. Levy, 2 M. & W. 519, 4 M. & W. 337;
Wellington v. Oil Co., 104 Mass. 64, 67; Lewis v. Terry, (Cal.) 43 Pac.
398. In Langridge v. Levy, 2 M. & W. 519, a dealer sold a gun to the
father for the use of the son, and represented that it was a safe gun,
and made by one Nock. It was not made by Nock, was a defective
gun, and when the son discharged it, it exploded and injured him.
The son was permitted to recover, because the defendant had
knowingly sold the gun to the father for the purpose of being used by
the plaintiff by loading and discharging it, and had knowingly made a
false warranty that this might be safely done, and the plaintiff, on the
faith of that warranty, and believing it to be true, had used the gun,
and sustained the damages. The court said in conclusion:
“We therefore think that, as there is fraud, and damage, the result
of that fraud, not from an act remote and consequential, but one
contemplated by the defendant at the time as one of its results, the
party guilty of the fraud is responsible to the party injured.”
This case was affirmed in 4 M. & W. 337, on the ground that the
sale of the gun to the father for the use of the son with the knowledge
that it was not as represented was a fraud, which entitled the son to
recover the damages he had sustained.
In Wellington v. Oil Co., the defendants knowingly sold to one
Chase, a retail dealer, to be sold by him to his customers as oil,
naphtha, a dangerous and explosive liquid. Chase sold the naphtha
as oil, the plaintiff used it in a lamp for illuminating purposes, it
ignited and exploded, and he recovered of the wholesale dealer.
Judge Gray, later Mr. Justice Gray of the Supreme Court, said:
“It is well settled that a man who delivers an article, which he
knows to be dangerous or noxious, to another person, without notice
of its nature and qualities, is liable for an injury which may
reasonably be contemplated as likely to result, and which does in fact
result therefrom to that person or any other who is not himself in
fault. Thus a person who delivers a carboy, which he knows to
contain nitric acid, to a carrier, without informing him of the nature
of its contents, is liable for an injury occasioned by the leaking out of
the acid upon another carrier, to whom it is delivered by the first in
the ordinary course of business, to be carried to its destination.
Farrant v. Barnes, 11 C. B. (N. S.) 553. So a chemist who sells a bottle
of liquid, made up of ingredients known only to himself, representing
it to be fit to be used for washing the hair, and knowing that it is to
be used by the purchaser’s wife, is liable for an injury occasioned to
her by using it for washing her hair. George v. Skivington, Law Rep.
5 Ex. 1.”
In Lewis v. Terry, (Cal.) 43 Pac. 398, a dealer, knowing a folding
bed to be defective and unsafe, sold it to a Mr. Apperson without
informing him of the fact. His wife suffered a broken arm and other
severe injuries from the negligence of the dealer in the sale of the
bed, and recovered of him the damages she sustained.
The Supreme Court of Missouri, in Heizer v. Kingsland & Douglass
Mfg. Co., in which they held that the manufacturer was not liable to a
third person for negligence in the construction of the cylinder of a
threshing machine, which burst and injured him, said:
“Had the defendant sold this machine to Ellis, knowing that the
cylinder was defective, and for that reason dangerous, without
informing him of the defect, then the defendant would be liable even
to third persons not themselves in fault. Shearman & Redfield on
Negligence, (4th ed.) § 117.”
Turning now to the case in hand, it is no longer difficult to dispose
of it. The allegations of the complaint are that the defendant
prepared a covering for the cylinder of the threshing machine, which
was customarily and necessarily used by those who operated it to
walk upon, and which was so incapable of sustaining the least weight
that it would bend and collapse whenever any one stepped upon it;
that it concealed this defective and dangerous condition of the
threshing rig so that it could not be readily discovered by persons
engaged in operating or working upon it; that it knew that the
machine was in this imminently dangerous condition when it
shipped and supplied it to the employer of the plaintiff; and that the
plaintiff has sustained serious injury through this defect in its
construction. The case falls fairly within the third exception. It
portrays a negligence imminently dangerous to the lives and limbs of
those who should use the machine, a machine imminently dangerous
to the lives and limbs of all who should undertake to operate it, a
concealment of this dangerous condition, a knowledge of the
defendant when it was shipped and supplied to the employer of the
plaintiff that the rig was imminently dangerous to all who should use
it for the purpose for which it was made and sold, and consequent
damage to the plaintiff. It falls directly within the rule stated by Mr.
Justice Gray that when one delivers an article, which he knows to be
dangerous to another person, without notice of its nature and
qualities, he is liable for an injury which may be reasonably
contemplated as likely to result, and which does in fact result
therefrom, to that person or to any other who is not himself in fault.
The natural, probable, and inevitable result of the negligence
portrayed by this complaint in delivering this machine when it was
known to be in a condition so imminently dangerous to the lives and
limbs of those who should undertake to use it for the purpose for
which it was constructed was the death, or loss of one or more of the
limbs, of some of the operators. It is perhaps improbable that the
defendant was possessed of the knowledge of the imminently
dangerous character of this threshing machine when it delivered it,
and that upon the trial of the case it will be found to fall under the
general rule which has been announced in an earlier part of this
opinion. But upon the facts alleged in this complaint, the act of
delivering it to the purchaser with a knowledge and a concealment of
its dangerous condition was so flagrant a disregard of the rule that
one is bound to avoid any act imminently dangerous to the lives and
health of his fellows that it forms the basis of a good cause of action
in favor of any one who sustained injury therefrom.
The judgment of the Circuit Court must be reversed, and the cause
must be remanded to the court below for further proceedings not
inconsistent with the views expressed in this opinion.

HEAVEN v. PENDER
In the Court of Appeal, July 30, 1883.
Reported in 11 Queen’s Bench Division, 503.

Action to recover damages for injuries alleged to have been


sustained by the plaintiff through the negligence of the defendant.
The County Court judge gave judgment for the plaintiff. The Queen’s
Bench Division, on appeal, ordered judgment for defendant. The
plaintiff appealed to the Court of Appeal.[173]
Brett, M. R. In this case the plaintiff was a workman in the
employ of Gray, a ship-painter. Gray entered into a contract with a
shipowner whose ship was in the defendant’s dock to paint the
outside of his ship. The defendant, the dock-owner, supplied, under a
contract with the shipowner, an ordinary stage to be slung in the
ordinary way outside the ship for the purpose of painting her. It must
have been known to the defendant’s servants, if they had considered
the matter at all, that the stage would be put to immediate use, that it
would not be used by the shipowner, but that it would be used by
such a person as the plaintiff, a working ship-painter. The ropes by
which the stage was slung, and which were supplied as a part of the
instrument by the defendant, had been scorched and were unfit for
use, and were supplied without a reasonably careful attention to
their condition. When the plaintiff began to use the stage the ropes
broke, the stage fell, and the plaintiff was injured. The Divisional
Court held that the plaintiff could not recover against the defendant.
The plaintiff appealed. The action is in form and substance an action
for negligence. That the stage was, through want of attention of the
defendant’s servants, supplied in a state unsafe for use is not denied.
But want of attention amounting to a want of ordinary care is not a
good cause of action although injury ensue from such want, unless
the person charged with such want of ordinary care had a duty to the
person complaining to use ordinary care in the matter called in
question. Actionable negligence consists in the neglect of the use of
ordinary care or skill toward a person to whom the defendant owes
the duty of observing ordinary care and skill, by which neglect the
plaintiff, without contributory negligence on his part, has suffered
injury to his person or property. The question in this case is whether
the defendant owed such a duty to the plaintiff.
If a person contracts with another to use ordinary care or skill
toward him or his property, the obligation need not be considered in
the light of a duty; it is an obligation of contract. It is undoubted,
however, that there may be the obligation of such a duty from one
person to another although there is no contract between them with
regard to such duty. Two drivers meeting have no contract with each
other, but under certain circumstances they have a reciprocal duty
toward each other. So two ships navigating the sea. So a railway
company which has contracted with one person to carry another has
no contract with the person carried, but has a duty toward that
person. So the owner or occupier of a house or land who permits a
person or persons to come to his house or land has no contract with
such person or persons, but has a duty toward him or them. It should
be observed that the existence of a contract between two persons
does not prevent the existence of the suggested duty between them
also being raised by law independently of the contract, by the facts
with regard to which the contract is made and to which it applies an
exactly similar but a contract duty. We have not in this case to
consider the circumstances in which an implied contract may arise to
use ordinary care and skill to avoid danger to the safety of person or
property. We have not in this case to consider the question of a
fraudulent misrepresentation, express or implied, which is a well-
recognized head of law. The questions which we have to solve in this
case are: What is the proper definition of the relation between two
persons other than the relation established by contract, or fraud,
which imposes on one of them a duty toward the other to observe,
with regard to the person or property of such other, such ordinary
care or skill as may be necessary to prevent injury to his person or
property; and whether the present case falls within such definition?
When two drivers or two ships are approaching each other, such a
relation arises between them when they are approaching each other
in such a manner that, unless they use ordinary care and skill to
avoid it, there will be danger of an injurious collision between them.
This relation is established in such circumstances between them, not
only if it be proved that they actually know and think of this danger,
but whether such proof be made or not. It is established, as it seems
to me, because any one of ordinary sense who did think would at
once recognize that if he did not use ordinary care and skill under
such circumstances there would be such danger. And every one
ought, by the universally recognized rules of right and wrong, to
think so much with regard to the safety of others who may be
jeopardized by his conduct; and if, being in such circumstances, he
does not think, and in consequence neglects, or if he neglects to use
ordinary care and skill, and injury ensue, the law, which takes
cognizance of and enforces the rules of right and wrong, will force
him to give an indemnity for the injury. In the case of a railway
company carrying a passenger with whom it has not entered into the
contract of carriage, the law implies the duty, because it must be
obvious that unless ordinary care and skill be used the personal
safety of the passenger must be endangered. With regard to the
condition in which an owner or occupier leaves his house or property
other phraseology has been used, which it is necessary to consider. If
a man opens his shop or warehouse to customers it is said that he
invites them to enter, and that this invitation raises the relation
between them which imposes on the inviter the duty of using
reasonable care so to keep his house or warehouse that it may not
endanger the person or property of the person invited. This is in a
sense an accurate phrase, and as applied to the circumstances a
sufficiently accurate phrase. Yet it is not accurate if the word
“invitation” be used in its ordinary sense. By opening a shop you do
not really invite, you do not ask A. B. to come in to buy; you intimate
to him that if it pleases him to come in he will find things which you
are willing to sell. So in the case of shop, warehouse, road, or
premises, the phrase has been used that if you permit a person to
enter them you impose on yourself a duty not to lay a trap for him.
This, again, is in a sense a true statement of the duty arising from the
relation constituted by the permission to enter. It is not a statement
of what causes the relation which raises the duty. What causes the
relation is the permission to enter and the entry. But it is not a
strictly accurate statement of the duty. To lay a trap means in
ordinary language to do something with an intention. Yet it is clear
that the duty extends to a danger the result of negligence without
intention. And with regard to both these phrases, though each covers
the circumstances to which it is particularly applied, yet it does not
cover the other set of circumstances from which an exactly similar
legal liability is inferred. It follows, as it seems to me, that there must
be some larger proposition which involves and covers both sets of
circumstances. The logic of inductive reasoning requires that where
two major propositions lead to exactly similar minor premises there
must be a more remote and larger premise which embraces both of
the major propositions. That, in the present consideration, is, as it
seems to me, the same proposition which will cover the similar legal
liability inferred in the cases of collision and carriage. The
proposition which these recognized cases suggest, and which is,
therefore, to be deduced from them, is that whenever one person is
by circumstances placed in such a position with regard to another
that every one of ordinary sense who did think would at once
recognize that if he did not use ordinary care and skill in his own
conduct with regard to those circumstances he would cause danger of
injury to the person or property of the other, a duty arises to use
ordinary care and skill to avoid such danger. Without displacing the
other propositions to which allusion has been made as applicable to
the particular circumstances in respect of which they have been
enunciated, this proposition includes, I think, all the recognized
cases of liability. It is the only proposition which covers them all. It
may, therefore, safely be affirmed to be a true proposition, unless
some obvious case can be stated in which the liability must be
admitted to exist, and which yet is not within this proposition. There
is no such case. Let us apply this proposition to the case of one
person supplying goods or machinery or instruments or utensils, or
the like, for the purpose of their being used by another person, but
with whom there is no contract as to the supply. The proposition will
stand thus: whenever one person supplies goods, or machinery, or
the like, for the purpose of their being used by another person under
such circumstances that every one of ordinary sense would, if he
thought, recognize at once that unless he used ordinary care and skill
with regard to the condition of the thing supplied or the mode of
supplying it, there will be danger of injury to the person or property
of him for whose use the thing is supplied and who is to use it, a duty
arises to use ordinary care and skill as to the condition or manner of
supplying such thing. And for a neglect of such ordinary care or skill
whereby injury happens, a legal liability arises to be enforced by an
action for negligence. This includes the case of goods, etc., supplied
to be used immediately by a particular person or persons, or one of a
class of persons, where it would be obvious to the person supplying,
if he thought that the goods would in all probability be used at once
by such persons before a reasonable opportunity for discovering any
defect which might exist, and where the thing supplied would be of
such a nature that neglect of ordinary care or skill as to its condition
or the manner of supplying it would probably cause danger to the
person or property of the person for whose use it was supplied, and
who was about to use it. It would exclude a case in which the goods
are supplied under circumstances in which it would be a chance by
whom they would be used or whether they would be used or not, or
whether they would be used before there would probably be means
of observing any defect, or where the goods would be of such a
nature that a want of care or skill as to their condition or the manner
of supplying them would not probably produce danger of injury to
person or property. The cases of vendor and purchaser and lender
and hirer under contract need not be considered, as the liability
arises under the contract, and not merely as a duty imposed by law,
though it may not be useless to observe that it seems difficult to
import the implied obligation into the contract except in cases in
which if there were no contract between the parties the law would,
according to the rule above stated, imply the duty.
Examining the rule which has been above enunciated with the
cases which have been decided with regard to goods supplied for the
purpose of being used by persons with whom there is no contract, the
first case to be considered is inevitably Langridge v. Levy, 2 M. & W.
519; 4 id. 337. It is not an easy case to act upon. It is not, it cannot be,
accurately reported; the declaration is set out; the evidence is
assumed to be reported; the questions left to the jury are stated. And
then it is said that a motion was made to enter a nonsuit in
pursuance of leave reserved on particular grounds. These grounds do
not raise the question of fraud at all, but only the question of
remoteness. And although the question of fraud seems in a sense to
have been left to the jury, yet no question was, according to the
report, left to them as to whether the plaintiff acted on the faith of
the fraudulent misrepresentation, which is, nevertheless, a necessary
question in a case of fraudulent misrepresentation. The report of the
argument makes the object of the argument depend entirely upon an
assumed motion to arrest the judgment, which raises always a
discussion depending entirely on the form of the declaration, and the
effect on it of a verdict, in respect of which it is assumed that all
questions were left to the jury. If this was the point taken the report
of the evidence and of the questions left to the jury is idle! The case
was decided on the ground of a fraudulent misrepresentation as
stated in the declaration. It is inferred that the defendant intended
the representation to be communicated to the son. Why he should
have such an intention in fact it seems difficult to understand. His
immediate object must have been to induce the father to buy and pay
for the gun. It must have been wholly indifferent to him whether,
after the sale and payment, the gun would be used or not by the son.
I cannot hesitate to say that, in my opinion, the case is a wholly
unsatisfactory case to act on as an authority. But taking the case to be
decided on the ground of a fraudulent misrepresentation made
hypothetically to the son, and acted upon by him, such a decision
upon such a ground in no way negatives the proposition that the
action might have been supported on the ground of negligence
without fraud. It seems to be a case which is within the proposition
enunciated in this judgment, and in which the action might have
been supported without proof of actual fraud. And this seems to be
the meaning of Cleasby, B., in the observations he made on
Langridge v. Levy, supra, in the case of George v. Skivington, L. R. 5
Ex. 1, 5. In that case the proposition laid down in that judgment is
clearly adopted. The ground of the decision is that the article was, to
the knowledge of the defendant, supplied for the use of the wife and
for her immediate use. And certainly, if he or any one in his position
had thought at all, it must have been obvious that a want of ordinary
care or skill in preparing the prescription sold would endanger the
personal safety of the wife.
In Corby v. Hill, 4 C. B. (N. S.) 556, it is stated by the Lord Chief
Justice that an allurement was held out to the plaintiff. And Willes,
J., stated that the defendant had no right to set a trap for the
plaintiff. But in the form of declaration suggested by Willes, J., on p.
567, there is no mention of allurement, or invitation or trap. The
facts suggested in that form are, “that the plaintiff had license to go
on the road, that he was in consequence accustomed and likely to
pass along it, that the defendant knew of that custom and
probability, that the defendant negligently placed slates in such a
manner as to be likely to prove dangerous to persons driving along
the road, that the plaintiff drove along the road, being by reason of
the license lawfully on the road, and that he was injured by the
obstruction.” It is impossible to state a case more exactly within the
proposition laid down in this judgment. In Smith v. London & St.
Katharine Docks Co., L. R. 3 C. P. 326, the phrase is again used of
invitation to the plaintiff by the defendants. Again, let it be observed
that there is no objection to the phrase as applied to the case. But the
real value of the phrase may not improperly be said to be that
invitation imports knowledge by the defendant of the probable use
by the plaintiff of the article supplied, and therefore carries with it
the relation between the parties which establishes the duty. In
Indermaur v. Dames, L. R. 1 C. P. 274, L. R. 2 C. P. 311, reliance is
again placed upon a supposed invitation of the plaintiff by the
defendant. But, again, it is hardly possible to state facts which bring a
case more completely within the definition of the present judgment.
In Winterbottom v. Wright, 10 M. & W. 109, it was held that there
was no duty cast upon the defendant with regard to the plaintiff. The
case was decided on what was equivalent to a general demurrer to
the declaration. And the declaration does not seem to show that the
defendant, if he had thought about it, must have known, or ought to
have known, that the coach would be necessarily or probably driven
by the plaintiff, or by any class of which he could be said to be one, or
that it would be so driven within any time which would make it
probable that the defect would not be observed. The declaration

You might also like