Binary Tree Catamorphism with Visitor

by dimitrs_papadimitriou

HTML

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

JavaScript

//http://bit.ly/jswitcatsbook
//Functional Programming in Javascript with Categories
var algList = {
    node: (l, v, r) => [].concat(l).concat(v).concat(r),
    leaf: (l) => [l]
  };
  
  var algSumInt = {
    node: (l, v, r) => l + v + r,
    leaf: (l) => l
  };
  
  var algPr = {
    node: (l, v, r) => `((${l}),${v},(${r}))`,
    leaf: (l) => l
  };
  
  var sumVsitor =  (alg)=>
  ({  
     visitNode : (n) => alg.node(n.l.accept(sumVsitor(alg)), n.v, n.r.accept(sumVsitor(alg))) ,  
     visitLeaf:l => alg.leaf(l.v)
  });
  
  
  var n = (l, v, r) => ({
    l: l,
    v: v,
    r: r,
    map: f => n(l.map(f), f(v), r.map(f)),
    accept:( visitor) => visitor.visitNode( n(l, v, r)) 
   
  });
  
  var lf = v => ({
    v: v, 
    map: f => lf(f(v)),
    accept: ( visitor) => visitor.visitLeaf( lf(v))
  });
  
  var inst = n(lf(2), 2, lf(3));
  
  var inst = n(n(n(lf(2), 2, lf(3)), 2, lf(3)), 2, n(lf(2), 2, n(lf(2), 2, lf(3))));
 
 
  console.log(inst.accept( sumVsitor( algSumInt  )))
  console.log(inst.accept( sumVsitor( algPr  )))