2013-10-22 35 views
1

已經收到Key a類型的值,我可以很容易地定義和使用此功能:通過Yesod's Key定義新實例a?

keyToInt64 :: Key a -> Int64 
keyToInt64 (Key (PersistInt64 n)) = n 
keyToInt64 _ = error "wrong database type" 

但是,我不能使用相同的功能,從實例中的Key a

instance Num (Key a) where 
    fromInteger = fromIntegral . keyToInt64 

我得到這個錯誤:

Illegal type synonym family application in instance: Key a 
In the instance declaration for `Num (Key a)' 

如何定義這種情況?爲什麼我的方法不工作?

回答

1

Key entityKeyBackend backend entity的同義詞,因此您需要在具體類型上定義實例。

instance Num (KeyBackend backend entity) where 
    Key (PersistInt64 a) + Key (PersistInt64 b) = Key . PersistInt64 $ a + b 
    Key _    + _     = error "wrong database type" 
    _     + Key _    = error "wrong database type" 
    ... 

儘管如此無償地使用error以後可能會導致很多痛苦。