14

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:

  • It's better to fix the problem in the actual MoneyModule by patching it with the missing instance.
  • That it's considered bad to have orphan instances. Instance declarations are preferably put in the module where either the type class or the data type was defined.

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.

4

2 に答える 2

21

GHCにはStandaloneDeriving拡張機能があり、それにより、次のことができます。

{-# LANGUAGE StandaloneDeriving #-}
import MoneyModule

deriving instance Read Money

多くのクラスのインスタンスを派生させます。

于 2012-10-12T04:40:16.630 に答える
4

スタンドアローンの派生に関する問題を解決するには、daniels solution を参照してください。しかし、質問で述べたように、孤立したインスタンスはベスト プラクティスではなく、ghc は警告を生成します。ghc 孤立警告を抑制するには、フラグを使用できます-fno-warn-orphans。また、cabal ファイルに追加することもできます。

...
library
  exposed-modules: ...
  ...
  ghc-options: -fno-warn-orphans
...
于 2012-10-12T16:18:36.827 に答える