将函数调用移动到where子句使用OverlappingInstances打破类型检查器

时间:2016-08-10 18:22:03

标签: haskell overlapping-instances

当我没有为某种类型提供自定义实例时,我正在使用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会欺骗类型检查器,使其View需要Show,而不是<div *ngIf=result.isImageExists()> <img [src]="result.image" /> </div> <div *ngIf=!result.isImageExists()> <img [src]="result.defaultImage" /> </div>

2 个答案:

答案 0 :(得分: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" ++ ")"

答案 1 :(得分:0)

感谢@dfeuer提供替代方法,但我认为我应该为问题本身编写相当快速的修复方法:

{-# LANGUAGE MonoLocalBinds #-}

一旦将它放在文件的顶部,一切正常。从我进行的研究看来,似乎某些扩展(我想包括OverlappingInstances)在本地绑定类型检查中戳孔,而MonoLocalBinds牺牲使用局部绑定以多态方式来修复这些漏洞。