2015-01-17 137 views
1

我想创建一个Pixel类型,并使其成为Eq和Show类的一个实例。但是,我一直在阅读很多地方的信息,并对此感到困惑。Haskell中的类型参数

下面是关于类型的一些信息我需要创建:

我必须存储两个数字(像素的位置,从0到255之间的值)。 如果它们具有相同的值,则无论它们的位置如何,两个像素都是相等的。 对于Show实例,我需要打印位置和值。

这是我尝试在此:

type position = Float 
type greyScale = Int 
type Pixel = (position, greyScale) 

instance Eq Pixel where 
    greyScale == greyScale = True 

instance Show Pixel where 
    show position = position 
    show greyScale = greyScale 

这是做正确的方式?

+0

而对于更多的例子:[learnyouahaskell.com](http://learnyouahaskell.com/making-our-own-类型和 - 类型类) – phg

回答

4

类型名称必须以大写字母开头。所以,你的定义,实际上应该是这样的,因为你只能定义类型的同义词:

type Position = Float 
type GreyScale = Int 

对于Pixel:它看起来像你想定义的数据类型,而不是只是一个代名词,所以你应该这样做这样的:

data Pixel = Pixel Position GreyScale 

下一篇:Eq实例比较两个Pixel S,所以你必须要代表他们这样:

instance Eq Pixel where 
    Pixel pos1 greyScale1 == Pixel pos2 greyScale2 = greyScale1 == greyScale2 

greyScale1 == greyScale2只是比较两个greyScales,这是你想要的。

此外,我不会建议覆盖Show实例以确保read . show == id成立。 (您可以通过在数据类型声明后添加deriving (Instance1, Instance2, ..)来自动导出特定实例)。而不是与它插手我将定义独立的功能:

showPosition :: Pixel -> String 
showPosition (Pixel position greyScale) = show position 

showGreyscale :: Pixel -> String 
showGreyscale (Pixel position greyScale) = show greyScale