Monadic改变元组 [英] Monadic alteration to tuple
问题描述
Monad m => (a,b)→> (b→m c)→> m(a,c)
在我看来,这是一些bind(>
)和镜头操作。
我知道我可以在绑定后用模式匹配解决这个问题,但我的直觉告诉我,有一种简单的方式来利用镜头来写这个。
有没有这样的操作?
这绝对是透镜。 monad实际上只是一个分心,因为你需要的只是一个仿函数:
$ p $ changesecond(a,b)f = fmap(a,)(fb)
我很确定 _2
镜头可以用一个基本的镜头来完成你的拍卖,比如可能超过
,但我对这个库还不太熟悉。
编辑
确实不需要combinator。你可以写成:
changesecond pair f = _2 f pair
您应该能够从 Lens
类型的一般定义中解决这个问题。
编辑2
这个简单的例子演示了Van Laarhoven镜头结构的主题:
fmap
来恢复结果的上下文。 Ed Kmett's lens
图书馆以各种方式阐述了这个主题。有时它会加强仿函数约束。有时它将函数推广到一个整体。在 Equality
的情况下,它将删除函子约束。事实证明,相同的基本类型形状可以表达许多不同的想法。
I am looking for a function with type similar to:
Monad m => (a, b) -> (b -> m c) -> m (a, c)
It appears to me as some combination of bind (>>=
) and a lens operation.
I am aware that I can solve this with a pattern match after a bind, but my gut tells me there is a "simpler" way to write this by leveraging lenses.
Is there any such operation?
This is definitely lensy. The monad is actually just a bit of a distraction because all you need is a functor:
changesecond (a, b) f = fmap (a,) (f b)
I'm pretty sure the _2
lens can be made to do your bidding with a basic lens thing like maybe over
but I'm not too familiar with the library yet.
Edit
No combinator is really needed. You can write
changesecond pair f = _2 f pair
You should be able to work this out from the general definition of the Lens
type.
Edit 2
This simple example demonstrates the main theme of Van Laarhoven lens construction:
- Extract the focus from the context.
- Apply the given function to produce a functorful of results.
- Use
fmap
to restore the contexts to the results.
Ed Kmett's lens
library elaborates on this theme in various ways. Sometimes it strengthens the functor constraint. Sometimes it generalizes the function to a profunctor. In the case of Equality
, it removes the functor constraint. It just turns out that the same basic type shape can express a lot of different ideas.
这篇关于Monadic改变元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!