Lesson 11: Generalizing further

Contents
  • Designing a typeclass
  • Folding over sum types
  • Desire for a generalized fmap
  • The lens library
  • The Success and Failure prisms
  • The Either-Validation isomorphism
  • The Validate class
  • Exercises
    • Exercise 1
    • Exercise 2

In this course we have emphasized two contrasts:

  1. Right is the side of Either that functions like fmap and (>>=) act upon; Left is the side that just tags along for the ride.

  2. Either is the type for which (<*>) stops at the first left value; Validation is the type for which (<*>) accumulates left values.

In this final lesson of the course, we will set aside these differences, ignore the functions and typeclass instances, and focus on the similarities in the structure of the data:

  1. Beyond the choice of which side we call “left” and “right”, Either a b is not really different from Either b a.

  2. Although Either and Validation have different names for their constructors, the two types have exactly the same structure.

From this perspective, Left/Right and Either/Validation differ superficially – in name only. We can exploit these symmetries to design with fewer, more generally-reusable components.

Worrying about generalization too soon can be dangerous. Whether you’re writing your own code or trying to understand someone else’s, we recommend following the approach we have taken here in this course: don’t start with a generality. Start with concrete examples, then observe what aspects they share. As a learner, this order provides more opportunity to understand complex or abstract concepts by grounding them in concrete ones. As an author, this order helps ensure that your more abstract inventions make sense and have purpose.

Sign up for access to the full page, plus the complete archive and all the latest content.