我使用OverlappingInstances
来制作一个漂亮的打印类,当我没有为某些类型提供自定义实例时,它将默认为Show
。
由于某些原因,当您使用where
子句或let
表达式时,这似乎会中断。
{-# LANGUAGE FlexibleInstances, UndecidableInstances #-}
class View a where
view :: a -> String
instance {-# OVERLAPS #-} Show a => View a where
view = show
-- Works just fine
instance (View a, View b) => View (a, b) where
view (a, b) = "(" ++ view a ++ ", " ++ view b ++ ")"
-- Does not work
instance (View a, View b) => View (a, b) where
view (a, b) = "(" ++ a' ++ ", " ++ b' ++ ")"
where
a' = view a
b' = view b
-- Does not work
instance (View a, View b) => View (a, b) where
view (a, b) = let
a' = view a
b' = view b
in "(" ++ a' ++ ", " ++ b' ++ ")"
现在,如果我删除默认的重叠实例,所有其他实例都可以正常工作。
我希望有人能向我解释为什么会发生这种情况,或者它只是一个bug?
我得到的具体错误是:
Could not deduce (Show a) arising from a use of ‘view’ from the context (View a, View b) bound by the instance declaration at ...
Could not deduce (Show b) arising from a use of ‘view’ from the context (View a, View b) bound by the instance declaration at ...
所以出于某种原因,where
/let
欺骗类型检查器认为View
需要Show
,当它不需要时。
类型族方法如下:
{-# LANGUAGE TypeFamilies, MultiParamTypeClasses,
FlexibleInstances, DataKinds, KindSignatures,
ScopedTypeVariables #-}
import Data.Proxy
data Name = Default | Booly | Inty | Pairy Name Name
type family ViewF (a :: *) :: Name where
ViewF Bool = 'Booly
ViewF Int = 'Inty
ViewF Integer = 'Inty --you can use one instance many times
ViewF (a, b) = 'Pairy (ViewF a) (ViewF b)
ViewF a = 'Default
class View (name :: Name) a where
view' :: proxy name -> a -> String
instance (Show a, Num a) => View 'Inty a where
view' _ x = "Looks Inty: " ++ show (x + 3)
instance a ~ Bool => View 'Booly a where
view' _ x = "Looks Booly: " ++ show (not x)
instance Show a => View 'Default a where
view' _ x = "Looks fishy: " ++ show x
instance (View n1 x1, View n2 x2) => View ('Pairy n1 n2) (x1, x2) where
view' _ (x, y) = view' (Proxy :: Proxy n1) x ++ "," ++ view' (Proxy :: Proxy n2) y
view :: forall a name .
(ViewF a ~ name, View name a)
=> a -> String
view x = view' (Proxy :: Proxy name) x
-- Example:
hello :: String
hello = "(" ++ view True ++ view (3 :: Int)
++ view "hi" ++ ")"
感谢@dfeuer提供的替代方法,但我认为我应该为问题本身编写相当快速的修复:
{-# LANGUAGE MonoLocalBinds #-}
一旦它被放在文件的顶部,一切都很好。从我所做的研究来看,似乎某些扩展(我猜包括OverlappingInstances
)在本地绑定类型检查中戳了洞,而MonoLocalBinds
牺牲了多态使用本地绑定来修复这些洞。