[英]Creating an instance for a new type
我在Haskell中创建了一个代表像素的类型,如下所示:
data Pixel = Pixel Float Float Int deriving (Eq, Show)
在这里,第一个浮点数对应于像素在x轴上的位置,第二个浮点数代表在y轴上的位置(因此基本上我在“屏幕”上具有2个坐标),并且Int
是其灰度值。
我想创造和实例Eq
为Pixel
,其中像素是彼此相等,如果它们的灰度值是相同的,而不管其位置的。
到目前为止,我已经做到了:
instance Eq Pixel where
但是现在我不知道如何检查它们是否相同,我的意思是,我怎么说我在这里有2个不同的Pixels,我想比较它们的Int
? 我不能做这样的事情
grey1 == grey2 = True
因为我不知道grey1
和grey2
来源。
我该怎么做?
另外,在为Show
创建实例时,如何引用浮点数和整数?
像这样吗
data Pixel = Pixel Float Float Int
instance Eq Pixel where
Pixel _ _ g1 == Pixel _ _ g2 = g1 == g2
instance Show Pixel where
show ( Pixel x y g ) = "Pixel " ++ show g ++ " at (" ++ show x ++ "," ++ show y ++ ")"
请改用记录语法 !
data Pixel = Pixel { xPos :: Float
, yPos :: Float
, value :: Int
}
xPos
, yPos
和value
具有类型Pixel -> Float
和Pixel -> Int
,这将使某些操作比模式匹配更容易。
但是,使其成为适当类的实例就足够了(示例):
instance Show Pixel where
show (Pixel x y g) = "[" ++ show x ++ ", " ++ show y ++ "(" ++ show g ++ ")]"
instance Eq Pixel where
(Pixel _ _ valA) == (Pixel _ _ valB) = valA == valB
与实际使用的记录语法相同:
instance Show Pixel where
show pixel = "[" ++ show (xPos pixel) ++ ", " ++ show (yPos pixel) ++ "(" ++ show (value pixel) ++ ")]"
instance Eq Pixel where
a == b = (value a) == (value b)
您可能需要修改示例。 它们仅用于说明目的。
您要做的是在Pixel
的构造函数上进行模式匹配 。 这就是您编写“拆分”类型的函数的方式。 模式匹配使用case
语句进行
case pixel of
Pixel x y grey -> ...
作为语法糖,也可以直接在定义中使用
getX :: Pixel -> Double
getX (Pixel x y grey) = x
-- same as
getX :: Pixel -> Double
getX px = case px of
Pixel x y grey -> x
所以我们要做两次以创建一个相等函数
instance Eq Pixel where
Pixel x1 y1 grey1 == Pixel x2 y2 grey2 = grey1 == grey2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.