简体   繁体   English

GHC.Generics还是Data.Data?

[英]GHC.Generics or Data.Data?

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 package. 目前使用GHC, Data.Data / Data.TypeableGHC.Generics进行泛型编程的选项有2个(如果你计算的是3个), 那么这两个选项都可以从基础包中获得。 So, what are the advantages and disadvantages of each? 那么,每个的优点和缺点是什么? Is GHC.Generics the "modern" way and Data.Data obsolete and just kept for backwards compatibility? GHC.Generics是“现代”方式而Data.Data是过时的,只是为了向后兼容而保留?

GHC.Generics is the modern way and it is much faster than SYB. GHC.Generics是现代方式,它比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. 然而,它向最终用户公开了一种不同的泛型编程方法,所以我认为它不应该被认为是SYB的直接替代,尽管它确实解决了同样的问题。

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: aeson库的记录序列化到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. 并使用toJSONToJSON类型类之后。

Using GHC.Generics 使用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. 然后使用与ToJSON类型类相同的toJSON

Using SYB 使用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: 并使用Data.Aeson.Generic具有以下签名的特定toJSON

toJSON :: Data a => a -> Value

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

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