google-research / dex-lang

Research language for array processing in the Haskell/ML family
BSD 3-Clause "New" or "Revised" License
1.56k stars 106 forks source link

Automatic derivation of instances #1293

Open normanrink opened 1 year ago

normanrink commented 1 year ago

For types of the form

data NewTy(<params>) = NewCon(WrappedTy(<params>))

if there is an instance Class(WrappedTy(<params>)), a Class instance for NewTy(<params>) can be automatically derived. This PR implements automatic instance derivation with the syntax

deriving instance Class(NewTy(<params>)) <givens>

Note that automatic instance derivation is asked for in issue #945, but the approach taken in this PR differs from extending DictExpr n with a new contructor NewtypeDict (DictType n) (DictExpr n), as suggested in issue #945. Instead, this PR synthesises an InstanceDef for Class(NewTy(<params>)) from the definition of instance Class(WrappedTy(<params>)).

The main difficulty in synthesising the InstanceDef for Class(NewTy(<params>)) is converting the methods of instance Class(WrappedTy(<params>)), which operate on WrappedTy(<params>), to methods that work with NewTy(<params>). Since the types WrappedTy(<params>) and NewTy(<params>) are isomorphic, this conversion is generally possible. Note that in order to facilitate this conversion, an isomorphism between WrappedTy(<params>) and NewTy(<params>) must be exhibited, consisting of a pair of maps, namely of a (forward-directed) isomorphism and its (backward-directed) inverse.