Reputation: 4609
When I was new to Haskell I had very hard time finding instances for various types.
Motivated by this, much later I noticed reifyInstances. While I know little about Template Haskell, it seems that that we can discover more instances than usual :info
can provide using this trick:
putStrLn $(stringE . pprint =<< reify ''Functor)
Does TH intentionally have "relaxed" access to the environment? What is the proper usage of reifyInstances and how it's different from the other form?
Upvotes: 0
Views: 94
Reputation: 2778
it seems that that we can discover more instances than usual
:info
can provide
:info
is selective by design. From the documentation:
To avoid showing irrelevant information, an instance is shown only if (a) its head mentions name, and (b) all the other things mentioned in the instance are in scope (either qualified or otherwise) as a result of a
:load
or:module
commands.The command
:info!
works in a similar fashion but it removes restriction (b), showing all instances that are in scope and mention name in their head.
So, by default it only shows instances for types that are already in scope, but it can also show other instances if you'd like (by using :info!
instead of :info
).
Does TH intentionally have "relaxed" access to the environment? What is the proper usage of reifyInstances and how it's different from the other form?
As far as I know, TH has access to everything in the code that the compiler has access to, otherwise it wouldn't be as effective at extending the language.
The proper usage of reifyInstances
is, indeed, in extending the language. The "other form" (by which I assume you mean :info
) is meant for easy interactive use in GHCi. The TH package, on the other hand, is for writing metaprogramming libraries. Say, for example, you're writing a library to generate instances for arbitrary types automatically. Maybe you want your library to generate generic code in the general case, but if the data type implements certain typeclasses already, you can instead automatically generate special "performance" code. reifyInstances
might be useful here.
Upvotes: 4