使用GHC 8.0,我可以编写一个模棱两可的函数,该函数在其类型签名的主要部分中未提及的某个类型上重载,然后使用显式类型应用程序对其进行调用:
{-# LANGUAGE ScopedTypeVariables, RankNTypes,
AllowAmbiguousTypes, TypeApplications, TypeFamilies #-}
showRead :: forall t . (Read t, Show t) => String -> String
showRead x = show (read x :: t)
showReadInt = showRead @Int
我想使用一种SPECIALIZE
编译指示来强制showRead
for的特殊化Int
(我的真实代码在另一个模块中具有实际的调用站点)。但是,常规SPECIALIZE
语法基于编写类型签名的主要部分,例如:
{-# SPECIALIZE showRead :: String -> String #-}
在这种情况下,我无法指定t
应有的内容,并且可以预料地给出有关其模棱两可的错误。
我尝试使用相等约束:
{-# SPECIALISE showRead :: forall t . (Read t, Show t, t ~ Int) => String -> String #-}
但这只是错误:
• Could not deduce (Read t0) a SPECIALISE pragma for ‘showRead’ from the context: (Read t, Show t, t ~ Int) bound by the type signature for: showRead :: (Read t, Show t, t ~ Int) => String -> String at foo.hs:4:1-76 The type variable ‘t0’ is ambiguous
有什么办法可以做到吗?当然,我可以使用Proxy
,但是不使用闪亮的新方法似乎很可惜。
GHC 8.0不支持此功能,但现在是提议在将来的GHC中支持它的主题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句