- Types that are the same but different
- Via concrete types (kind
- Via type constructors (kind
* -> *)
- Constructor must be in scope
DerivingVia GHC extension provides the
via deriving strategy, which lets your type copy typeclass instances from other types.
The type providing the instances and the type receiving the instances have to be representationally equivalent Another way to say this is that the two types have to be coercible with each other. – more or less the same, distinguished only by one or more layers of
newtype definitions. This may sound fairly limited, but it turns out that a suprising variety of situations satisfy this condition. Haskellers write newtypes a lot, especially when introducing interesting typeclass instances.
Deriving Via was proposed in April 2018,The Deriving via GHC proposal and the paperDeriving Via: or, How to Turn Hand-Written Instances into an Anti-Pattern by Baldur Blöndal, Andres Löh, and Ryan Scott gives an excellent overview of the motivations and implementation details. The extension first appeared in GHC 8.6.1 in September of the same year.
Types that are the same but different
We sometimes think of a Haskell type as a set of values. The
Bool type consists of the values
Natural type consists of the counting numbers (0, 1, 2, …), etc. By forming sums and products of simple types we build increasingly complex data structures;
[Natural] is lists of numbers,
Map Natural Bool is mappings from numbers to truth values, etc. But values and data structures is only half of the story with types.