Bản dịch thẳng tiến.
type Vector3D = (Double, Double, Double)
class Shape shape where
name :: shape -> String
position :: shape -> Vector3D
data Sphere = Sphere {
sphereName :: String,
spherePosition :: Vector3D,
sphereRadius :: Double
}
data Prism = Prism {
prismName :: String,
prismPosition :: Vector3D,
prismDimensions :: Vector3D
}
instance Shape Sphere where
name = sphereName
position = spherePosition
instance Shape Prism where
name = prismName
position = prismPosition
Bạn thường không làm điều này; các danh sách lặp lại và đa hình yêu cầu các phần mở rộng ngôn ngữ.
Thay vào đó, dán chúng vào một kiểu dữ liệu đóng duy nhất có lẽ là giải pháp đầu tiên bạn nên sử dụng.
type Vector3D = (Double, Double, Double)
data Shape
= Sphere { name :: String, position :: Vector3D, radius :: Double }
| Prism { name :: String, position :: Vector3D, dimensions :: Vector3D }
Bạn chắc chắn có thể mô phỏng nhiều cấp độ thừa kế bằng cách tạo ra nhiều typeclasses:
class (Shape shape) => Prism shape where
dimensions :: Vector3D
data RectangularPrism = ...
data TriangularPrism = ...
instance Prism RectangularPrism where ...
instance Prism TriangularPrism where ...
Bạn cũng có thể mô phỏng nó bằng cách nhúng kiểu dữ liệu.
type Vector3D = (Double, Double, Double)
data Shape = Shape { name :: String, position :: Vector3D }
data Sphere = Sphere { sphereToShape :: Shape, radius :: Double }
newSphere :: Vector3D -> Double -> Shape
newSphere = Sphere . Shape "Sphere"
data Prism = Prism { prismToShape :: Shape, dimensions :: Vector3D }
data RectangularPrism = RectangularPrism { rectangularPrismToPrism :: Prism }
newRectangularPrism :: Vector3D -> Vector3D -> RectangularPrism
newRectangularPrism = (.) RectangularPrism . Prism . Shape "RectangularPrism"
data TriangularPrism = TriangularPrism { triangularPrismToPrism :: Prism }
newTriangularPrism :: Vector3D -> Vector3D -> TriangularPrism
newTriangularPrism = (.) TriangularPrism . Prism . Shape "TriangularPrism"
Nhưng mô phỏng OO trong Haskell không ở bất kỳ đâu gần như thỏa mãn như thực tế suy nghĩ theo cách Haskellish. Bạn đang cố làm gì vậy?
(Cũng lưu ý rằng tất cả các giải pháp này chỉ cho phép upcasts, downcasting là không an toàn và không được phép.)
làm cách nào bạn thể hiện chuỗi thừa kế có nhiều cấp độ sâu? ví dụ. 'shape' ->' Prism' -> 'RectangularPrism' – barkmadley