|
| 1 | +# Status |
| 2 | + |
| 3 | +- [ ] Proposed 2024-05-07 |
| 4 | + |
| 5 | +# Context |
| 6 | + |
| 7 | +## The Problem |
| 8 | +In `cardano-api` we have multiple functions performing conversions between one value of the type to the other, for example: |
| 9 | + |
| 10 | +```haskell |
| 11 | +toShelleyScriptHash :: ScriptHash -> ScriptHash |
| 12 | +fromShelleyScriptHash :: ScriptHash -> ScriptHash |
| 13 | +``` |
| 14 | + |
| 15 | +There are multiple naming conventions for the conversion functions which makes them hard to locate. |
| 16 | +Some conversion functions with lengthy names, are not very convenient to use. |
| 17 | + |
| 18 | +## Solution Proposal |
| 19 | + |
| 20 | +### Type classes |
| 21 | + |
| 22 | +For total functions, which are simply converting a value from one type to another, we can use type classes [`Inject`](https://cardano-ledger.cardano.intersectmbo.org/cardano-ledger-core/Cardano-Ledger-BaseTypes.html#t:Inject) & [`Convert`](https://cardano-api.cardano.intersectmbo.org/cardano-api/Cardano-Api-Internal-Eras.html#t:Convert): |
| 23 | +```haskell |
| 24 | +class Inject t s where |
| 25 | + inject :: t -> s |
| 26 | + |
| 27 | +class Convert (f :: a -> Type) (g :: a -> Type) where |
| 28 | + convert :: forall a. f a -> g a |
| 29 | +``` |
| 30 | + |
| 31 | +The use of those conversion functions is limited to **internal use only**. |
| 32 | +The library should still export conversion functions with explicit type names for better readability. |
| 33 | + |
| 34 | +### Explicit conversion functions |
| 35 | + |
| 36 | +For explicit conversion functions, the following naming convention should follow: |
| 37 | + |
| 38 | +```haskell |
| 39 | +fooToBar :: Foo -> Bar |
| 40 | +``` |
| 41 | + |
| 42 | + |
| 43 | +If the module exporting conversion functions is meant to be imported qualified, and provides functions for operating on a single data type, a shorter name with `from` prefix is allowed: |
| 44 | + |
| 45 | +```haskell |
| 46 | +module Data.Foo where |
| 47 | + |
| 48 | +fromBar :: Bar -> Foo |
| 49 | +``` |
| 50 | + |
| 51 | +where the usage would look like: |
| 52 | +```haskell |
| 53 | +import Data.Foo qualified as Foo |
| 54 | + |
| 55 | +Foo.fromBar bar |
| 56 | +``` |
| 57 | + |
| 58 | +# Decision |
| 59 | + |
| 60 | +TBD |
| 61 | + |
| 62 | +# Consequences |
| 63 | + |
| 64 | +## Advantages |
| 65 | +- An uniform API for total conversions |
| 66 | +- Less exported symbols, which currently have few conventions for the conversions |
| 67 | +- Less maintenance burden with regards to the naming conventions of the conversion functions |
| 68 | + |
| 69 | +## Disadvantages |
| 70 | +- It may be a bit difficult to discover available conversions, because one would have to browse the type's `Inject` instances to find the conversion functions they are looking for - instead of looking for exported functions. |
0 commit comments