简体   繁体   English

同时派生Generic和ToJSON?

[英]deriving Generic and ToJSON at the same time?

I have a module Foo.hs which contains a definition which does not derive Generic : 我有一个模块Foo.hs ,其中包含一个不继承Generic的定义:

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

And in another module I want to derive ToJSON : 在另一个模块中,我想派生ToJSON

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

import GHC.Generics
import Data.Aeson

instance Generic Blather
instance ToJSON Blather

but it doesn't compile. 但不会编译。 If I derive Generic in Foo.hs at the definition site I can later derive ToJSON in another module. 如果我在定义站点的Foo.hs中派生Generic, Foo.hs可以稍后在另一个模块中派生ToJSON

Can I derive ToJSON Blather in Bar.hs without modifying the original Foo.hs ? 我可以在Bar.hs派生ToJSON Blather Bar.hs而无需修改原始Foo.hs吗?

Or is there a simple way to write instance ToJSON Blather by hand? 还是有一种简单的方法手动编写instance ToJSON Blather

Enable StandaloneDeriving and use deriving instance ... since this doesn't require that the derivation is in the same module as the data type. 启用StandaloneDeriving并使用deriving instance ...因为这不需要派生与数据类型在同一模块中。

Example: 例:

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

import GHC.Generics
import Data.Aeson
import Foo

deriving instance Generic Blather
deriving instance ToJSON Blather

main = undefined

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM