Question

Having received a value of type Key a, I can easily define and use this function:

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

However, I can't use the same function from within an instance for Key a!

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

I get this error:

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

How do I define this instance? Why doesn't my approach work?

Was it helpful?

Solution

Key entityis a synonym for KeyBackend backend entity, so you need to define the instance on the concrete type.

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"
  ...

Though using error so gratuitously is likely to cause a lot of pain later.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top