[英]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.