haskell - 根据 Data 类型类定义 fmap

标签 haskell metaprogramming

可以定义fmapData方面来自 Data.Data 的类型类?

似乎使用 gfoldl一个不能修改类型..还有其他组合器可以做到这一点吗?

我猜这在一般情况下无法完成,因为人们无法仅影响“Righta位于 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/

相关文章:

c++ - 如何反省可变参数模板模板参数的多样性?

c# - 我可以使用 Roslyn 进行编译时代码重写吗?

performance - 实现 (^)

c++ - Boost Hana 编译时列表转换

haskell - 为什么我可以在 Haskell 中将值绑定(bind)到值?

haskell - 在类型类函数上显式 forall

Ruby 元编程和传递参数

c++ - 除了模板之外,还有其他 C++ 元编程替代方案吗?

haskell - Haskell 内部的 IO 实现

haskell - 类型类与代数数据类型?