(Apology by the title, I can't do better)
My question is to find some generalized struct or "standard" function to perform the next thing:
xmap :: (a -> b) -> f a -> g b
then, we can map not only elements, by also the entire struct.
Some (not real) example
xmap id myBinaryTree :: [a]
at the moment, I must to do a explicit structure conversor (typical fromList
, toList
) then
toList . fmap id -- if source struct has map
fmap id . fromList -- if destination struct has map
(to perform toStruct
, fromStruct
I use fold
).
Exists some way to generalize to
/from
structs? (should be)
Exists that function (xmap
)?
Thank you!! :)
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 usefoldMap
, we know thatf
isFoldable
. Then we need some way how to constructs elements ofg a
and combine them together. We can useAlternative
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).Then using tel's
xmap
we can do things like
As
f
andg
are functors, a natural transformation is what you're looking for (see also You Could Have Defined Natural Transformations). So a transformation likeis needed to create xmap which is then just
You still need to define types of
(f :~> g)
, but there' not a general way of doing that.