2

我有一个模块Foo.hs,其中包含一个不派生的定义Generic

-- Foo.hs
data Blather = Blather ...  -- Generic not derived here

在另一个模块中我想派生ToJSON

-- Bar.hs
{-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}

import GHC.Generics
import Data.Aeson

instance Generic Blather
instance ToJSON Blather

但它不编译。如果我在定义站点导出 Generic,Foo.hs我稍后可以ToJSON在另一个模块中导出。

我可以ToJSON BlatherBar.hs不修改原件的情况下推导出来Foo.hs吗?

或者有没有简单instance ToJSON Blather的手写方式?

4

1 回答 1

4

启用StandaloneDeriving和使用deriving instance ...,因为这不需要派生与数据类型位于同一模块中。

例子:

{-# LANGUAGE DeriveGeneric, StandaloneDeriving, DeriveAnyClass #-}

import GHC.Generics
import Data.Aeson
import Foo

deriving instance Generic Blather
deriving instance ToJSON Blather

main = undefined
于 2017-08-08T15:51:33.837 回答