mercredi 2 septembre 2020

How to replace ImplicitParams with the 'reflection' package?

I have an enumeration type, e.g.

data MyType = A | B

And I want to be able to pass values of this type implicitly to my functions. I can do this using the ImplicitParams GHC extension like this:

type HasMyType = (?myType :: MyType)

myFun :: HasMyType => String
myFun = case ?myType of
    A -> "Foo"
    B -> "Bar"

But I've heard many times that it's better to use the Haskell package reflection for this task. Unfortunately, the reflection documentation doesn't explain how to write a similar code using the library. And it's not that straightforward to figure it out.

So, my question is, whether it's possible to use the reflection library to implement a similar code and to satisfy the following requirements?

  1. Values of MyType should be passed implicitly.
  2. If the HasMyType constraint is not specified, the default value of MyType should be taken.
  3. It should be possible to override the value passed via the HasMyType constraint in a single place, e.g. at the beginning of the application.

Does something like this is possible? Or what would be the closest approximation of this using the reflection library?





Aucun commentaire:

Enregistrer un commentaire