List catamorphisms

by dimitrs_papadimitriou

HTML

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

JavaScript

Array.prototype.matchWith = function (pattern) {
        return this.length == 0 ?
            pattern.empty() :
            pattern.concat(this[0], this.slice(1));// informed decesion not to clone
    }

    Array.prototype.cata = function (evaluation) {
        return this.matchWith({
            empty: () => evaluation.empty(),
            concat: (head, tail) => evaluation.concat(head,tail.cata(evaluation))
        })
    }

    var foldAlg = (acc, reducer) => ({
        empty: () => acc,
        concat: (v, r) => reducer(reducer(acc, v), r)
    })
    
    const fold = array=>array.cata(foldAlg(0, (acc, i) => acc + i));
   
   console.log(fold([1, 2, 6, 4, 5, 2]));