在 Haskell 中键入参数
type parameters in Haskell
我想创建一个 Pixel 类型,并使其成为 Eq 和 Show class 的一个实例。但是,我一直在阅读很多地方的信息,并且对此感到非常困惑。
这是我需要创建的类型的一些信息:
我必须存储两个数字(像素的位置和一个从 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
这样做正确吗?
类型名称必须以大写字母开头。所以,你的定义实际上应该是这样的,因为你只定义类型同义词:
type Position = Float
type GreyScale = Int
对于Pixel
:看起来你想定义一个数据类型,而不仅仅是一个同义词,所以你应该这样做:
data Pixel = Pixel Position GreyScale
下一步:Eq
实例比较两个 Pixel
,所以你必须这样表示它们:
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
我想创建一个 Pixel 类型,并使其成为 Eq 和 Show class 的一个实例。但是,我一直在阅读很多地方的信息,并且对此感到非常困惑。
这是我需要创建的类型的一些信息:
我必须存储两个数字(像素的位置和一个从 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
这样做正确吗?
类型名称必须以大写字母开头。所以,你的定义实际上应该是这样的,因为你只定义类型同义词:
type Position = Float
type GreyScale = Int
对于Pixel
:看起来你想定义一个数据类型,而不仅仅是一个同义词,所以你应该这样做:
data Pixel = Pixel Position GreyScale
下一步:Eq
实例比较两个 Pixel
,所以你必须这样表示它们:
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