module Data.Generics.Uniplate
where
import Control.Monad
import Data.Generics.Uniplate.Internal.Utils
type UniplateType on = on -> ([on], [on] -> on)
class Uniplate on where
uniplate :: UniplateType on
universe :: Uniplate on => on -> [on]
universe x = builder (f x)
where
f :: Uniplate on => on -> (on -> res -> res) -> res -> res
f x cons nil = x `cons` concatCont (map (\x -> f x cons) $ children x) nil
children :: Uniplate on => on -> [on]
children = fst . uniplate
transform :: Uniplate on => (on -> on) -> on -> on
transform f x = f $ generate $ map (transform f) current
where (current, generate) = uniplate x
transformM :: (Monad m, Uniplate on) => (on -> m on) -> on -> m on
transformM f x = mapM (transformM f) current >>= f . generate
where (current, generate) = uniplate x
rewrite :: Uniplate on => (on -> Maybe on) -> on -> on
rewrite f = transform g
where g x = maybe x (rewrite f) (f x)
rewriteM :: (Monad m, Uniplate on) => (on -> m (Maybe on)) -> on -> m on
rewriteM f = transformM g
where g x = f x >>= maybe (return x) (rewriteM f)
descend :: Uniplate on => (on -> on) -> on -> on
descend f x = generate $ map f current
where (current, generate) = uniplate x
descendM :: (Monad m, Uniplate on) => (on -> m on) -> on -> m on
descendM f x = liftM generate $ mapM f current
where (current, generate) = uniplate x
contexts :: Uniplate on => on -> [(on, on -> on)]
contexts x = (x,id) : f (holes x)
where
f xs = [ (y, ctx . context)
| (child, ctx) <- xs
, (y, context) <- contexts child]
holes :: Uniplate on => on -> [(on, on -> on)]
holes x = uncurry f (uniplate x)
where f [] _ = []
f (x:xs) gen = (x, gen . (:xs)) :
f xs (gen . (x:))
para :: Uniplate on => (on -> [r] -> r) -> on -> r
para op x = op x $ map (para op) $ children x