{-
  Purpose:
    Further develop idea that Bifold in posts:
      http://article.gmane.org/gmane.comp.lang.haskell.cafe/83874
      http://article.gmane.org/gmane.comp.lang.haskell.cafe/83883
    if somehow like the f in section 12.5 of:
      http://www.thocp.net/biographies/papers/backus_turingaward_lecture.pdf
-}

module BifoldIfRecur where
  import Monad;
  import Control.Applicative;

-- {*83874 article
  {-
  bifold :: (l -> a -> r -> (r,l)) -> (l,r) -> [a] -> (r,l)
  bifold _ (l,r) [] = (r,l)
  bifold f (l,r) (a:as) = (ra,las)
   where (ras,las) = bifold f (la,r) as
           (ra,la) = f l a ras
  -}
-- }*83874 article

-- {*83883 article
  {--}
  (.^) :: (a -> a) -> Int -> a -> a
  f .^ 0 = id
  f .^ n = f . (f .^ (n - 1))
  
  (./) :: (b -> c -> c) -> [a -> b] -> (a->c) -> a -> c
  (./) = flip . foldr . \h f g -> h <$> f <*> g
  
  _Q_ :: (b -> c -> c) -> (a -> b) -> (a -> a) -> (a -> c) -> a -> c
  _Q_ h i j k = h <$> i <*> (k . j)
  {--}
-- }*83883 article

-- {*if_recur.hpp from http://svn.boost.org/svn/boost/sandbox/variadic_templates/boost/mpl/
  if_recur :: state_down
           -> (state_down -> Bool) 
           -> (state_down -> state_down) 
           -> ((state_down,state_up) -> state_up) 
           -> (state_down -> state_up)
           -> state_up
  
  if_recur state_now  -- current state
           recur_     -- continue recursion?
           then_down  -- ::state_down -> state_down
           now_up     -- ::((state_down,state_up)->state_up
           else_      -- ::state_down -> state_up
           = if recur_ state_now
             then now_up
                  ( state_now
                  , if_recur (then_down state_now)
                             recur_
                             then_down
                             now_up
                             else_
                  )
             else else_ state_now

-- }*if_recur.hpp from http://svn.boost.org/svn/boost/sandbox/variadic_templates/boost/mpl/

{--}
  palindrome_btm :: [a] -> a -> [a]

  palindrome_btm x b = if_recur 
                   (x,[]) --state_now
                   (not.null.fst) --recur_
                   (\(sn,cd) -> (tail sn,(head sn):cd)) --then_down
                   (\(sn,cu) -> (head $ fst sn):cu) --now_up
                   (\(sn,cd) -> b:cd)

  test = sequence
         [ print (palindrome_btm [1,2,3] 999)
         , print (foldl (flip(:)) [999] [1,2,3])
         , print (foldr (:) [999] [1,2,3])
         ]
{--}
