gpt4 book ai didi

haskell - 将函数调用移动到 where 子句会破坏带有重叠实例的类型检查器

转载 作者:行者123 更新时间:2023-12-02 12:54:21 26 4
gpt4 key购买 nike

我使用 OverlappingInstances 制作一个 pretty-print 类,每当我没有为某种类型提供自定义实例时,该类就会默认为 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,当事实并非如此。

最佳答案

类型族方法如下所示:

{-# 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" ++ ")"

关于haskell - 将函数调用移动到 where 子句会破坏带有重叠实例的类型检查器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38880858/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com