如果有这个:
data Rectangle = Rectangle Height Width
data Circle = Circle Radius
class Shape a where
area :: a -> Float
perimeter :: a -> Float
instance Shape Rectangle where
area (Rectangle h w) = h * w
perimeter (Rectangle h w) = 2*h+w*2
instance Shape Circle where
area (Circle r) = pi * r**2
perimeter (Circle r) = 2*pi*r
volumenPrism base height = (area base) * height
surfacePrism shape h = (area shape) * 2 + perimeter shape * h
为什么我不能写这个呢?
a
是一种类型,为什么这不起作用呢?instance (Shape a) => Eq a where
x==y = area x == area y
很明显地,要做到这样:
instance Eq Circle where
x==y = area x == area y
首先对于圆形,然后对于矩形进行操作是可行的,但似乎不是正确的方法。
在这一切中,我没有理解哪一部分。
谢谢
instance Shape a => Eq a
的意思是“所有类型都使用这个定义作为Eq
实例。使用此实例会使得使用的类型添加一个Shape
约束条件。” - CarlIncoherentInstances
等弯曲得相当厉害了,所以我不认为这一切都完全自然地遵循那个假设。 - GS - Apologise to Monica