在Traversable和MonoTraversable之间是否存在某些东西?

Jos*_*ica 3 haskell types traversal typeclass parametric-polymorphism

我有一个数据类型和伴随函数,看起来非常像某种遍历。这是一个简化的示例:

data Foo x = MkFoo (Bar x) (Bar x)

almostTraverse :: Applicative f => (Bar a -> f (Bar b)) -> Foo a -> f (Foo b)
almostTraverse f (MkFoo x y) = MkFoo <$> f x <*> f y
Run Code Online (Sandbox Code Playgroud)

假定这Bar是某种不透明类型,并且不一定是函子。是否有某种类型化的泛化almostTraverse?它不是otraversefrom的MonoTraversable,因为应用程序内部的结果类型不必与输入类型完全相同,也不traverseTraversable二者之一,因为传入的函数Bar尽管不在type参数中,但也需要知道。

Dan*_*ner 6

镜头包装将其称为Traversal

almostTraverse :: Traversal (Foo a) (Foo b) (Bar a) (Bar b)
Run Code Online (Sandbox Code Playgroud)

您可以考虑创建Each类型类的实例,例如

instance Each (Foo a) (Foo b) (Bar a) (Bar b) where
    each f (MkFoo x y) = liftA2 MkFoo (f x) (f y)
Run Code Online (Sandbox Code Playgroud)