我制作了一个图像处理模块,将Pixel类型定义为 aColor和Location。Pixel,Color和Locationderived Eq,因为我可能想比较多个图像之间的像素。
Eq适合我比较像素以查看它们是否完全相同的需要,这正是我想要的。实例化的一个奇怪的副作用Eq是,将 2 个不同的像素与相同Location的像素进行比较<=,>=结果为True,但False为==、<和>。
data Color = Color { red :: Int
, green :: Int
, blue :: Int
, alpha :: Int
} deriving ( Show, Eq )
data Location = Location { x :: Int
, y :: Int
} deriving ( Show, Eq, Ord )
data Pixel = Pixel { color :: Color
, location :: Location
} deriving ( Show, Eq )
instance Ord Pixel where
compare (Pixel _ a) (Pixel _ b) = compare a b
然后在ghci中进行一些测试。
>let a = Pixel (Color 0 0 0 255) (Location 0 0)
>let b = Pixel (Color 0 0 1 255) (Location 0 0)
>let c = Pixel (Color 0 0 0 255) (Location 0 0)
>let d = Pixel (Color 0 0 0 255) (Location 0 1)
>a == b
False
>a /= b
True
>a < b
False
>a > b
False
>a <= b
True
>a >= b
True
>a == c
True
>a /= c
False
>a > c
False
>a < c
False
>a >= c
True
>a <= c
True
>a == d
False
>a /= d
True
>a > d
False
>a < d
True
a >= d
False
a <= d
True
似乎我Ord对 a 的定义Pixel影响了这些比较,这是可以理解的。d表明Location影响比较。我感到困惑的部分是a是既>=和<= b而不是==, <, or >。
编辑:如果有人想使用此代码中的任何一个,我将包含此解决问题的代码段。请务必Eq从Pixel定义中删除。
instance Eq Pixel where
(Pixel _ a) == (Pixel _ b) = a == b
(Pixel _ a) /= (Pixel _ b) = a /= b
这仅允许比较Location。享受!:)