3

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' ++ ")"

现在,如果我删除默认的重叠实例,所有其他实例都可以正常工作。

我希望有人可以向我解释为什么会发生这种情况,还是只是一个错误?

我为每个人得到的具体错误是:

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正在欺骗类型检查器认为Viewrequires Show,而实际上不需要。

4

2 回答 2

0

类型族方法如下所示:

{-# 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" ++ ")"
于 2016-08-11T18:08:58.020 回答
0

感谢@dfeuer 提供了一种替代方法,但我认为我应该为问题本身编写相当快速的解决方案:

{-# LANGUAGE MonoLocalBinds #-}

一旦将其放在文件的顶部,一切都会正常工作。从我所做的研究来看,某些扩展(我猜包括)似乎OverlappingInstances在本地绑定类型检查中戳了一个洞,并且MonoLocalBinds牺牲了多态地使用本地绑定来修复这些漏洞。

于 2016-08-28T21:58:40.037 回答