Search code examples
haskellfunctorapplicative

How can I use functors or applicatives to rewrite this Haskell function over lists of tuples


Is there a nicer way to write the following function fs' with functors or applicatives?

fncnB = (* 2)
fncnA = (* 3)
fs' fs = zip (map (fncnA . fst) fs) $ map (fncnB . snd) fs

I see from this question that I could rely on the functor instance of lists to map a single function acting over both elements of each tuple, or e.g. on the applicative instance of tuples to apply functions to just the second-half of a two-tuple, but I'm curious how functors and applicatives fit into the picture of operating over lists of multi-component data types.


Solution

  • A tuple is a bifunctor, so bimap is available.

    import Data.Bifunctor
    
    fncnB = (* 2)
    fncnA = (* 3)
    fs' = map (bimap fncnA fncnB)
    

    No third-party libraries required.