haskellfunctional-programmingfoldable

For for foldables


for is flip traverse.

forM is flip mapM.

And so on with for_, etc.

What about foldMap? It's lonely.

flip foldMap = ?


Solution

  • It would be silly if every 2-argument function had a flipped counterpart. The reason the for variants are worthwhile is mainly that they play so nicely together with do notation, in a way that closely remembers e.g. Python loops.

    main = do
      ...
      forM_ [0..9] $ \i -> do
         print i
         ...
      return ()
    

    For foldMap you could still benefit from a syntax-heralding $+lambda on the RHS, however you wouldn't be in a monad (at least not one used as such), wouldn't use do notation, and probably would need some parentheses anyway. So there's not much advantage to be had over the regular foldMap with a parenthesized function in the middle.