不同类型的列表? [英] List of different types?
问题描述
data Plane = Plane { point :: Point, normal :: Vector Double }
data Sphere = Sphere { center :: Point, radius :: Double }
class Shape s where
intersect :: s -> Ray -> Maybe Point
surfaceNormal :: s -> Point -> Vector Double
我也制作了 Plane
和 Sphere
形状
。
试图将球体和飞机存储在同一个列表中,但它不起作用。我知道它不应该工作,因为 Sphere
和 Plane
是两种不同的类型,但它们都是 Shape
,所以它不应该工作?如何将形状和平面存储在列表中?
I'm trying to store spheres and planes in the same list, but it doesn't work. I understand that it shouldn't work because Sphere
and Plane
are two different types, but they are both instances of Shape
, so shouldn't it work? How would I store shapes and planes in a list?
shapes :: (Shape t) => [t]
shapes = [ Sphere { center = Point [0, 0, 0], radius = 2.0 },
Plane { point = Point [1, 2, 1], normal = 3 |> [0.5, 0.6, 0.2] }
]
推荐答案
<这个问题代表了面向对象和功能思维之间的转折点。有时候,即使是复杂的Haskellers也仍然处于这种心理转变之中,他们的设计经常会落入
这个问题的一个功能性解决方案涉及将类型类型转换为数据类型(通常一旦完成,需要类型类型消失):
A functional solution to this problem involves reifying the typeclass into a data type (usually once this is done, the need for the typeclass vanishes):
data Shape = Shape {
intersect :: Ray -> Maybe Point,
surfaceNormal :: Point -> Vector Double
}
现在您可以轻松构建 Shape
s,因为它是一个单形类型。由于Haskell不支持向下转换,因此通过消除 Plane
s和 Sphere
s之间的表示区别,不会丢失任何信息。具体的数据类型变成构造 Shape
s的函数:
Now you can easily construct a list of Shape
s, because it is a monomorphic type. Because Haskell does not support downcasting, no information is lost by removing the representational distinction between Plane
s and Sphere
s. The specific data types become functions that construct Shape
s:
plane :: Point -> Vector Double -> Shape
sphere :: Point -> Double -> Shape
如果您无法捕获所有关于中的形状的知识,按照托马斯的说法,你可以用代数数据类型枚举这些情况。但如果可能的话,我会建议不要这样做;相反,尝试找到您需要的形状的基本特征,而不是仅列举示例。
If you cannot capture everything you need to know about a shape in the Shape
data type, you can enumerate the cases with an algebraic data type, as Thomas suggested. But I would recommend against that if possible; instead, try to find the essential characteristics of a shape that you need rather than just listing off examples.
这篇关于不同类型的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!