Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiversion API implementation

Tags:

haskell

If I have library which implements API to some REST service (in several modules: types+API calls+JSON instances...), what is the best (and convenient?) way to implement support for new API (version 2)? To create totally new library? But mostly code is the same, there are some breaking changes in JSON instances, API calls are the same, types mostly are the same. In this case any bug in common code must be "fixed" twice: in both libraries (also this involves tests modification in both libraries). How to "replace" only instances? Such flexible module modification is possible in ML and in F#, but I didn't find a way to do it in Haskell: importing of type only, w/o its instances and recreate for it new instance leads to error about duplicated instance (although instances are not exported and imported). So, what is the right and best was to create new API without big repeat of code? PS. Client will use both versions together

like image 936
RandomB Avatar asked Mar 19 '26 01:03

RandomB


1 Answers

This seems like a use case of backpack. Separate the types and instances that change between the two versions in one library for each version, and write the rest of the project against the common interface, which you can instantiate twice, similarly to ML functors.

If you don't want to duplicate the type declarations, I'm not certain it would work well, but maybe you can declare types with a phantom parameter of kind Version in a common library:

data Version = V1 | V2

data MyData (v :: Version) = ...
data MyData2 (v :: Version) = C X Y (MyData v) | ...

and have two libraries declaring orphan instances for MyData V1 and MyData V2 respectively.

importing of type only, w/o its instances

Instances are always exported and cannot be hidden, that's how Haskell's typeclass system works to ensure coherence (to the extent possible). My suggestion above introduces instances for two disjoint types MyData V1, MyData V2, while making it possible to freely coerce from one to the other.

like image 186
Li-yao Xia Avatar answered Mar 20 '26 18:03

Li-yao Xia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!