【发布时间】:2019-02-25 18:08:13
【问题描述】:
我需要一个方法来根据类的特定实例有条件地应用函数。
我尝试使用 Proxy 用其输入的类型来注释函数:
class ApplyIf b where
applyIf :: Show b => proxy a -> (a -> a) -> b -> String
instance ApplyIf Int where
applyIf (p :: Proxy Int) f b = show (f b)
applyIf _ _ b = show b
instance ApplyIf String where
applyIf _ _ b = show b
main = do
putStrLn $ applyIf (Proxy:: Proxy Int) (*2) 1 -- 2
putStrLn $ applyIf (Proxy:: Proxy Int) (*2) "ok" -- ok
但我在第 5 行收到“非法类型签名:“代理 Int”错误。
我是否应该使用其他一些机制,例如 Tagged、Typeable、...?
【问题讨论】:
-
要放置该类型签名,您需要
ScopedTypeVariables。实例 decl 中的Proxy Int比实例头部的预期更具体。试试applyIf (p :: proxy Int) f b = ...。 -
您是否尝试对类型进行模式匹配?从这段代码片段中很难看出你的最终目标是什么。
-
applyIf (Proxy:: Proxy Int) (*2) "ok"不应该进行类型检查,因为b是String并且(*2)不会返回String。 -
我需要在类定义中将 (a -> b) 替换为 (a ->a)。
标签: haskell