Leanpub Header

Skip to main content

Optics By Example

Functional lenses in Haskell

A comprehensive example-driven guide to optics. Examples in Haskell, but adaptable to other languages.

Become a data-manipulation wizard using optics to manipulate data!

This book takes you from beginner to advanced using Lenses, Traversals, Prisms, and more!

Minimum price

$20.00

$40.00

You pay

$40.00

Author earns

$32.00
$

...Or Buy With Credits!

You can get credits monthly with a Reader Membership
PDF
EPUB
WEB
1,388
Readers
420
Pages
101,268Words
About

About

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.

Share this book

Categories

Author

About the Author

Chris Penner

Hey there! I'm a programmer, coffee lover and acrobat!

I love functional programming and I love writing, seems only natural to bring the two together (especially since it's a bit tougher to match coding and acrobatics!)

Hope you enjoy my book!

Leanpub Podcast

Episode 179

An Interview with Chris Penner

Contents

Table of Contents

1Obligatory Preamble

  1. 1.1Why should I read this book?
  2. 1.2How to read this book
  3. 1.3Chosen language and optics encodings
  4. 1.4Your practice environment
  5. 1.5Following examples
  6. 1.6About the type signatures
  7. 1.7About the exercises

2Optics

  1. 2.1What are optics?
  2. 2.2Strengths
  3. 2.3Weaknesses
  4. 2.4Practical optics at a glance
  5. 2.5Impractical optics at a glance

3Lenses

  1. 3.1Introduction to Lenses
  2. Anatomy
  3. Exercises – Optic Anatomy
  4. 3.2Lens actions
  5. Viewing through lenses
  6. Setting through a lens
  7. Exercises - Lens Actions
  8. 3.3Lenses and records
  9. Lenses subsume the “accessor” pattern
  10. Building a lens for a record field
  11. Exercises - Records Part One
  12. Getting and setting with a field lens
  13. Modifying fields with a lens
  14. Automatically generating field lenses
  15. makeLenses
  16. Exercises - Records Part Two
  17. 3.4Limitations
  18. Is it a Lens?
  19. Is it a Lens? – Answers
  20. 3.5Lens Laws
  21. Why do optics have laws?
  22. The Laws
  23. Breaking Laws
  24. Case Study: _1
  25. Case Study: msg
  26. Case Study: lensProduct
  27. Exercises - Laws
  28. 3.6Virtual Fields
  29. What’s a virtual field
  30. Writing a virtual field
  31. Breakage-free refactoring
  32. Exercises – Virtual Fields
  33. 3.7Data correction and maintaining invariants
  34. Including correction logic in lenses
  35. Exercises – Self-Correcting Lenses

4Polymorphic Optics

  1. 4.1Introduction to polymorphic optics
  2. Simple vs Polymorphic optics
  3. 4.2When do we need polymorphic lenses
  4. Type-changing focuses
  5. Changing type variables with polymorphic lenses
  6. Exercises – Polymorphic Lenses
  7. 4.3Composing Lenses
  8. How do I update fields in deeply nested records?
  9. Composing update functions
  10. Composing Lenses
  11. How do Lens Types Compose?
  12. Exercises – Lens Composition

5Operators

  1. 5.1Lens Operators
  2. 5.2view a.k.a. ^.
  3. 5.3set a.k.a. .~
  4. 5.4Chaining many operations
  5. 5.5Using %~ a.k.a. over
  6. 5.6Learning Hieroglyphics
  7. 5.7Modifiers
  8. 5.8When to use operators vs named actions?
  9. 5.9Exercises – Operators

6Folds

  1. 6.1Introduction to Folds
  2. Focusing all elements of a container
  3. Decomposing Problems
  4. Collapsing the Set
  5. Collecting focuses as a list
  6. Using lenses as folds
  7. Composing folds
  8. Foundational fold combinators
  9. Exercises – Simple Folds
  10. 6.2Custom Folds
  11. Mapping over folds
  12. Combining multiple folds on the same structure
  13. Exercises – Custom Folds
  14. 6.3Fold Actions
  15. Writing queries with folds
  16. Queries case study
  17. Folding with effects
  18. Combining fold results
  19. Using ‘view’ on folds
  20. Customizing monoidal folds
  21. Exercises – Fold Actions
  22. 6.4Higher Order Folds
  23. Taking, Dropping
  24. Backwards
  25. TakingWhile, DroppingWhile
  26. Exercises – Higher Order Folds
  27. 6.5Filtering folds
  28. Filtered
  29. Exercises – Filtering
  30. 6.6Fold Laws

7Traversals

  1. 7.1Introduction to Traversals
  2. How do Traversals fit into the hierarchy?
  3. A bit of Nostalgia
  4. From fold to traversal
  5. 7.2Traversal Combinators
  6. Traversing each element of a container
  7. More Combinators
  8. Traversing multiple paths at once
  9. Focusing a specific traversal element
  10. 7.3Traversal Composition
  11. Exercises – Simple Traversals
  12. 7.4Traversal Actions
  13. A Primer on Traversable
  14. Traverse on Traversals
  15. Infix traverseOf
  16. Using Traversals directly
  17. Exercises – Traversal Actions
  18. 7.5Custom traversals
  19. Optics look like traverse
  20. Our first custom traversal
  21. Traversals with custom logic
  22. Case Study: Transaction Traversal
  23. Exercises – Custom Traversals
  24. 7.6Traversal Laws
  25. Law One: Respect Purity
  26. Law Two: Consistent Focuses
  27. Good Traversal Bad Traversal
  28. Exercises – Traversal Laws
  29. 7.7Advanced manipulation
  30. partsOf
  31. Polymorphic partsOf
  32. partsOf and other data structures
  33. Exercises – partsOf

8Indexable Structures

  1. 8.1What’s an “indexable” structure?
  2. 8.2Accessing and updating values with ‘Ixed’
  3. The Ixed Class
  4. Accessing and setting values with ix
  5. Indexed Structures
  6. Indexing monomorphic types
  7. Indexing stranger structures
  8. 8.3Inserting & Deleting with ‘At’
  9. Map-like structures
  10. Manipulating Sets
  11. Exercises – Indexable Structures
  12. 8.4Custom Indexed Data Structures
  13. Custom Ixed: Cyclical indexing
  14. Custom At: Address indexing
  15. Exercises – Custom Indexed Structures
  16. 8.5Handling missing values
  17. Checking whether updates succeed
  18. Fallbacks with ‘failing’
  19. Default elements
  20. Checking fold success/failure
  21. Exercises – Missing Values

9Prisms

  1. 9.1Introduction to Prisms
  2. How do Prisms fit into the hierarchy?
  3. Simple Pattern-Matching Prisms
  4. Checking pattern matches with prisms
  5. Generating prisms with makePrisms
  6. Embedding values with prisms
  7. Other types of patterns
  8. Exercises – Prisms
  9. 9.2Writing Custom Prisms
  10. Rebuilding _Just and _Nothing
  11. Matching String Prefixes
  12. Cracking the coding interview: Prisms style!
  13. Exercises – Custom Prisms
  14. 9.3Laws
  15. Law One: Review-Preview
  16. Law Two: Prism Complement
  17. Law Three: Pass-through Reversion
  18. Summary
  19. Exercises – Prism Laws
  20. 9.4Case Study: Simple Server
  21. Path prefix matching
  22. Altering sub-sets of functions
  23. Matching on HTTP Verb

10Isos

  1. 10.1Introduction to Isos
  2. How do Isos fit into the hierarchy?
  3. There and back again
  4. 10.2Building Isos
  5. 10.3Flipping isos with from
  6. 10.4Modification under isomorphism
  7. 10.5Varieties of isomorphisms
  8. Composing isos
  9. Exercises – Intro to Isos
  10. 10.6Projecting Isos
  11. Exercises – Projected Isos
  12. 10.7Isos and newtypes
  13. Coercing with isos
  14. Newtype wrapper isos
  15. 10.8Laws
  16. The one and only law: Reversibility
  17. Exercises – Iso Laws

11Indexed Optics

  1. 11.1What are indexed optics?
  2. 11.2Index Composition
  3. Custom index composition
  4. Exercises – Indexed Optics
  5. 11.3Filtering by index
  6. Exercises – Index Filters
  7. 11.4Custom indexed optics
  8. Custom IndexedFolds
  9. Custom IndexedTraversals
  10. Index helpers
  11. Exercises – Custom Indexed Optics
  12. 11.5Index-preserving optics

12Dealing with Type Errors

  1. 12.1Interpreting expanded optics types
  2. 12.2Type Error Arena
  3. First Foe: Level 1 Lenslion
  4. Level 2 Tuplicant
  5. Level 3 Settersiren
  6. Level 4 Composicore
  7. Level 5 Foldasaurus
  8. Level 6 Higher Order Beast
  9. Level 7 Traversacula

13Optics and Monads

  1. 13.1Reader Monad and View
  2. 13.2State Monad Combinators
  3. 13.3Magnify & Zoom

14Classy Lenses

  1. 14.1What are classy lenses and when do I need them?
  2. No duplicate record fields
  3. Separating logic and minimizing global knowledge
  4. Granular dependencies with makeFields
  5. Field requirements compose
  6. 14.2makeFields vs makeClassy

15JSON

  1. 15.1Introspecting JSON
  2. 15.2Diving deeper into JSON structures
  3. Tracking down mistakes
  4. 15.3Traversing into multiple JSON substructures
  5. Traversing Arrays
  6. Traversing Objects
  7. 15.4Filtering JSON Queries
  8. 15.5Serializing & Deserializing within an optics path
  9. 15.6Exercises: Kubernetes API
  10. BONUS Questions

16Uniplate - Manipulating recursive data

  1. 16.1A Brief History
  2. 16.2Control.Lens.Plated
  3. Children
  4. Rewrite
  5. Universe
  6. Transform
  7. Deep
  8. 16.3Overriding plate
  9. 16.4The magic of biplate
  10. 16.5Exercises – Uniplate

17generic-lens

  1. 17.1Generic Lenses
  2. Record Fields
  3. Positional Lenses
  4. Typed Lenses
  5. Altogether Now
  6. Subtype Lenses
  7. 17.2Generic Traversals
  8. Types Traversal
  9. Parameter Traversals
  10. 17.3Generic Prisms
  11. Constructor Prisms
  12. Typed Prisms
  13. 17.4Exercises – Generic Lens

18Appendices

  1. 18.1Optic Composition Table
  2. 18.2Optic Compatibility Chart
  3. 18.3Operator Cheat Sheet
  4. Legend for Getters
  5. Legend for Setters/Modifiers
  6. 18.4Optic Ingredients

19Answers to Exercises

  1. 19.1Optic Anatomy
  2. 19.2Lens Actions
  3. 19.3Records Part One
  4. 19.4Records Part Two
  5. Laws
  6. 19.5Virtual Fields
  7. 19.6Self-Correcting Lenses
  8. 19.7Polymorphic Lenses
  9. 19.8Lens Composition
  10. 19.9Operators
  11. 19.10Simple Folds
  12. 19.11Writing Custom Folds
  13. 19.12Querying Using Folds
  14. 19.13Higher Order Folds
  15. 19.14Filtering
  16. 19.15Simple Traversals
  17. 19.16Traversal Actions
  18. 19.17Custom Traversals
  19. 19.18Traversal Laws
  20. 19.19partsOf
  21. 19.20Indexable Structures
  22. 19.21Custom Indexed Structures
  23. 19.22Missing Values
  24. 19.23Prisms
  25. 19.24Custom Prisms
  26. 19.25Prism Laws
  27. 19.26Intro to Isos
  28. 19.27Projected Isos
  29. 19.28Iso Laws
  30. 19.29Indexed Optics
  31. 19.30Index Filters
  32. 19.31Custom Indexed Optics
  33. 19.32Type Errors
  34. First Foe: Level 1 Lenslion
  35. Level 2 Tuplicant
  36. Level 3 Settersiren
  37. Level 4 Composicore
  38. Level 5 Foldasaurus
  39. Level 6 Foldasaurus
  40. Level 7 Traversacula
  41. 19.33Kubernetes API
  42. BONUS Questions
  43. 19.34Uniplate
  44. 19.35Generic Lens

20Thanks

  1. 20.1Patreon Supporters
  2. 20.2Book Cover

Get the free sample chapters

Click the buttons to get the free sample in PDF or EPUB, or read the sample online here

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 earned over $14 million writing, 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

Write and Publish on Leanpub

You can use Leanpub to easily write, publish and sell in-progress and completed ebooks and online courses!

Leanpub is a powerful platform for serious authors, combining a simple, elegant writing and publishing workflow with a store focused on selling in-progress ebooks.

Leanpub is a magical typewriter for authors: just write in plain text, and to publish your ebook, just click a button. (Or, if you are producing your ebook your own way, you can even upload your own PDF and/or EPUB files and then publish with one click!) It really is that easy.

Learn more about writing on Leanpub