同时导出Generic和ToJSON?

时间:2017-08-08 15:30:42

标签: haskell aeson ghc-generics

我有一个模块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

但它没有编译。如果我在定义网站的Foo.hs中派生Generic,我稍后可以在另一个模块中派生ToJSON

我可以在ToJSON Blather中导出Bar.hs而无需修改原始Foo.hs吗?

或者有一种简单的方法可以手写instance ToJSON Blather吗?

1 个答案:

答案 0 :(得分: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
相关问题