gpt4 book ai didi

haskell - 类型族内的多态函数

转载 作者:行者123 更新时间:2023-12-04 18:06:47 24 4
gpt4 key购买 nike

我试图在类型系列中定义一个函数,该函数在类型系列中定义的 GADT 本身的幻影类型上是多态的。

我的类型族定义是这样的:

class Channel t where
data Elem t a :: *
foo :: t -> Elem t a
bar :: Elem t a -> [a]

我有一个实例如下:
data MyChannelType = Ch

instance Channel MyChannelType where

data Elem MyChannelType a where
MyConstructor :: Char -> Elem MyChannelType Char

foo _ = MyConstructor 'a'

bar (MyConstructor c) = repeat c

编译器提示说:
Couldn't match type ‘a’ with ‘Char’
‘a’ is a rigid type variable bound by
the type signature for foo :: MyChannelType -> Elem MyChannelType a

是否可以使用 Rank2Types 编写此函数或重新制定我的数据类型以启用它?

编辑 :回应 Ganesh 要求的澄清

我想要 foo (bar Ch) :: [Int]是非法的。

我一直在使用 Ganesh 建议的解决方案,但我受到以下更复杂示例的启发,该示例失败了;给出:
data MyOtherType = IntCh | StringCh

我有一个实例如下:
instance Channel MyOtherType where

data Elem MyOtherType a where
ElemInt :: Int -> Elem MyOtherType Int
ElemString :: String -> Elem MyOtherType String

foo IntCh = ElemInt 0
foo StringCh = ElemString "a"

bar (ElemInt i) = repeat i
bar (ElemString s) = repeat s

非常感谢,

迈克尔

最佳答案

使用您提供的签名,foo对于 MyChannelType 无法实现因为它声称可以生产Elem MyChannelType a对于任何 a类型。

如果您真正想要的是应该只有一个 a给定的类型 t ,您可以使用类型函数来表达这一点:

class Channel t where
data Elem t a :: *
type Contents t :: *

foo :: t -> Elem t (Contents t)
bar :: Elem t a -> [a]

然后添加
type Contents MyChannelType = Char

到实例。

为了回应你的编辑,我会分手 Channel分为两类:
class Channel t where
data Elem t a :: *
bar :: Elem t a -> [a]

class Channel t => ChannelContents t a where
foo :: t -> Elem t a

然后您可以定义 MyOtherType实例:
instance Channel MyOtherType where

data Elem MyOtherType a where
ElemInt :: Int -> Elem MyOtherType Int
ElemString :: String -> Elem MyOtherType String

bar (ElemInt i) = repeat i
bar (ElemString s) = repeat s

instance ChannelContents MyOtherType Int where
foo IntCh = ElemInt 0

instance ChannelContents MyOtherType String where
foo StringCh = ElemString "a"

您需要启用一些扩展: MultiParamTypeClasses , TypeSynonymInstances , FlexibleInstances (后两个只是因为 String 实例)。

关于haskell - 类型族内的多态函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25255720/

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