मेरे पास दो रिकॉर्ड हैं जिनके पास एक फ़ील्ड है जिसे मैं डिस्प्ले के लिए निकालना चाहता हूं। मैं चीजों की व्यवस्था कैसे करूं ताकि उन्हें एक ही कार्य के साथ छेड़छाड़ की जा सके? चूंकि उनके पास अलग-अलग फ़ील्ड हैं (इस मामले में firstName
और buildingName
) जो उनके नाम फ़ील्ड हैं, उन्हें प्रत्येक को firstName
से name
पर मैप करने के लिए कुछ "एडाप्टर" कोड चाहिए।एक कक्षा को परिभाषित करने के लिए जो हास्केल में विभिन्न अभिलेखों तक समान पहुंच की अनुमति देता है?
class Nameable a where
name :: a -> String
data Human = Human {
firstName :: String
}
data Building = Building {
buildingName :: String
}
instance Nameable Human where
name x = firstName x
instance Nameable Building where
-- I think the x is redundant here, i.e the following should work:
-- name = buildingName
name x = buildingName x
main :: IO()
main = do
putStr $ show (map name items)
where
items :: (Nameable a) => [a]
items = [ Human{firstName = "Don"}
-- Ideally I want the next line in the array too, but that gives an
-- obvious type error at the moment.
--, Building{buildingName = "Empire State"}
]
यह संकलन नहीं करता है::
TypeTest.hs:23:14:
Couldn't match expected type `a' against inferred type `Human'
`a' is a rigid type variable bound by
the type signature for `items' at TypeTest.hs:22:23
In the expression: Human {firstName = "Don"}
In the expression: [Human {firstName = "Don"}]
In the definition of `items': items = [Human {firstName = "Don"}]
मैं अपेक्षा की होगी instance Nameable Human
अनुभाग इस काम होगा यहाँ मैं अब तक है। क्या कोई यह समझा सकता है कि मैं क्या गलत कर रहा हूं, और बोनस के लिए क्या मैं "अवधारणा" काम करने की कोशिश कर रहा हूं, क्योंकि मुझे यह जानने में परेशानी हो रही है कि क्या खोजना है।
This question समान लगता है, लेकिन मैं अपनी समस्या के साथ कनेक्शन को समझ नहीं पाया।
items :: (Nameable a) => [a]
यह कह रहा है कि किसी भी प्रकार के लिए Nameable
, items
मुझे उस प्रकार की एक सूची दे देंगे:
यदि आप 'आइटम्स' के लिए टाइप-एनोटेशन हटाते हैं तो यह काम करता है ... हालांकि, आइटमों में '[मानव]' टाइप है (जो शायद आप नहीं चाहते हैं?) – phynfo