Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monadic alteration to tuple

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?

like image 349
Luke Cycon Avatar asked Aug 13 '15 02:08

Luke Cycon


1 Answers

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:

  1. Extract the focus from the context.
  2. Apply the given function to produce a functorful of results.
  3. 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.

like image 153
dfeuer Avatar answered Sep 27 '22 21:09

dfeuer