我想撰寫一個適用于所有自定義資料型別(屬于我的自定義型別類)的函式,但每種資料型別都有自己的實作。例如:
getValue :: Ent entity => entity -> Float
getValue (Player position _) = doA position
getValue (Enemy position) = doB position
然而,這給了我以下錯誤:
Couldn't match expected type ‘entity’ with actual type ‘Player’ ‘entity’ is a rigid type variable bound by ??the type signature for: ???getValue :: forall entity. Ent entity => entity -> Float
如何撰寫一個對所有型別類都有唯一實作的函式?
uj5u.com熱心網友回復:
你這樣做的型別的類,使得getValue它的方法:
class Ent a where
getValue :: a -> Float
instance Ent Player where
getValue (Player p _) = doA p
instance Ent Enemy where
getValue (Enemy e) = doB e
現在getValue :: Ent a => a -> Float這和你想要的一樣。
型別變數的名稱不算數,直到一致的重命名。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/350114.html
上一篇:遍歷一個字串并使用每個字符,但我收到此例外訊息:“(48,1)-(50,35):函式textToMorse中的非窮舉模式”
下一篇:如何為資料型別類撰寫函式
