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
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.
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!
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!
Optics by Example opened my eyes to the benefits of Lenses et al. First I was blind but now I see!
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.
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.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.1 Introduction to Lenses
- 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
- Is it a Lens?
- Is it a Lens? – Answers
3.5 Lens Laws
- Why do optics have laws?
- The Laws
- 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.1 Lens Operators
- 5.4 Chaining many operations
- 5.6 Learning Hieroglyphics
- 5.7 Modifiers
- 5.8 When to use operators vs named actions?
- 5.9 Exercises – Operators
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
- TakingWhile, DroppingWhile
- Exercises – Higher Order Folds
6.5 Filtering folds
- Exercises – Filtering
- 6.6 Fold Laws
- 6.1 Introduction to Folds
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
- 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
- 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’
Accessing and setting values with
- Indexed Structures
- Indexing monomorphic types
- Indexing stranger structures
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.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
- Matching String Prefixes
- Cracking the coding interview: Prisms style!
- Exercises – Custom Prisms
- Law One: Review-Preview
- Law Two: Prism Complement
- Law Three: Pass-through Reversion
- 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.1 Introduction to Isos
- How do Isos fit into the hierarchy?
- There and back again
- 10.2 Building Isos
10.3 Flipping isos with
- 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
- 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
- Field requirements compose
- 14.1 What are classy lenses and when do I need them?
- 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.4 The magic of
- 16.5 Exercises – Uniplate
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.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
- 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.1 Patreon Supporters
- 20.2 Book Cover
The Leanpub 45-day 100% Happiness Guarantee
Within 45 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.
See full terms
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), EPUB (for phones and tablets) and MOBI (for 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.
C++ Best PracticesJason Turner
Level up your C++, get the tools working for you, eliminate common problems, and move on to more exciting things!
OpenIntro StatisticsDavid Diez, Christopher Barr, Mine Cetinkaya-Rundel, and OpenIntro
A 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.
Functional Design and ArchitectureAlexander Granin
Software Design in Functional Programming, Design Patterns and Practices, Methodologies and Application Architectures. How to build real software in Haskell with less efforts and low risks. The first complete source of knowledge.
R Programming for Data ScienceRoger D. Peng
This 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.
C++20 is the next big C++ standard after C++11. As C++11 did it, C++20 changes the way we program modern C++. This change is, in particular, due to the big four of C++20: ranges, coroutines, concepts, and modules.
I am a Software Engineer and I am in ChargeAlexis Monville and Michael Doyle
I am a Software Engineer and I am in Charge is a real-world, practical book that helps you increase your impact and satisfaction at work no matter who you work with.
In the book, we will follow Sandrine, a fictional character who learns to think in a new way enabling her to take a different course of action.
Atomic KotlinBruce Eckel and Svetlana Isakova
For both beginning and experienced programmers! From the author of the multi-award-winning Thinking in C++ and Thinking in Java together with a member of the Kotlin language team comes a book that breaks the concepts into small, easy-to-digest "atoms," along with exercises supported by hints and solutions directly inside IntelliJ IDEA!
Invest In Digital Health - The Medical Futurist's GuideDr. Bertalan Mesko
Artificial Intelligence and Digital Health are booming. In this book, we explain why now it's a good time to invest in Digital Health and give recommendations on where to invest by looking at the top 24 technological trends we find the most promising.
The Hundred-Page Machine Learning BookAndriy Burkov
Everything you really need to know in Machine Learning in a hundred pages.
Mastering STM32Carmine Noviello
With more than 600 microcontrollers, STM32 is probably the most complete ARM Cortex-M platform on the market. This book aims to be the first guide around that introduces the reader to this exciting MCU portfolio from ST Microelectronics and its official CubeHAL.
Software Architecture for Developers: Volumes 1 & 2 - Technical leadership and communication
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...
CCIE Service Provider Ultimate Study Bundle
2 BooksPiotr 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...
The Future of Digital Health
6 BooksWe put together the most popular books from The Medical Futurist to provide a clear picture about the major trends shaping the future of medicine and healthcare. Digital health technologies, artificial intelligence, the future of 20 medical specialties, big pharma, data privacy and how technology giants such as Amazon or Google want to conquer...
Cisco CCNA 200-301 Complet
4 BooksCe lot comprend les quatre volumes du guide préparation à l'examen de certification Cisco CCNA 200-301.
CCDE Practical Studies (All labs)
3 BooksCCDE lab
"The C++ Standard Library" and "Concurrency with Modern C++"
2 BooksGet my books "The C++ Standard Library" and "Concurrency with Modern C++" in a bundle. The first book gives you the details you should know about the C++ standard library; the second one dives deeper into concurrency with modern C++. In sum, you get more than 600 pages full of modern C++ and about 250 source files presenting the standard library...
Modern Management Made Easy
3 BooksRead all three Modern Management Made Easy books. Learn to manage yourself, lead and serve others, and lead the organization.
Linux Administration Complet
4 BooksCe 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é...
Programming with Ease
3 BooksAlle drei Bände der Serie Programming with Ease in einem Paket. Darin findest du alles, was ich dir zu den wichtigsten Phasen der Softwareentwicklung im Hinblick auf Clean Code Development für langfristig hohe Produktivität sagen kann.Im Band Slicing findest du die Anforderungsanalyse im Rahmen eines iterativ-inkrementellen Vorgehensmodells aus...
2 BooksUnveil the power of Ansible and Vagrant with this bundle at a special price. You'll have everything you need to get started with Vagrant - learn the basics and how to create your virtual development environments, using Ansible as provisioner! About Vagrant Cookbook Vagrant Cookbook is a complete guide to get started with Vagrant and create your...