Is there a zipWith analogue for tuples?

  • A+

Preliminary note: this is a respin of a deleted question by SeanD.

Just like there is zipWith for lists...

GHCi> zipWith (+) [1,2] [3,4] [4,6] 

... it feels like there should be something analogous for tuples, in the spirit of...

tupleZipWith (+) (1,2) (3,4) 

... but there doesn't seem to be anything obviously like that in base. Which options do I have?

One option is using the tuples-homogenous-h98 package, which provides newtype wrappers for homogeneous tuples that have appropriate Applicative instances:

GHCi> import Data.Tuple.Homogenous GHCi> import Control.Applicative GHCi> liftA2 (+) (Tuple2 (1,2)) (Tuple2 (3,4)) Tuple2 {untuple2 = (4,6)} GHCi> (>) <$> Tuple3 (7,4,7) <*> Tuple3 (6,6,6) Tuple3 {untuple3 = (True,False,True)} 

If you have a favourite homogenous tuple/fixed-size vector/fixed-size list library other than tuples-homogenous-h98, odds are that it will also have suitable ZipList-like Applicative instances.

For a slightly different take on the matter when it comes to pairs, you might want to consider Data.Biapplicative from bifunctors:

GHCi> import Data.Biapplicative GHCi> bimap (+) (+) (1,2) <<*>> (3,4) (4,6) 

One nice thing about this approach is that it can handle heterogeneous pairs:

GHCi> bimap (+) (+) (1,2.5) <<*>> (3,4) (4,6.5) GHCi> bimap (+) (++) (1,"foo") <<*>> (3,"bar") (4,"foobar") 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: