Dan*_*Dos 4 haskell scrap-your-boilerplate rank-n-types
由于我对 N 级类型不熟悉,所以 的类型签名gfoldl对我来说很麻烦:
gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b)
-> (forall g. g -> c g)
-> a
-> c a
Run Code Online (Sandbox Code Playgroud)
我能想到的唯一函数分别是\xs y -> ($y) <$> xs和pure。
其他函数如gunfold和 也gmapT有类似的问题。那么它们的重要用途有哪些值得注意的例子呢?
对于这种gmapT情况,mkT原始论文中为此目的定义了函数。
mkT :: (Typeable a, Typeable b ) => (b -> b) -> a -> a
mkT f = fromMaybe id (cast f)
Run Code Online (Sandbox Code Playgroud)
例如,要增加int中的所有字段A,您可以编写类似的内容
data A = A {f :: Int, s :: Int} deriving (Data, Typeable)
ex = gmapT (mkT inc) (A 2 3) where
inc :: Int -> Int
inc = (+1)
Run Code Online (Sandbox Code Playgroud)
为了更清楚,该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)
Run Code Online (Sandbox Code Playgroud)