组合两个遍历,对中间层具有只读访问权限

Compose two Traversals, with read-only access to the middle layer

我想合成两个遍历,然后用同样依赖于 "middle" 层的东西遍历合成。

我认为这意味着从两个 Traversal 中制作一个 IndexedTraversal

rememberMidpoint :: Traversal' s a -> Traversal' a b -> IndexedTraversal' a s b

也许问题可以进一步简化为

remember :: Traversal' s a -> IndexedTraversal' s a a

remember :: Traversal' s a -> IndexedTraversal' a s a

?

所以我的问题是:

@phadej helped me out over on #haskell-lens, pointing me towards selfIndex:

Use a value itself as its own index. This is essentially an indexed version of id.

与组合器 <. 一起组成索引遍历和非索引遍历,我们得到:

rememberMidpoint :: Traversal' s a -> Traversal' a b -> IndexedTraversal' a s b
rememberMidpoint outer inner = outer . selfIndex <. inner

并在评论中解决 @András Kovács 的观点:

According to docs, your intended IndexedTraversal is not legal, as the a index changes if you modify an innermost b.

我不相信这是真的:如果我理解 selfIndex 正确,索引中的 a 将保留 "original" a,而不是变成里面修改了b的那个。