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
的参数使用(因此,typeChar
与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