Optics By Example
Optics By Example
Functional lenses in Haskell
About the Book
Hi! I'm Chris, the author of Optics By Example!
Optics By Example is a one-stop comprehensive guide to mastering optics in functional programming languages. It covers everything you need to know to go from complete beginner to advanced. Each topic is accompanied by copious examples and exercises!
See the Sample for a complete list of chapters, but here are some highlights:
- Complete introductions to Lenses, Folds, Traversals, Prisms and Isos
- Learn the magic of Indexed optics
- Composing Optics
- Lenses & Records
- Fixing "The Record Problem"
- Application design techniques using Classy optics
- Breakdowns of laws and limitations for each optic type
- Virtual lenses
- Validation lenses
- A guide to fully polymorphic optics
- A guide to "operator-style"
- Learn to query, filter, and aggregate data with surgical precision
- Learn how to use higher-order optics effectively
- Learn to write custom versions of all optics types for your own applications
- Manipulate data types with a clean and consistent interface
- Learn the monadic DSLs for using lenses in real monad stacks
WHY OPTICS?
Optics have become a wonderful and powerful new way of working with immutable data structures. They're almost a necessity at this point; and the benefits they bring in terms of re-usability, simplification of code maintenance & refactoring, and expressivity are immense! However, learning to use optics can be tricky or even intimidating at first, it's not always clear how to build up a large complicated mutation or query from the building blocks of optics. Optics by example is here to help!
This book is great as a first guide to optics, as a reference guide for discovering and mastering the optics you need for day-to-day problems, and as a springboard into new ideas and tools which you may not have even heard of.
Reader Testimonials
Riccardo Odone
Instabuy
Instabuy. Chris is one of the best FP mentors I've ever met. When I heard about the book I stopped reading anything else about optics. This is all I'm gonna need!
Evie Ciobanu
Great Pacing
I'm really happy Optics by Example is out! I've been programming in Haskell for almost two years and I've been mostly staying away from optics/lens until now due to their infamous errors and lack of good tutorials/references. This book is a great and thorough introduction, the pacing's great, and it's packed with fun exercises. I recommended it to all my colleagues, and I recommend it to anyone doing Haskell/FP!
Fintan Halpenny
Eye Opener
Optics by Example opened my eyes to the benefits of Lenses et al. First I was blind but now I see!
Chessai
I used to be an optics skeptic. Not skeptical that optics are useful, but skeptical that you could write maintainable _and_ widely approachable code using them. This book changed my mind. I now think that it _is_ possible to make optics, even the more powerful parts, approachable to people of all skill levels. Chris told me at some point that he had been teaching novices to be competent with lens, and at the time, I just didn't believe him. Now I do.
Table of Contents
-
1 Obligatory Preamble
- 1.1 Why should I read this book?
- 1.2 How to read this book
- 1.3 Chosen language and optics encodings
- 1.4 Your practice environment
- 1.5 Following examples
- 1.6 About the type signatures
- 1.7 About the exercises
-
2 Optics
- 2.1 What are optics?
- 2.2 Strengths
- 2.3 Weaknesses
- 2.4 Practical optics at a glance
- 2.5 Impractical optics at a glance
-
3 Lenses
-
3.1 Introduction to Lenses
- Anatomy
- Exercises – Optic Anatomy
-
3.2 Lens actions
- Viewing through lenses
- Setting through a lens
- Exercises - Lens Actions
-
3.3 Lenses and records
- Lenses subsume the “accessor” pattern
- Building a lens for a record field
- Exercises - Records Part One
- Getting and setting with a field lens
- Modifying fields with a lens
- Automatically generating field lenses
- Exercises - Records Part Two
-
3.4 Limitations
- Is it a Lens?
- Is it a Lens? – Answers
-
3.5 Lens Laws
- Why do optics have laws?
- The Laws
-
Case Study:
_1
-
Case Study:
msg
-
Case Study:
lensProduct
- Exercises - Laws
-
3.6 Virtual Fields
- What’s a virtual field
- Writing a virtual field
- Breakage-free refactoring
- Exercises – Virtual Fields
-
3.7 Data correction and maintaining invariants
- Including correction logic in lenses
- Exercises – Self-Correcting Lenses
-
3.1 Introduction to Lenses
-
4 Polymorphic Optics
-
4.1 Introduction to polymorphic optics
- Simple vs Polymorphic optics
-
4.2 When do we need polymorphic lenses
- Type-changing focuses
- Changing type variables with polymorphic lenses
- Exercises – Polymorphic Lenses
-
4.3 Composing Lenses
- How do I update fields in deeply nested records?
- Composing update functions
- Composing Lenses
- How do Lens Types Compose?
- Exercises – Lens Composition
-
4.1 Introduction to polymorphic optics
-
5 Operators
- 5.1 Lens Operators
-
5.2
view
a.k.a.^.
-
5.3
set
a.k.a..~
- 5.4 Chaining many operations
-
5.5 Using
%~
a.k.a.over
- 5.6 Learning Hieroglyphics
- 5.7 Modifiers
- 5.8 When to use operators vs named actions?
- 5.9 Exercises – Operators
-
6 Folds
-
6.1 Introduction to Folds
- Focusing all elements of a container
- Collapsing the Set
- Collecting focuses as a list
- Using lenses as folds
- Composing folds
- Foundational fold combinators
- Exercises – Simple Folds
-
6.2 Custom Folds
- Mapping over folds
- Combining multiple folds on the same structure
- Exercises – Custom Folds
-
6.3 Fold Actions
- Writing queries with folds
- Queries case study
- Folding with effects
- Combining fold results
- Using ‘view’ on folds
- Customizing monoidal folds
- Exercises – Fold Actions
-
6.4 Higher Order Folds
- Taking, Dropping
- Backwards
- TakingWhile, DroppingWhile
- Exercises – Higher Order Folds
-
6.5 Filtering folds
- Filtered
- Exercises – Filtering
- 6.6 Fold Laws
-
6.1 Introduction to Folds
-
7 Traversals
-
7.1 Introduction to Traversals
- How do Traversals fit into the hierarchy?
- A bit of Nostalgia
- From fold to traversal
-
7.2 Traversal Combinators
- Traversing each element of a container
- More Combinators
- Traversing multiple paths at once
- Focusing a specific traversal element
-
7.3 Traversal Composition
- Exercises – Simple Traversals
-
7.4 Traversal Actions
- A Primer on Traversable
- Traverse on Traversals
- Infix traverseOf
- Using Traversals directly
- Exercises – Traversal Actions
-
7.5 Custom traversals
-
Optics look like
traverse
- Our first custom traversal
- Traversals with custom logic
- Case Study: Transaction Traversal
- Exercises – Custom Traversals
-
Optics look like
-
7.6 Traversal Laws
- Law One: Respect Purity
- Law Two: Consistent Focuses
- Good Traversal Bad Traversal
- Exercises – Traversal Laws
-
7.7 Advanced manipulation
- partsOf
- Polymorphic partsOf
- partsOf and other data structures
- Exercises – partsOf
-
7.1 Introduction to Traversals
-
8 Indexable Structures
- 8.1 What’s an “indexable” structure?
-
8.2 Accessing and updating values with ‘Ixed’
-
The
Ixed
Class -
Accessing and setting values with
ix
- Indexed Structures
- Indexing monomorphic types
- Indexing stranger structures
-
The
-
8.3 Inserting & Deleting with ‘At’
- Map-like structures
- Manipulating Sets
- Exercises – Indexable Structures
-
8.4 Custom Indexed Data Structures
- Custom Ixed: Cyclical indexing
- Custom At: Address indexing
- Exercises – Custom Indexed Structures
-
8.5 Handling missing values
- Checking whether updates succeed
- Fallbacks with ‘failing’
- Default elements
- Checking fold success/failure
- Exercises – Missing Values
-
9 Prisms
-
9.1 Introduction to Prisms
- How do Prisms fit into the hierarchy?
- Simple Pattern-Matching Prisms
- Checking pattern matches with prisms
- Generating prisms with makePrisms
- Embedding values with prisms
- Other types of patterns
- Exercises – Prisms
-
9.2 Writing Custom Prisms
-
Rebuilding
_Just
and_Nothing
- Matching String Prefixes
- Cracking the coding interview: Prisms style!
- Exercises – Custom Prisms
-
Rebuilding
-
9.3 Laws
- Law One: Review-Preview
- Law Two: Prism Complement
- Law Three: Pass-through Reversion
- Summary
- Exercises – Prism Laws
-
9.4 Case Study: Simple Server
- Path prefix matching
- Altering sub-sets of functions
- Matching on HTTP Verb
-
9.1 Introduction to Prisms
-
10 Isos
-
10.1 Introduction to Isos
- How do Isos fit into the hierarchy?
- There and back again
- 10.2 Building Isos
-
10.3 Flipping isos with
from
- 10.4 Modification under isomorphism
-
10.5 Varieties of isomorphisms
- Composing isos
- Exercises – Intro to Isos
-
10.6 Projecting Isos
- Exercises – Projected Isos
-
10.7 Isos and newtypes
- Coercing with isos
- Newtype wrapper isos
-
10.8 Laws
- The one and only law: Reversibility
- Exercises – Iso Laws
-
10.1 Introduction to Isos
-
11 Indexed Optics
- 11.1 What are indexed optics?
-
11.2 Index Composition
- Custom index composition
- Exercises – Indexed Optics
-
11.3 Filtering by index
- Exercises – Index Filters
-
11.4 Custom indexed optics
- Custom IndexedFolds
- Custom IndexedTraversals
- Index helpers
- Exercises – Custom Indexed Optics
- 11.5 Index-preserving optics
-
12 Dealing with Type Errors
- 12.1 Interpreting expanded optics types
-
12.2 Type Error Arena
- First Foe: Level 1 Lenslion
- Level 2 Tuplicant
- Level 3 Settersiren
- Level 4 Composicore
- Level 5 Foldasaurus
- Level 6 Higher Order Beast
- Level 7 Traversacula
-
13 Optics and Monads
- 13.1 Reader Monad and View
- 13.2 State Monad Combinators
- 13.3 Magnify & Zoom
-
14 Classy Lenses
-
14.1 What are classy lenses and when do I need them?
- No duplicate record fields
- Separating logic and minimizing global knowledge
-
Granular dependencies with
makeFields
- Field requirements compose
-
14.2
makeFields
vsmakeClassy
-
14.1 What are classy lenses and when do I need them?
-
15 JSON
- 15.1 Introspecting JSON
- 15.2 Diving deeper into JSON structures
-
15.3 Traversing into multiple JSON substructures
- Traversing Arrays
- Traversing Objects
- 15.4 Filtering JSON Queries
- 15.5 Serializing & Deserializing within an optics path
-
15.6 Exercises: Kubernetes API
- BONUS Questions
-
16 Uniplate - Manipulating recursive data
- 16.1 A Brief History
-
16.2 Control.Lens.Plated
- Children
- Rewrite
- Universe
- Transform
- Deep
-
16.3 Overriding
plate
-
16.4 The magic of
biplate
- 16.5 Exercises – Uniplate
-
17
generic-lens
-
17.1 Generic Lenses
- Record Fields
- Positional Lenses
- Typed Lenses
- Altogether Now
- Subtype Lenses
-
17.2 Generic Traversals
- Types Traversal
- Parameter Traversals
-
17.3 Generic Prisms
- Constructor Prisms
- Typed Prisms
- 17.4 Exercises – Generic Lens
-
17.1 Generic Lenses
-
18 Appendices
- 18.1 Optic Composition Table
- 18.2 Optic Compatibility Chart
-
18.3 Operator Cheat Sheet
- Legend for Getters
- Legend for Setters/Modifiers
- 18.4 Optic Ingredients
-
19 Answers to Exercises
- 19.1 Optic Anatomy
- 19.2 Lens Actions
- 19.3 Records Part One
-
19.4 Records Part Two
- Laws
- 19.5 Virtual Fields
- 19.6 Self-Correcting Lenses
- 19.7 Polymorphic Lenses
- 19.8 Lens Composition
- 19.9 Operators
- 19.10 Simple Folds
- 19.11 Writing Custom Folds
- 19.12 Querying Using Folds
- 19.13 Higher Order Folds
- 19.14 Filtering
- 19.15 Simple Traversals
- 19.16 Traversal Actions
- 19.17 Custom Traversals
- 19.18 Traversal Laws
- 19.19 partsOf
- 19.20 Indexable Structures
- 19.21 Custom Indexed Structures
- 19.22 Missing Values
- 19.23 Prisms
- 19.24 Custom Prisms
- 19.25 Prism Laws
- 19.26 Intro to Isos
- 19.27 Projected Isos
- 19.28 Iso Laws
- 19.29 Indexed Optics
- 19.30 Index Filters
- 19.31 Custom Indexed Optics
-
19.32 Type Errors
- First Foe: Level 1 Lenslion
- Level 2 Tuplicant
- Level 3 Settersiren
- Level 4 Composicore
- Level 5 Foldasaurus
- Level 6 Foldasaurus
- Level 7 Traversacula
-
19.33 Kubernetes API
- BONUS Questions
- 19.34 Uniplate
- 19.35 Generic Lens
-
20 Thanks
- 20.1 Patreon Supporters
- 20.2 Book Cover
- Notes
The Leanpub 60 Day 100% Happiness Guarantee
Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.
Now, this is technically risky for us, since you'll have the book or course files either way. But we're so confident in our products and services, and in our authors and readers, that we're happy to offer a full money back guarantee for everything we sell.
You can only find out how good something is by trying it, and because of our 100% money back guarantee there's literally no risk to do so!
So, there's no reason not to click the Add to Cart button, is there?
See full terms...
Earn $8 on a $10 Purchase, and $16 on a $20 Purchase
We pay 80% royalties on purchases of $7.99 or more, and 80% royalties minus a 50 cent flat fee on purchases between $0.99 and $7.98. You earn $8 on a $10 sale, and $16 on a $20 sale. So, if we sell 5000 non-refunded copies of your book for $20, you'll earn $80,000.
(Yes, some authors have already earned much more than that on Leanpub.)
In fact, authors have earnedover $13 millionwriting, publishing and selling on Leanpub.
Learn more about writing on Leanpub
Free Updates. DRM Free.
If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).
Most Leanpub books are available in PDF (for computers) and EPUB (for phones, tablets and Kindle). The formats that a book includes are shown at the top right corner of this page.
Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.
Learn more about Leanpub's ebook formats and where to read them