Haskell实例包装[]

问题描述 投票:4回答:1

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

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

我确定这一定有可能,但我想念咒语。非常感谢收到的所有指针。

haskell
1个回答
4
投票

您的最后一次尝试是最接近的一次,但是您需要一个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
  |                         ^^
© www.soinside.com 2019 - 2024. All rights reserved.