我有一个数据类型(以 GADT 形式显示在下面):
data Test a where
C1 :: Int -> a -> Test a
C2 :: Test a -> Test a -> a -> Test a
C3 :: Test a -> a -> Test a
...
我想做的是能够将一些函数 Monoid m => Test a -> m
一般应用于 Test a
中的任何给定实例构造函数,然后映射
全部。
例如,给定 f:
f :: Test a -> [Int]
f (C1 n _) = [n]
f _ = []
我想要一些函数 g 可以将其映射到每个构造函数参数,如下所示:
g :: Monoid m => (Test a -> m) -> Test a -> m
g f v@(C1 Int _) = f v
g f (C2 x y _) = f x `mappend` f y
g f (C3 x _) = f x
...
除了我不想写 g
,我想写一个 g
的通用版本,它可以对任何支持的数据类型执行此操作(我'我认为 GHC.Generics 可能很适合这个,但一直无法获得正确的类型)。
也就是说,我想将遍历数据结构的实际机制(使用基于 mappend
的折叠重复应用 f
)与有趣的 位(上面 g
中 C1
的终止情况)
有什么想法吗?
最佳答案
实际上,我会更深入地研究 GHC.Generics,并且肯定会阅读 the SYB paper如果你还没有。
我将在这里概述另一种方法,即使用定点类型,这非常适合解决这个问题。
newtype Mu f = Roll { unroll :: f (Mu f) }
-- Replace all recursive constructors with r.
-- If any of them are nonregular (e.g. C3 :: Test Int -> Test a)
-- then this approach gets quite a bit more complicated, so I hope not.
data TestF a r where
C1 :: Int -> a -> TestF a r
C2 :: r -> r -> a -> TestF a r
...
-- This will take care of finding the recursive constructors
deriving instance Foldable (TestF a)
-- This is your actual type (might want to wrap it in a newtype)
type Test a = Mu (TestF a)
foldMapRec :: (Foldable f, Monoid m) => (Mu f -> m) -> Mu f -> m
foldMapRec f (Roll a) = foldMap f a
在实践中,我实际上并没有充分利用固定点类型,它们似乎总是比它们的值(value)更麻烦。但现在实现了 PatternSynonyms
,我认为它更好一些。无论如何,只是想向您展示这一点供您考虑。
关于haskell - 如何映射 ADT 构造函数的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41235424/