I'm having a hard time understanding the documentation/examples out there describing the reflection package. I'm an imperative-programming veteran but a Haskell newb. Can you walk me through a very simple introduction?
Package: https://hackage.haskell.org/package/reflection
Edit: to whoever closed this question: this is meant to be a beginner introduction to Haskell reflection. The answer below is excellent and others would be useful too, so please reopen.
In the simplest use-case, if you have some configuration information you'd like to make generally available across a set of functions:
you can add a
Given Configconstraint to the functions that need access to the configuration:and then use the value
givento refer to the current configuration (and sow givenors givento refer to its fields):With a few other functions, some that use the configuration and some that don't:
you can then run a computation under different configurations that you
give:This is similar to:
defining
given :: Configglobally, except you can run the computation under multiple configurations in the same program;passing the configuration around as an extra parameter to every function, except you avoid the bother of explicitly accepting the configuration and passing it on, like:
using a
Readermonad, but you don't have to lift everything to an awkward monad- or applicative-level syntax, like:The full example: