gpt4 book ai didi

Haskell 实例包装 []

转载 作者:行者123 更新时间:2023-12-01 00:10:21 25 4
gpt4 key购买 nike

我正在尝试创建一个包装 [] 的类型的实例;即,

instance Foo (NonNull []) where

(其中 NonNull 是 Michael Snoyman 的 Data.NonNull )这适用于,比如说,

instance Foo [] where

但是使用 NonNull [],我得到了

Expected kind ‘* -> *’, but ‘NonNull []’ has kind ‘*’

我已经尝试使用 RankNTypes 来提供一个明确的 forall:

instance ∀ α . Foo (NonNull [α]) where

结果类似:

Expected kind ‘* -> *’, but ‘NonNull [α]’ has kind ‘*’

还有一个类型同义词:

type NonNullList α = NonNull [α]
instance ToSeq NonNullList where

给出:

The type synonym ‘NonNullList’ should have 1 argument, but has been given none

我确信这一定是可能的,但我错过了咒语。非常感谢收到任何指示。

最佳答案

你最后一次尝试是最接近的一次,但你需要一个 newtype 而不是 type 同义词(data 也可以):

newtype NonNullList α = NonNullList (NonNull [α])

instance ToSeq NonNullList where ...
您首先尝试的

NonNull [] 没有意义,因为 NonNull 的参数必须是一个类型(如 [Int] ), 而不是像 [] 这样的类型构造函数。您应该会看到第二个错误,例如 in this similar example :

instance Functor (Maybe []) where

main.hs:5:19: error:
• Expected kind ‘* -> *’, but ‘Maybe []’ has kind ‘*’
• In the first argument of ‘Functor’, namely ‘(Maybe [])’
In the instance declaration for ‘Functor (Maybe [])’
|
5 | instance Functor (Maybe []) where
| ^^^^^^^^
main.hs:5:25: error:
• Expecting one more argument to ‘[]’
Expected a type, but ‘[]’ has kind ‘* -> *’
• In the first argument of ‘Maybe’, namely ‘[]’
In the first argument of ‘Functor’, namely ‘(Maybe [])’
In the instance declaration for ‘Functor (Maybe [])’
|
5 | instance Functor (Maybe []) where
| ^^

关于Haskell 实例包装 [],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59319013/

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