Fold

by dimitrs_papadimitriou

HTML

<script src="https://rawgit.com/eu81273/jsfiddle-console/master/console.js"></script>

JavaScript

// f :: Int -> Maybe (Int, Int)
// f current = let oneSmaller = current - 1
//             in   if oneSmaller < 0
//                    then Nothing
//                    else Just (oneSmaller, oneSmaller)

// ana :: (state -> Maybe (value, state)) -> state -> [value]
// ana f stateOld = case f stateOld of
//             Nothing                -> []
//             Just (value, stateNew) -> value : ana f stateNew

  


const some = v => ({
  v: v, 
  cata: (alg) => alg.some(v), 
  });

var none = _ => ({
   cata: (alg) => alg.none( ), 
 });

var coAlgList = n=>n<=0? none() : some({h:n-1, s:n-1});

 var ana  = (colAg, oldState)=>colAg(oldState).cata({
  some: (v) => [v.h].concat(ana(colAg, v.s) ) ,
  none: (_) => [] 
 })

 var d  = ana(coAlgList, 5);

 console.log(d)