Representing Interfaces when you have no Interfaces.
Tags: Idris Dependent-Types Interfaces
I was chatting with someone about Interfaces/Type-classes and how in their language of choice you do not get default functions. It reminded me of a little implementation trick I used in my thesis to hot swap model implementations in an evaluator I wrote.
I will show this trick using the dependently typed language Idris but make not that I don’t see any real reason why this cannot be achieved in a language that supports polymorphism and indexed data types.
The core idea of this trick is to realise that within Idris Interfaces are realised as algebraic data types.
We can show this by approximating the Num interface with the following record:
record MyNum (type : Type) where constructor MkNum add : type -> type -> type times : type -> type -> type fromInt : Integer -> type
and an implementation that instantiates the fields with implementations for Nat
natNum : MyNum Nat natNum = MkNum (Nat.plus) (Nat.mult) (fromIntegerNat)
We can now start to write functions that use this ‘interface’, and where we would have an interface constraint we now explicitly pass around an implementation.
double : (impl : MyNum type) -> (x : type) -> type double impl x = (add impl) x x
Now with this setup we can also provide default functions.
Here is an approximation for the Eq interface:
record MyEq (type : Type) where constructor MkEq equal : type -> type -> Bool notEqual : type -> type -> Bool
We can construct factories to then build the default implementations for methods if they are provided.
mkEq : (eq : type -> type -> Bool) -> (mNotEq : Maybe (type -> type -> Bool)) -> MyEq type mkEq f Nothing = MkEq f (\x, y => not $ f x y) mkEq f (Just nf) = MkEq f nf
Here we now construct an instance of MyEq for Nats.
First we define equality.
natEqFunc : Nat -> Nat -> Bool natEqFunc Z Z = True natEqFunc (S l) (S r) = natEqFunc l r natEqFunc _ _ = False
Then we can build an implementation that uses a ‘default’ implementation.
natEq : MyEq Nat natEq = mkEq natEqFunc Nothing
and one that does not.
natEq' : MyEq Nat natEq' = mkEq natEqFunc (Just (\x,y => not $ natEqFunc x y))
As a final thought, what about implementing default implementations in terms of the ‘interface’ itself. For that I would suggest removing those functions as fields and write functions that use the ‘interface’.
PS
The reason records are not highlighted nicely is due to issues with Idris’ highlighting code for records.
Related Posts
- Handling Side-Effects using Resource Dependent Algebraic Effects
- Revisiting Type-Driven Design of Communicating Systems
- Type-Driven Development of SoC Architectures.
- Type-Driven Development of SoC Architectures.
- A Short Note on Collecting Dependently Typed Values
← Handling Side-Effects using Resource Dependent Algebraic Effects | Computing Types with Idris & Linking Specifications with Implementations. →