I'd like to add to tel's answer (I got my idea only after reading it) that in many cases you can make general natural transformation that will work similarly to foldMap
. If we can use foldMap
, we know that f
is Foldable
. Then we need some way how to constructs elements of g a
and combine them together. We can use Alternative
for that, it has all we need (pure
, empty
and <|>
), although we could also construct some less general type class for this purpose (we don't need <*>
anywhere).
{-# LANGUAGE TypeOperators, RankNTypes #-}
import Prelude hiding (foldr)
import Control.Applicative
import Data.Foldable
type f :~> g = forall a. f a -> g a
nt :: (Functor f, Foldable f, Alternative g) => f :~> g
nt = foldr ((<|>) . pure) empty
Then using tel's xmap
xmap :: (a -> b) -> (f :~> g) -> (f a -> g b)
xmap f n = map f . n
we can do things like
> xmap (+1) nt (Just 1) :: [Int]
[2]