gpt4 book ai didi

haskell - 在镜头库中使用Traversable []和Applicative Maybe的效果

转载 作者:行者123 更新时间:2023-12-02 02:44:04 24 4
gpt4 key购买 nike

我有以下结构:

y = [
fromList([("c", 1 ::Int)]),
fromList([("c", 5)]),
fromList([("d", 20)])
]

我可以用它来更新每个“c”:

y & mapped . at "c" . mapped  %~ (+ 1)
-- [fromList [("c",2)], fromList [("c",6)], fromList [("d",20)]]

所以第三个条目基本上被忽略了。但我想要的是操作失败。

Only update, iff all the maps contain the key "c".



所以我想要:

y & mysteryOp
-- [fromList [("c",1)], fromList [("c",5)], fromList [("d",20)]]
-- fail because third entry does not contain "c" as key

我想我知道在这里使用哪些功能:

over
-- I want to map the content of the list

mapped
-- map over the structure and transform to [(Maybe Int)]

traverse
-- I need to apply the operation, which will avoid

at "c"
-- I need to index into the key "c"

我只是不知道如何组合它们

最佳答案

这里有几种替代方法,可以根据您的喜好进行观察;

使用懒惰来延迟决定是否进行更改,

f y = res
where (All c, res) = y
& each %%~ (at "c" %%~ (Wrapped . is _Just &&& fmap (applyWhen c succ)))

或者预先决定是否进行更改,
f' y = under (anon y $ anyOf each (nullOf $ ix "c")) (mapped . mapped . ix "c" +~ 1) y

关于haskell - 在镜头库中使用Traversable []和Applicative Maybe的效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60673964/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com