gpt4 book ai didi

haskell - 顶级 OverloadedLists 字面量

转载 作者:行者123 更新时间:2023-12-03 15:02:45 31 4
gpt4 key购买 nike

我有一个用于重构练习的测试套件,我希望它与 Data.List 兼容。和 Data.List.NonEmpty .练习包含一个函数 foo :: [Foo] -> Foo并且测试套件有一些

data Case = Case
{ description :: String
, input :: [Foo]
, expected :: Foo
}

cases :: [Case]
cases =
[ Case { description = "blah blah"
, input = [Foo 1, Foo 2, Foo 3]
, expected = Foo 1
}
, ...
]

使用 OverloadedLists 使测试套件具有多态性, 我试过了

{-# LANGUAGE OverloadedLists #-}
...

data Case list = Case
{ description :: String
, input :: list Foo
, expected :: Foo
}

cases =
[ Case { description = "blah blah"
, input = [Foo 1, Foo 2, Foo 3]
, expected = Foo 1
}
, ...
]

但这给了我错误
    • Couldn't match expected type ‘GHC.Exts.Item (list0 Foo)’
with actual type ‘Foo’
The type variable ‘list0’ is ambiguous
...
|
50 | , input = [Foo 1, Foo 2, Foo 3]
| ^^^^^

我想移动 IsList listCase 的约束数据类型,像这样

{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedLists #-}
...

data Case list where
Case :: IsList list => String -> list Foo -> Foo -> Case list

cases =
[ Case "blah blah" [Foo 1, Foo 2, Foo 3] (Foo 1), ... ]

但这给了我错误
    • Expected kind ‘* -> *’, but ‘list’ has kind ‘*’
• In the type ‘list Foo’
In the definition of data constructor ‘Case’
In the data declaration for ‘Case’
|
24 | Case :: IsList list => String -> list Foo -> Foo -> Case list
| ^^^^^^^^

我不确定这里最简单的方法是什么。有什么提示吗?

最佳答案

这不起作用的原因是因为 Item List (l Foo) => l 的类型本身不是 Foo .扩展对其进行了抽象,因此它期望列表文字的元素为 Item (l Foo) 类型.

但是,您可以添加一个类型约束,表明这些项目确实属于 Foo 类型。 :

{-# LANGUAGE OverloadedLists #-}

data Case list = Case
{ description :: String
, input :: list Foo
, expected :: Foo
}

cases :: (IsList (l Foo), Item (l Foo) ~ Foo) => [Case l]
cases = [
Case { description = "blah blah"
, input = [Foo 1, Foo 2, Foo 3]
, expected = Foo 1
}
]

在这里,我们因此说 Item (l Foo)应与 Foo 相同.

关于haskell - 顶级 OverloadedLists 字面量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59173478/

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