module Data.Generics.UniplateStr
(
module Data.Generics.UniplateStr,
module Data.Generics.Str
) where
import Control.Monad hiding (mapM)
import Data.Traversable
import Prelude hiding (mapM)
import Data.Generics.Uniplate.Internal.Utils
import Data.Generics.Str
type UniplateType on = on -> (Str on, Str on -> on)
class Uniplate on where
uniplate :: UniplateType on
uniplateList :: Uniplate on => on -> ([on], [on] -> on)
uniplateList x = (c, b . d)
where
(a,b) = uniplate x
(c,d) = strStructure a
universe :: Uniplate on => on -> [on]
universe x = builder f
where
f cons nil = g cons nil (One x) nil
g cons nil Zero res = res
g cons nil (One x) res = x `cons` g cons nil (fst $ uniplate x) res
g cons nil (Two x y) res = g cons nil x (g cons nil y res)
children :: Uniplate on => on -> [on]
children x = builder f
where
f cons nil = g cons nil (fst $ uniplate x) nil
g cons nil Zero res = res
g cons nil (One x) res = x `cons` res
g cons nil (Two x y) res = g cons nil x (g cons nil y res)
transform :: Uniplate on => (on -> on) -> on -> on
transform f = f . descend (transform f)
transformM :: (Monad m, Uniplate on) => (on -> m on) -> on -> m on
transformM f x = f =<< descendM (transformM f) 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 $ fmap 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 Zero _ = []
f (One i) generate = [(i, generate . One)]
f (Two l r) gen = f l (gen . (\i -> Two i r))
++ f r (gen . (\i -> Two l i))
para :: Uniplate on => (on -> [r] -> r) -> on -> r
para op x = op x $ map (para op) $ children x