Deriving Via Type-directed instances
Examensarbete för masterexamen
Type classes are at the heart of Haskell and constitute a language of type-directed behaviour. The programmer defines behaviour for each type by defining a class instance where the compiler transparently fills in the blanks with code. Types guide this process. Each type has a single instance: what if there is more than one way to act? The established approach is to wrap such a type in a newtype, ensuring it has the same memory representation. newtypes require require laborious manual wrapping and unwrapping which have no effect at runtime. Haskell’s deriving construct allows easily generating instances that follow a common pattern by simply listing the classes you want derived. At present, GHC only supports deriving a few classes. The only alternative is to write it by hand. This thesis offers an alternative: the language extension -XDerivingVia (appeared in GHC 8.6 ) and the GHCi command :instances (appeared in GHC 8.10 ) which lists instances of types. The Deriving Via introduces a new deriving strategy via which allows deriving classes from one or more ‘via types’. These types must be identical (at runtime) to the type we are deriving for. We instantiate behaviour at a via type and then coerce it to our type. The :instances command lists candidates that can be derived via a given type. That enables programmers to compose instances from named programming patterns, thereby turning deriving into a high-level domain-specific language for defining instances. Deriving Via leverages newtypes—an already familiar tool of the Haskell trade—to declare recurring patterns in a way that both feels natural and allows a high degree of abstraction.
Thesis , deriving , Haskell , program synthesis , type classes , safe coercions