ErikR
ErikR

Reputation: 52039

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
data Blather = Blather ...  -- Generic not derived here

And in another module I want to derive 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.

Can I derive ToJSON Blather in Bar.hs without modifying the original Foo.hs?

Or is there a simple way to write instance ToJSON Blather by hand?

Upvotes: 2

Views: 431

Answers (1)

Shaun the Sheep
Shaun the Sheep

Reputation: 22742

Enable StandaloneDeriving and use deriving instance ... since this doesn't require that the derivation is in the same module as the data type.

Example:

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

import GHC.Generics
import Data.Aeson
import Foo

deriving instance Generic Blather
deriving instance ToJSON Blather

main = undefined

Upvotes: 4

Related Questions