Automatic instance deriving after declaration
In Haskell, when defining a data type you can choose to automatically derive some instances, but can I defer the automatic deriving, perhaps even put it in another library?
Here is an example:
Automatic deriving in Haskell is a real time saver!
module MoneyModule where
data Money = Money Int
deriving Show
Now I wish to use the MoneyModule
, but I also want a Read
instance for Money
:
module ExternalModule where
instance Read Money where
read = error "Can't this be done automatically instead?"
But I would really have preferred for it to be derived automatically, which I know ghc could have done if only the MoneyModule author had auto-derived the Read
instance.
I know that:
MoneyModule
by patching it with the missing instance. In my case I can't follow best practices since the type class is unrelated to the data type. I doubt that the type class module nor the data type module wants to hold the instance, so therefore I'm creating a third library because in some applications you need the instance declaration.
GHC has the StandaloneDeriving
extension, with that, you can
{-# LANGUAGE StandaloneDeriving #-}
import MoneyModule
deriving instance Read Money
derive instances for many classes.
To solve the problem about stand alone deriving, see daniels solution. But as you mentioned in your question, orphan instances is not best practice and ghc will generate warnings. To surpress the ghc orphan warnings, you can use the flag -fno-warn-orphans
. You can also add it to your cabal file:
...
library
exposed-modules: ...
...
ghc-options: -fno-warn-orphans
...
链接地址: http://www.djcxy.com/p/33166.html
上一篇: 需要灵活的实例?
下一篇: 声明后自动导出实例