gpt4 book ai didi

haskell - 是否有标准组合器将镜头的结果包装在仿函数中?

转载 作者:行者123 更新时间:2023-12-04 18:11:19 26 4
gpt4 key购买 nike

在尝试将具有多层仿函数的函数应用于主机数据结构的成员时,如下例所示:

update ::
(SomeProductField -> Maybe (Int, SomeProductField)) ->
(SomeProduct -> Maybe (Int, SomeProduct))
我想出了以下实用程序:
inFunctor :: Functor f => Lens s t a b -> Lens s (f t) a (f b)
inFunctor lens f = getCompose . lens (Compose . f)
允许我实现 update像这样的功能:
someProductFieldLens :: Lens' SomeProduct SomeProductField

update = inFunctor someProductFieldLens
我想知道“镜头”中是否已经存在类似的东西,以及使用现有方法是否可以通过其他方式实现。

最佳答案

也许不是标准方法,但无论如何: alaf 可以处理Compose包装。例如:

data SomeProduct = SomeProduct
{ _someProductField :: Bool
, _anotherProductField :: String
}
deriving Show
makeLenses ''SomeProduct
ghci> alaf Compose someProductField (\b -> Just (fromEnum b, not b)) (SomeProduct False "foo")
Just (0,SomeProduct {_someProductField = True, _anotherProductField = "foo"})
如果您仍想定义通用组合器:
inFunctor :: Functor f => Lens s t a b -> Lens s (f t) a (f b)
inFunctor l = alaf Compose l

关于haskell - 是否有标准组合器将镜头的结果包装在仿函数中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70492973/

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