haskell - 为什么 “failing”(来自镜头)会产生无效遍历?

标签 haskell haskell-lens

来自 the documentation :

Try the first Traversal (or Fold), falling back on the second Traversal (or Fold) if it returns no entries.

This is only a valid Traversal if the second Traversal is disjoint from the result of the first or returns exactly the same results.


是否有 failing 生成的无效遍历的简单示例?和一个证明它的测试用例?

最佳答案

对于反例,我们首先定义一个新的数据类型,我们使用 makePrisms 为其生成遍历。 :

data T = A T | C deriving Show
makePrisms ''T
_A :: Traversal T T现在是一个有效的遍历。现在,使用 failing 构造一个新的遍历。 :
t :: Traversal' T T
t = failing _A id

请注意 (C & t .~ A C) ^.. t = [C] ,看起来它不符合遍历定律(你没有“得到你放入的东西”)。事实上,第二遍历定律是:
fmap (t f) . t g ≡ getCompose . t (Compose . fmap f . g)

不满意,可以从以下 f 的选择中看出和 g :
-- getConst . t f = toListOf t
f :: T -> Const [T] T
f = Const . (:[])

-- runIdentity . t g = t .~ A C
g :: T -> Identity T
g = pure . const (A C)

然后:
> getConst . runIdentity . fmap (t f) . t g $ C
[C]

尽管:
> getConst . runIdentity . getCompose . t (Compose . fmap f . g) $ C
[A C]

所以确实有failing的情况具有有效遍历不会产生有效遍历。

关于haskell - 为什么 “failing”(来自镜头)会产生无效遍历?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27138856/

相关文章:

arrays - Haskell 中的固定大小数组

haskell - 在没有 Monoid 实例的情况下,如何处理 Control.Lens.Indexed 中 at 的 Maybe 结果

haskell - 为遍历和折叠实现多态 'deep' 函数

haskell - Stack中简单整数的条件选择

haskell - 如何使用 Haskell 和海龟库从文件流式传输时删除行

haskell - 在 Haskell 记录初始化中强制关键字参数

haskell - 镜头变焦模糊变量

haskell - 如何解决无法使用存在类型的镜头?

haskell - 如何为 sum 类型编写镜头

windows - 为什么 nmap 显示我的 TCP 服务器没有监听它应该监听的端口?