RandomB
RandomB

Reputation: 3749

Sequence-like on tuples

Consider a code using a tuple:

import Data.Tuple.All  -- tuple library
import Control.Lens

..............

f2 :: (SequenceT a1 b, Each s a1 a2 b2) => s -> (a2 -> b2) -> b
f2 tpl f = sequenceT $ tpl & each %~ f

Example of the usage:

> f x = print x >> pure x
> f2 (1,2,3,4) f
1
2
3
4
(1, 2, 3, 4)

which means that as I have a map and sequence on lists, now I have f2 on tuples. But f2 depends on the tuple.

How can I write the same f2 using just lens? Without sequenceT. Is it possible?

PS. Maybe you know another similarly simple solutions?

Upvotes: 1

Views: 125

Answers (1)

Li-yao Xia
Li-yao Xia

Reputation: 33464

You indeed don't need the package tuple, only lens, since f2 is actually just flip each.

import Control.Lens

f2 :: (Each s t a b, Applicative f) => s -> (a -> f b) -> f t
f2 = flip each

main = do
  xs <- f2 (1,2,3) (\x -> print x >> pure (x :: Int))
  print xs

{- Output:
1
2
3
(1,2,3)
-}

Upvotes: 3

Related Questions