JSFiddle - React, Tailwind, and code Playground
by dimitrs_papadimitriou
JavaScript
Object.prototype.log = function () {
console.log(JSON.stringify(this));
};
class Tree {}
class Node extends Tree {
constructor(left, right) {
super()
this.left = left;
this.right = right;
}
cata(algebra) {
return algebra.Node(this.left, this.right);
}
show() {
return ` (${this.left.show( )} ,${this.right.show( )})`;
}
}
class Leaf extends Tree {
constructor(v) {
super()
this.v = v;
}
cata(algebra) {
return algebra.Leaf(this.v);
}
show() {
return (` ${ this.v} `);
}
}
Array.prototype.cata = function (alg) {
if (this.length === 0) {
return alg.empty();
} else {
return alg.concat(this.shift(), this)
}
};
var zipOrderd = (a1, a2) => a1.cata({
empty: _ => a2,
concat: (x, xs) => a2.cata({
empty: _ => xs,
concat: (y, ys) => x > y ? [x].concat(zipOrderd(xs, [y].concat(ys))) : [y].concat(zipOrderd(ys, [x].concat(xs)))
})
})
var ana = a => a.length == 1 ? new Leaf(a) :
new Node(ana(a.slice(0, a.length / 2)),
ana(a.slice(a.length / 2, a.length)));
Tree.prototype.sort = function () {
this.show().log()
return this.cata({
Leaf: v => v,
Node: (l, r) => zipOrderd(l.sort(), r.sort())
})
}
var mergesort = a => ana(a).sort()
console.log(mergesort([3, 7,10, 4, 1, 11, 5]))
///////////
Object.prototype.log = function () {
console.log(JSON.stringify(this));
};
class List {}
class Cons extends List {
constructor(v, rest) {
super()
this.v = v;
this.rest = rest;
}
cata(algebra) {
return algebra.Cons(this.v, this.rest);
}
show() {
return ` (${this.v } ,${this.rest.show( )})`;
}
}
class Nill extends List {
constructor(v) {
super()
}
cata(algebra) {
return algebra.Nill();
}
show() {
return (` Nill `);
}
}
Array.prototype.toBase = function () {
if (this.length === 0) {
return new Nill();
} else {
return new Cons(this.shift(), this.toBase())
}
};
[2, 3, 4,...