gpt4 book ai didi

haskell - TypeFamilies 或 GADT 突然破坏了有效代码

转载 作者:行者123 更新时间:2023-12-04 06:31:14 25 4
gpt4 key购买 nike

我的代码看起来很无辜

data Config = Config
{ cInts :: [Int]
, cStrings :: [String] }

instance Semigroup Config where
c1 <> c2 = Config
{ cInts = andCombiner cInts
, cStrings = andCombiner cStrings }
where
andCombiner field = field c1 <> field c2

它编译并且工作正常。但是,如果我添加 TypeFamiliesGADTs扩展我看到非常奇怪的错误:
.../Main.hs:19:22: error:
• Couldn't match type ‘Int’ with ‘[Char]’
Expected type: [String]
Actual type: [Int]
• In the ‘cStrings’ field of a record
In the expression:
Config {cInts = andCombiner cInts, cStrings = andCombiner cStrings}
In an equation for ‘<>’:
c1 <> c2
= Config
{cInts = andCombiner cInts, cStrings = andCombiner cStrings}
where
andCombiner field = field c1 <> field c2
|
19 | , cStrings = andCombiner cStrings }
| ^^^^^^^^^^^^^^^^^^^^

.../Main.hs:19:34: error:
• Couldn't match type ‘[Char]’ with ‘Int’
Expected type: Config -> [Int]
Actual type: Config -> [String]
• In the first argument of ‘andCombiner’, namely ‘cStrings’
In the ‘cStrings’ field of a record
In the expression:
Config {cInts = andCombiner cInts, cStrings = andCombiner cStrings}
|
19 | , cStrings = andCombiner cStrings }
| ^^^^^^^^

此编译器错误的原因可能是什么?

最佳答案

这是由于 -XMonoLocalBinds 其中-XGADTs-XTypeFamilies意味着。您可以通过将类型签名添加到 andCombiner 来让您的代码再次编译。 (或通过打开 -XNoMonoLocalBinds ,尽管我不建议这样做):

instance Semigroup Config where
c1 <> c2 = Config
{ cInts = andCombiner cInts
, cStrings = andCombiner cStrings }
where
andCombiner :: Semigroup a => (Config -> a) -> a
andCombiner field = field c1 <> field c2

使用我链接的 GHC 文档中的术语, andCombiner没有完全概括,因为它提到了 c1c2没有关闭或导入的。

关于haskell - TypeFamilies 或 GADT 突然破坏了有效代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48029598/

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