Haskell Typeclass声明类型不匹配

Haskell Typeclass声明类型不匹配,haskell,Haskell,我试图使我的单元格类型成为显示类型类的成员。显示行有问题。在这种情况下,如何确保a是Char?我希望语句的顺序能让fallthrough处理它,但那不行 data Cell = Solid | Blank | Char instance Show (Cell) where show Solid = "X" show Blank = "_"; show a = [a] main = print $ show Solid Char这里不是类型Char;它是一个名为Ch

我试图使我的
单元格
类型成为
显示
类型类的成员。
显示
行有问题。在这种情况下,如何确保
a
Char
?我希望语句的顺序能让fallthrough处理它,但那不行

data Cell = Solid | Blank | Char

instance Show (Cell) where
    show Solid = "X"
    show Blank  = "_";
    show a = [a]

main = print $ show Solid

Char
这里不是类型
Char
;它是一个名为
Char
的新数据构造函数。如果希望
单元格
实心
空白
,或类型为
字符
的值,则需要

data Cell = Solid | Blank | Char Char

instance Show Cel where
    show Solid = "X"
    show Blank = "_"
    show (Char c) = [c]
一些例子:

> show Solid
"X"
> show Blank
"_"
> show (Char '4')
"4"

查看类型类
Show
的定义,主要是
Show
功能:

class Show a where
    show      :: a   -> String

现在,您的
单元格
类型的实例是否满足它?第一种情况下,
show Solid=“X”
does-
Solid
Cell
“X”
是一个字符串。第二种情况也是如此。但第三种情况是什么?您将其定义为
show a=[a]
,因此类型签名是
Cell->[Cell]
,而
[Cell]
不是
字符串。因此会出现类型不匹配。

您无法确保
a
Char
类型的值,因为事实并非如此
a
将始终是类型为
Cell
的值,特别是值
Char
(与类型
Char
无关)

您似乎希望
单元格的第三个构造函数包含
Char
类型的值。为此,构造函数需要一个参数:

data Cell = Solid | Blank | CharCell Char

instance Show (Cell) where
    show Solid = "X"
    show Blank  = "_"
    show (CharCell a) = [a]
如果已使用构造函数
CharCell
,则
CharCell a
大小写匹配,并且
a
将作为
CharCell
的参数使用(因此,type
Char
CharCell
的参数类型相同)

这是一个,这意味着
Solid
Blank
Char
是构造函数名称,而不是类型。例如,
Char::Cell

我怀疑你的意思是这样的:

data CellType = CellConstructor Char

instance Show CellType where
  show (CellConstructor c) = [c]
示例:

  • CellConstructor'X':CellType
  • CellConstructor'.'::CellType
  • CellConstructor'a':CellType
如果只有一个构造函数,则通常为类型和构造函数指定相同的名称

data Cell = Cell Char
如果只有一个构造函数只有一个字段,则通常使用newtype

newtype Cell = Cell Char 
newtype Cell = Cell Char