Haskell:显示/递归数据类型的非法实例声明

时间:2015-11-28 17:23:12

标签: haskell

我一直在寻找这个,但我找不到一些可靠的东西。

我用我自己的数据类型创建自己的模块,然后我尝试制作一个show实例,那就是事情变得混乱的时候。我会告诉你

data listOfFav a = Insert (a,Bool) (listOfFav a) | Empty deriving (Show)

instance Show a => Show (listOfFav a) where
  show = ('{' :) . go
   where
      go Empty                 = "}"
      go (Insert (x,y) Vazia)  = show x ++ show y ++ "}"
      go (Insert (x,y) xs)     = show x ++ show y ++", " ++ go xs

由于某种原因,我收到了这个错误:

Illegal instance declaration for ‘Show (listaFavoritos a)’
  (All instance types must be of the form (T a1 ... an)
   where a1 ... an are *distinct type variables*,
   and each type variable appears at most once in the instance head.
   Use FlexibleInstances if you want to disable this.)
In the instance declaration for ‘Show (listaFavoritos a)’

如果有人能帮助我,我会非常感激

1 个答案:

答案 0 :(得分:2)

Haskell要求数据类型以大写字母开头。您的代码应如下所示:

data ListOfFav a = Insert (a,Bool) (ListOfFav a) | Empty

instance Show a => Show (ListOfFav a) where
  show = ('{' :) . go
   where
      go Empty                 = "}"
      go (Insert (x,y) Empty)  = show x ++ show y ++ "}"
      go (Insert (x,y) xs)     = show x ++ show y ++", " ++ go xs

此外,Haskell每个数据类型只允许一个Show个实例。您可以使用deriving Show让Haskell编译器为您创建一个或者您自己编写,但不能同时执行这两个操作。在上面的代码中,我删除了deriving Show以使手写实例优先。