GHC.Generics or Data.Data?

后端 未结 1 872
情歌与酒
情歌与酒 2021-02-03 20:06

There are currently 2 (3 if you count TemplateHaskell) options for generic programming using GHC, Data.Data / Data.Typeable and GHC.Generics, both available from the base packag

1条回答
  •  有刺的猬
    2021-02-03 20:57

    GHC.Generics is the modern way and it is much faster than SYB. It however exposes a different approach to generic programming to the end user, so I don't think that it should be thought of as a direct replacement of SYB, though it does solve the same problems.

    A good example of how those approaches differ from user's perspective can be extracted from the aeson library's functionality of serialization of a record to JSON:

    Without generics

    {-# LANGUAGE OverloadedStrings #-}
    import Data.Aeson
    
    data Coord = Coord { x :: Double, y :: Double }
    
    instance ToJSON Coord where
       toJSON (Coord x y) = object ["x" .= x, "y" .= y]
    

    And use toJSON of ToJSON typeclass afterwards.

    Using GHC.Generics

    {-# LANGUAGE DeriveGeneric #-}
    import Data.Aeson    
    import GHC.Generics
    
    data Coord = Coord { x :: Double, y :: Double } deriving Generic
    
    instance ToJSON Coord
    

    And use the same toJSON of ToJSON typeclass afterwards.

    Using SYB

    {-# LANGUAGE DeriveDataTypeable #-}
    import Data.Data
    import Data.Aeson.Generic
    
    data Coord = Coord { x :: Double, y :: Double } deriving (Data, Typeable)
    

    And use a specific toJSON from Data.Aeson.Generic with the following signature:

    toJSON :: Data a => a -> Value
    

    0 讨论(0)
提交回复
热议问题