GHC.Generics或Data.Data? [英] GHC.Generics or Data.Data?

查看:86
本文介绍了GHC.Generics或Data.Data?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前使用GHC进行泛型编程的选项有2(如果您计算TemplateHaskell)选项, Data.Data / Data.Typeable GHC.Generics ,都可从基础包中获得。那么,每个人的优点和缺点是什么?是GHC.Generics的现代方式和Data.Data过时,只是为了向后兼容? 解决方案

GHC.Generics是现代化的方式,它比SYB快得多。然而,它向最终用户展示了一种不同的泛型编程方法,所以我认为它不应该被认为是SYB的直接替代品,尽管它确实解决了相同的问题。



可以从 aeson库中提取这些方法与用户角度不同的一个很好的示例这是一个将记录序列化为JSON的功能:



没有泛型



  { - #LANGUAGE OverloadedStrings# - } 
import Data.Aeson

data Coord = Coord {x :: Double,y :: Double}

实例ToJSON Coord where
toJSON(Coord xy)= object [x。= x,y。= y]

然后使用 toJSON 之后的 ToJSON 类型类别。



使用GHC.Generics



  { - #LANGUAGE DeriveGeneric# - } 
import Data.Aeson
import GHC.Generics

data Coord = Coord {x :: Double,y :: Double}派生类Generic

实例ToJSON Coord

并使用相同的 toJSON ToJSON 之后的类型类别。



使用SYB



<$ p $
import Data.Aeson.Generic

data Coord = Coord {x :: Double,y :: Double}派生(Data,Typeable)

并且使用特定的toJSON Data.Aeson.Generic 的签名:

  toJSON :: Data a => a  - >价值


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. 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 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

这篇关于GHC.Generics或Data.Data?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆