所以有一天我想出了如何写这个函数(需要base-4.7.0.0
或更晚):
{-# LANGUAGE ScopedTypeVariables, TypeOperators, GADTs #-}
import Data.Typeable
-- | Test dynamically whether the argument is a 'String', and boast of our
-- exploit if so.
mwahaha :: forall a. Typeable a => a -> a
mwahaha a = case eqT :: Maybe (a :~: String) of
Just Refl -> "mwahaha!"
Nothing -> a
所以我被带走了,并决定尝试使用它来编写一个测试其参数类型是否为Show
实例的函数。如果我理解正确,这应该不起作用,因为TypeRep
仅存在于单态类型中。所以这个定义自然不会出现问题:
isShow :: forall a b. (Typeable a, Typeable b, Show b) => a -> Bool
isShow a = case eqT :: Maybe (a :~: b) of
Just Refl -> True
Nothing -> False
{-
/Users/luis.casillas/src/scratch.hs:10:11:
Could not deduce (Typeable b0)
arising from the ambiguity check for ‘isShow’
from the context (Typeable a, Typeable b, Show b)
bound by the type signature for
isShow :: (Typeable a, Typeable b, Show b) => a -> Bool
at /Users/luis.casillas/src/scratch.hs:10:11-67
The type variable ‘b0’ is ambiguous
In the ambiguity check for:
forall a b. (Typeable a, Typeable b, Show b) => a -> Bool
To defer the ambiguity check to use sites, enable AllowAmbiguousTypes
In the type signature for ‘isShow’:
isShow :: forall a b. (Typeable a, Typeable b, Show b) => a -> Bool
-}
但请注意消息To defer the ambiguity check to use sites, enable AllowAmbiguousTypes
。如果我启用该pragma,定义类型检查,但是......
{-# LANGUAGE ScopedTypeVariables, TypeOperators, GADTs #-}
{-# LANGUAGE AllowAmbiguousTypes #-}
import Data.Typeable
isShow :: forall a b. (Typeable a, Typeable b, Show b) => a -> Bool
isShow a = case eqT :: Maybe (a :~: b) of
Just Refl -> True
Nothing -> False
{- Typechecks, but...
>>> isShow 5
False
>>> isShow (id :: String -> String)
False
-}
这里发生了什么?编译器为b
选择什么类型的?它是一个Skolem类型变量,àlaExistentialTypes
?
哦,呃,我刚问了这个问题,并迅速想出了如何回答:
whatsTheTypeRep :: forall a b. (Typeable a, Typeable b, Show b) => a -> TypeRep
whatsTheTypeRep a = typeRep (Proxy :: Proxy b)
{-
>>> whatsTheTypeRep 5
()
>>> isShow ()
True
-}
我仍然有兴趣听听这里发生了什么。这是违约规则吗?
答案 0 :(得分:13)
开启-Wall
,您就会得到答案:)
<interactive>:50:11: Warning:
Defaulting the following constraint(s) to type ‘()’
(Typeable b0)
arising from the ambiguity check for ‘isShow’
at <interactive>:50:11-67
(Show b0)
arising from the ambiguity check for ‘isShow’
at <interactive>:50:11-67
In the ambiguity check for:
forall a b. (Typeable a, Typeable b, Show b) => a -> Bool
In the type signature for ‘isShow’:
isShow :: forall a b. (Typeable a, Typeable b, Show b) => a -> Bool
(是的,它是默认规则)