सीधी-सपाट अनुवाद।
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
हालांकि आप आमतौर पर ऐसा नहीं करेंगे; यह दोहरावदार और बहुलक सूची में भाषा एक्सटेंशन की आवश्यकता है।
इसके बजाय, उन्हें एक ही बंद डेटाप्रकार में चिपके हुए शायद पहली समाधान आप के लिए जाना चाहिए।
type Vector3D = (Double, Double, Double)
data Shape
= Sphere { name :: String, position :: Vector3D, radius :: Double }
| Prism { name :: String, position :: Vector3D, dimensions :: Vector3D }
आप निश्चित रूप से अधिक typeclasses बनाने के द्वारा विरासत के कई स्तरों अनुकरण कर सकते हैं:
class (Shape shape) => Prism shape where
dimensions :: Vector3D
data RectangularPrism = ...
data TriangularPrism = ...
instance Prism RectangularPrism where ...
instance Prism TriangularPrism where ...
तुम भी डेटाटाइप्स एम्बेड करके यह अनुकरण कर सकते हैं।
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"
लेकिन हास्केल में OO अनुकरण के पास कहीं भी नहीं है वास्तव में एक Haskellish तरह से सोच के रूप में के रूप में संतोषजनक। तुम क्या करने की कोशिश कर रहे हो?
(भी ध्यान रखें कि इन समाधानों में से सब केवल upcasts की अनुमति, downcasting असुरक्षित और उसे अस्वीकृत है।)
आप एक विरासत श्रृंखला का प्रतिनिधित्व कैसे करेंगे जो एक से अधिक स्तर गहरे हैं? जैसे 'आकार' -> 'प्रिज्म' -> 'आयताकारप्रिज्म' – barkmadley