【问题标题】:Type family error类型族错误
【发布时间】:2018-06-04 09:53:00
【问题描述】:

您好,我编写了我的第一个类型为 family 的程序

{-# LANGUAGE TypeFamilies #-}

data Colist a = Colist (Maybe (a,Colist a))

class Listable l where type Item l :: *
    toList :: l -> [Item l]

instance Listable (Colist a) where 
    type Item (Colist a) = (Colist a)
    toList x = [x]

程序应该将 Colist a 放入列表中 我收到“项目 l”无法与实际类型“l”匹配的错误。但我写的是 Item x EQUALS (Colist a)。我的错在哪里?

【问题讨论】:

  • 我想你的意思是type Item (Colist a) = a。您可能的意思是 toListListable 的一种方法?
  • 如果你想要一个好的解释,你需要包含导致错误的代码。此代码加载得很好(在修复缩进错误之后)。这就是说:这是因为,像所有类型族的初学者一样,您还没有理解“类型族不是单射的”是什么意思。
  • imgur.com/a/bIjXI 我收到此错误
  • 不要在 SO 上发布文本图像 - 将实际的错误文本消息复制并粘贴到您的问题中,这样每个人都会注意到并立即阅读。将重要信息隐藏在图片链接下可以减少其他人直接跳过问题而没有提供任何帮助的可能性。

标签: haskell types functional-programming type-families


【解决方案1】:

你是说……

{-# LANGUAGE TypeFamilies #-}

newtype List a = List (Maybe (a, List a))

class Listable l where
    type Item l :: *
    toList :: l -> [Item l]

instance Listable (List a) where
    type Item (List a) = a

    toList (List Nothing) = []
    toList (List (Just (x, xs)) = x : toList xs

我对您的代码进行了一些更改。零,我将Colist 重命名为List(因为在Haskell 中不存在协约列表之类的东西)。一,我修复了缩进,使toList成为Listable类的方法。第二,我让List aItem 实例返回a,而不是List a。三,我修复了 toList 以实际返回 List 的元素列表 - 您的版本只是将整个 List 放在一个单例列表中。

我强烈怀疑你在这里滥用类型族。这是这个类的一个更简单、更类似于 Haskell 的表述:

class Listable l where
    toList :: l a -> [a]

instance Listable List where
    toList (List Nothing) = []
    toList (List (Just (x, xs)) = x : toList xs

或者您可以直接派生Foldable 并免费获得toList

newtype List a = List (Maybe (a, List a)) deriving Foldable

ghci> import Data.Foldable
ghci> toList $ List (Just ('a', List Nothing))
"a"

【讨论】:

  • 归纳列表应该是data List a = Nil | Cons !a !(List a),不是吗?
  • 另外...我不认为MonoFoldable 的精简版是不合理的。与FunctorTraverseable 不同,更高级别的Foldable 仅在特殊情况下(例如多态递归)提供额外的功能。还有一些重要的实例,比如未装箱的数组,不能是Foldable
  • @dfeuer 我从来没有说过这是不合理的,MonoFoldable 确实是一个有用的类。不过,通过阅读问题,我怀疑提问者是初学者,所以对我来说,将提问者指向Foldable 感觉在教学上是合理的:)
  • 我的意思是说,如果您是初学者,并且正在学习使用班级系统
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多