简体   繁体   English

如何使用Data.Data?

[英]How to use Data.Data?

As I'm not familiar with rank-N types, the type signature of gfoldl is a troublesome for me:由于我不熟悉 rank-N 类型,因此gfoldl的类型签名对我来说很麻烦:

gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b)
-> (forall g. g -> c g)
-> a
-> c a

The only functions I can think of are \\xs y -> ($y) <$> xs and pure , respectively.我能想到的唯一函数分别是\\xs y -> ($y) <$> xspure

Other functions such as gunfold and gmapT have similar problems.其他函数如gunfoldgmapT也有类似的问题。 So what are notable examples of nontrivial uses of them?那么它们的重要用途有哪些值得注意的例子呢?

For the gmapT case the mkT function is defined for this purpose in the original paper.对于gmapT情况,原始论文中为此目的定义了mkT函数。

mkT :: (Typeable a, Typeable b ) => (b -> b) -> a -> a
mkT f = fromMaybe id (cast f)

For example to increment all int fields in the A , you can write something like例如,要增加A中的所有int字段,您可以编写类似

data A = A {f :: Int, s :: Int} deriving (Data, Typeable)

ex = gmapT (mkT inc) (A 2 3) where 
  inc :: Int -> Int
  inc = (+1)

To make it clearer the ex function can be written like this too:为了更清楚, ex函数也可以这样写:

ex2 = gmapT f (A 2 3) where 
  f :: (Data a ) =>  a -> a
  f a = case cast a of 
    Nothing -> a
    (Just (b :: Int)) -> fromJust $ cast (b + 1)

Data.Data is part of a generic metaprogramming framework called "Scrap your boilerplate". Data.Data是称为“Scrap Data.Data ”的通用元编程框架的一部分。

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

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