Generalized `fold` or how to execute` fold` and `map` at a time

(Apology by name, I can not do better)

My question is to find a generalized structural or "standard" function to perform the following task:

xmap :: (a -> b) -> fa -> gb 

then we can display not only elements, but the whole structure.

Some (not real) examples

 xmap id myBinaryTree :: [a] 

for now, I have to make an explicit structure converter (typical fromList , toList ), then

 toList . fmap id -- if source struct has map fmap id . fromList -- if destination struct has map 

(to execute toStruct , fromStruct I use fold ).

Is there some way to generalize to / from structures? (should be) xmap there this function ( xmap )?

Thanks!:)

+4
source share
2 answers

I would like to add to tel's answer (I got my idea only after reading it) that in many cases you can do a general natural conversion that will work the same way before foldMap . If we can use foldMap , we know that f is Foldable . Then we need to somehow build the elements of ga and combine them together. We can use Alternative for this, it has everything we need ( pure , empty and <|> ), although we could also build a less general class of classes for this purpose (we do not need <*> anywhere).

 {-# LANGUAGE TypeOperators, RankNTypes #-} import Prelude hiding (foldr) import Control.Applicative import Data.Foldable type f :~> g = forall a. fa -> ga nt :: (Functor f, Foldable f, Alternative g) => f :~> g nt = foldr ((<|>) . pure) empty 

Then using tel xmap

 xmap :: (a -> b) -> (f :~> g) -> (fa -> gb) xmap fn = map f . n 

we can do things like

 > xmap (+1) nt (Just 1) :: [Int] [2] 
+4
source

Since f and g are functors, a natural transformation is what you are looking for (see also you could define natural transformations ). So type conversion

 f :~> g = forall a. fa -> ga 

needed to create xmap, which is then simply

 xmap :: (a -> b) -> (f :~> g) -> (fa -> gb) xmap fn = map f . n 

You still need to define types (f :~> g) , but there is no general way to do this.

+5
source

Source: https://habr.com/ru/post/1493195/


All Articles