可以定义fmap
在Data
方面来自 Data.Data
的类型类?
似乎使用 gfoldl
一个不能修改类型..还有其他组合器可以做到这一点吗?
我猜这在一般情况下无法完成,因为人们无法仅影响“Right
” a
位于 Either a a
,但也许它可以在某些情况下完成,例如 Maybe
?
(我知道 fmap
很容易推导出来,但我仍然对使用 Data
是否可以实现这一点感兴趣)
最佳答案
这是使用 syb
的示例来自 here
{-# LANGUAGE DeriveDataTypeable, ScopedTypeVariables, FlexibleContexts #-}
import Data.Generics
import Unsafe.Coerce
{- | C tags the type that is actually parameterized, so to avoid touching the
Int when a ~ Int:
> data T a = T Int a
by changing the type (not representation) to:
> x :: T Int (C Int)
-}
newtype C a = C a deriving (Data,Typeable)
fmapData :: forall t a b. (Typeable a, Data (t (C a)), Data (t a)) =>
(a -> b) -> t a -> t b
fmapData f input = uc . everywhere (mkT $ \(x::C a) -> uc (f (uc x)))
$ (uc input :: t (C a))
where uc = unsafeCoerce
关于haskell - 根据 Data 类型类定义 fmap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13839833/