1

Following is my failing attempt to extract a TypeRef of b:

import Data.Typeable

f :: Typeable b => a -> b
f = impl
  where
    bTypeRep = typeOf $ (undefined :: Typeable b => (a -> b) -> b) impl
    impl = undefined

The error message is following:

Could not deduce (Typeable a0) arising from a use of `typeOf'
  from the context (Typeable b)
    bound by the type signature for f :: Typeable b => a -> b
    at src/Xet.hs:14:6-25
  The type variable `a0' is ambiguous

What is wrong? How to solve this?

4

2 回答 2

2

问题是类型变量在标准 Haskell 中没有作用域,因此签名中的类型变量f和类型注释中的类型变量之间没有联系。你还不如写

bTypeRep = typeOf $ (undefined :: Typeable d => (c -> d) -> d) impl

正如 luqui 在评论中建议的那样,解决方案是启用ScopedTypeVariables扩展。请注意,这不会使所有类型变量都具有作用域;您必须使用显式forall量词向编译器指示何时需要对类型变量进行作用域。

{-# LANGUAGE ScopedTypeVariables #-}

import Data.Typeable

f :: forall a b. Typeable b => a -> b
f = impl
  where
    bTypeRep = typeOf $ (undefined :: Typeable b => (a -> b) -> b) impl
    impl = undefined
于 2013-05-30T17:27:11.133 回答
0

下面解决了这个问题。感谢luqui

{-# LANGUAGE ScopedTypeVariables #-}

import Data.Typeable

f :: forall a b . Typeable b => a -> b
f = undefined
  where
    bTypeRep = typeOf $ (undefined :: b)

我愿意接受另一个答案,解释为什么forall a b .零件会有所作为,以及可能的其他解决方案。

于 2013-05-30T17:26:42.183 回答