Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use two mappings to traverse a 2-tuple in Haskell?

I have a monad m that supports the following operation:

someName :: (t1 -> m u1) -> (t2 -> m u2) -> ((t1, t2) -> m (u1, u2))

In something more like English: given a mapping that could be used with bind to turn an m t1 into m u1 and another mapping for another pair of types, return such a mapping for pairs of the two types.

Does this concept have a name? Is it well-defined for all monads? Only some? None, and I have my facts wrong for the one I'm working on?


This is reminiscent of the traverse operation on Traversables, except there are two mappings involved. Plus, traverse for 2-tuples only seems to apply the mapping to the second element:

ghci> f a = Just (a + 1)
ghci> traverse f (0, 1)
Just (0,2)
ghci> traverse f ("Hello", 1)
Just ("Hello",2)
like image 971
jacobsa Avatar asked Nov 23 '25 17:11

jacobsa


2 Answers

It's called bitraverse and comes standard with your favorite compiler.

like image 151
Daniel Wagner Avatar answered Nov 26 '25 07:11

Daniel Wagner


All monads have this operation. In fact, all applicative functors have this operation:

someName :: Applicative m => (t1 -> m u1) -> (t2 -> m u2) -> ((t1, t2) -> m (u1, u2))
someName f1 f2 = \(t1, t2) -> (,) <$> f1 t1 <*> f2 t2

For this reason, I doubt it has any special name, or any interesting properties beyond those of Applicative more generally.

like image 29
bradrn Avatar answered Nov 26 '25 07:11

bradrn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!