I noticed that GHC's ScopedTypeVariables
is able to bind type variables in function patterns but not let patterns.
As a minimal example, consider the type
data Foo where Foo :: Typeable a => a -> Foo
If I want to gain access to the type inside a Foo, the following function does not compile:
fooType :: Foo -> TypeRep
fooType (Foo x) =
let (_ :: a) = x
in typeRep (Proxy::Proxy a)
But using this trick to move the type variable binding to a function call, it works without issue:
fooType (Foo x) =
let helper (_ :: a) = typeRep (Proxy::Proxy a)
in helper x
Since let
bindings are actually function bindings in disguise, why aren't the above two code snippets equivalent?
(In this example, other solutions would be to create the TypeRep
with typeOf x
, or bind the variable directly as x :: a
in the top-level function. Neither of those options are available in my real code, and using them doesn't answer the question.)
fooType (Foo x) = typeRep [x]
will also work, using the fact that theproxy
fortypeRep
can be any functor: not necessarily the trivialProxy
, it can also be something that actually contains ana
value!fooType (Foo x) = typeOf x
. I went ahead and assumed the real use case was something where having access to the type variable was the important part.proxy x
argument can also be called with a concrete container containing an actualx
value.typeOf
or other solutions in this case (see last paragraph of the question in parentheses), but in my real code that is not available. I need to get a Template HaskellType
by putting the type variable in a type quote. I also can't binda
directly in the top function, because the type I am trying to get is actually a functional dependency of the hidden type. The helper function solution works fine, I just don't really understand why.let
can not do that, since it uses lazy pattern matching, and that can not bring typeclass dictionaries in scope. This is the same issue of stackoverflow.com/a/23540431/3234959