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.
See full terms
80% Royalties. Earn $16 on a $20 book.
We pay 80% royalties. That's not a typo: you earn $16 on a $20 sale. If we sell 5000 non-refunded copies of your book or course for $20, you'll earn $80,000.
(Yes, some authors have already earned much more than that on Leanpub.)
In fact, authors have earned$12,307,240writing, 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
Top Books
OpenIntro Statistics
David Diez, Christopher Barr, Mine Cetinkaya-Rundel, and OpenIntroA complete foundation for Statistics, also serving as a foundation for Data Science.
Leanpub revenue supports OpenIntro (US-based nonprofit) so we can provide free desk copies to teachers interested in using OpenIntro Statistics in the classroom and expand the project to support free textbooks in other subjects.
More resources: openintro.org.
Personal Finance
Jason AndersonThis textbook provides an in-depth analysis on personal finance that is both practical and straightforward in its approach. It has been written in such a way that the readers can gain knowledge without getting overwhelmed by the technical terms. Suitable for both beginners and advanced learners.
Getting to Know IntelliJ IDEA
Trisha Gee and Helen ScottIf we treat our IDE as a text editor, we are doing ourselves a disservice. Using a combination of tutorials and a questions-and-answers approach, Getting to Know IntelliJ IDEA will help you find ways to use IntelliJ IDEA that enable you to work comfortably and productively as a professional developer.
C++20 - The Complete Guide
Nicolai M. JosuttisAll new language and library features of C++20 (for those who know previous C++ versions).
The book presents all new language and library features of C++20. Learn how this impacts day-to-day programming, to benefit in practice, to combine new features, and to avoid all new traps.
Buy early, pay less, free updates.
Other books:
R Programming for Data Science
Roger D. PengThis book brings the fundamentals of R programming to you, using the same material developed as part of the industry-leading Johns Hopkins Data Science Specialization. The skills taught in this book will lay the foundation for you to begin your journey learning data science. Printed copies of this book are available through Lulu.
Mastering STM32 - Second Edition
Carmine NovielloWith more than 1200 microcontrollers, STM32 is probably the most complete ARM Cortex-M platform on the market. This book aims to be the most complete guide around introducing the reader to this exciting MCU portfolio from ST Microelectronics and its official CubeHAL and STM32CubeIDE development environment.
Stats One
William FooteThe Rails 7 Way
Obie Fernandez, Lucas Dohmen, and Tom Henrik AadlandThe Rails™ 7 Way is the comprehensive, authoritative reference guide for professionals delivering production-quality code using modern Ruby on Rails. It illuminates the entire Rails 7 API, its most powerful idioms, design approaches, and libraries. Building on the previous editions, this edition has been heavily refactored and updated.
Machine Learning Q and AI
Sebastian Raschka, PhDHave you recently completed a machine learning or deep learning course and wondered what to learn next? With 30 questions and answers on key concepts in machine learning and AI, this book provides bite-sized bits of knowledge for your journey to becoming a machine learning expert.
Gradual Modularization for Ruby and Rails
Stephan HagemannGet yourself a new tool to manage your Rails application and your growing engineering organization! Prevent the ball-of-mud (and fix it!). Go for microservices or SOA if it makes sense not just because you don't have any other tool. Do all this through a low-overhead tool: packages. Enable better conversations to make practical changes today.
Top Bundles
- #1
Software Architecture
2 Books
"Software Architecture for Developers" is a practical and pragmatic guide to modern, lightweight software architecture, specifically aimed at developers. You'll learn:The essence of software architecture.Why the software architecture role should include coding, coaching and collaboration.The things that you really need to think about before... - #2
CCIE Service Provider Ultimate Study Bundle
2 Books
Piotr Jablonski, Lukasz Bromirski, and Nick Russo have joined forces to deliver the only CCIE Service Provider training resource you'll ever need. This bundle contains a detailed and challenging collection of workbook labs, plus an extensively detailed technical reference guide. All of us have earned the CCIE Service Provider certification... - #3
1500 QUIZ COMMENTATI (3 libri)
3 Books
Tre libri dei QUIZ MMG Commentati al prezzo di DUE! I QUIZ dei concorsi ufficiali di Medicina Generale relativi agli anni: 2000-2001-2003-2012-2013-2014-2015-2016-2017-2018-2019-2020-2021 +100 inediti Raccolti in unico bundle per aiutarvi nello studio e nella preparazione al concorso. All'interno di ogni libro i quiz sono stati suddivisi per... - #4
Pattern-Oriented Memory Forensics and Malware Detection
2 Books
This training bundle for security engineers and researchers, malware and memory forensics analysts includes two accelerated training courses for Windows memory dump analysis using WinDbg. It is also useful for technical support and escalation engineers who analyze memory dumps from complex software environments and need to check for possible... - #5
Practical FP in Scala + Functional event-driven architecture
2 Books
Practical FP in Scala (A hands-on approach) & Functional event-driven architecture, aka FEDA, (Powered by Scala 3), together as a bundle! The content of PFP in Scala is a requirement to understand FEDA so why not take advantage of this bundle!? - #6
Modern C++ Collection
3 Books
Get All about Modern C++C++ Standard Library, including C++20Concurrency with Modern C++, including C++20C++20Each book has about 200 complete code examples. Updates are included. When I update one of the books, you immediately get the updated bundle. You can expect significant updates to each new C++ standard (C++23, C++26, .. ) and also... - #7
Linux Administration Complet
4 Books
Ce lot comprend les quatre volumes du Guide Linux Administration :Linux Administration, Volume 1, Administration fondamentale : Guide pratique de préparation aux examens de certification LPIC 1, Linux Essentials, RHCSA et LFCS. Administration fondamentale. Introduction à Linux. Le Shell. Traitement du texte. Arborescence de fichiers. Sécurité... - #9
Development and Deployment of Multiplayer Online Games, Part ARCH. Architecture (Vol. I-III)
3 Books
What's the Big Idea? The idea behind this book is to summarize the body of knowledge that already exists on multiplayer games but is not available in one single place.And quite a fewof the issues discussed within this series (planned as three nine volumes ~300 pages each), while known in the industry, have not been published at all (except for... - #10
Growing Agile: The Complete Coach's Guide
7 Books
Growing Agile: Coach's Guide Series This bundle provides a collection of training and workshop plans for a variety of agile topics. The series is aimed at agile coaches, trainers and ScrumMasters who often find themselves needing to help teams understand agile concepts. Each book in the series provides the plans, slides, handouts and activity...