Skip to content

Instantly share code, notes, and snippets.

@dimitris-papadimitriou-chr
Last active July 2, 2020 17:46
Show Gist options
  • Select an option

  • Save dimitris-papadimitriou-chr/c10cdaafc7065bca45af02cb6009dcb3 to your computer and use it in GitHub Desktop.

Select an option

Save dimitris-papadimitriou-chr/c10cdaafc7065bca45af02cb6009dcb3 to your computer and use it in GitHub Desktop.
class Balance {
static Left = new Balance(0, 1)
static Right = new Balance(1, 0)
static Empty = new Balance(0, 0)
L: number
R: number
constructor(l: number, r: number) {
this.L = l;
this.R = r;
}
}
class MonoidWeight implements monoid<Balance> {
empty: Balance = Balance.Empty;
concat(x: Balance, y: Balance): Balance {
if (x.R < y.L)
return new Balance(x.L + y.L - x.R, y.R);
else
return new Balance(x.L, y.R + x.R - y.L);
}
}
var parse: (c: string) => Balance = (c: string) => {
switch (c) {
case "(": return Balance.Left
case ")": return Balance.Right
default: return Balance.Empty
}
}
var weight = new MonoidWeight();
var parsed = Array.from("((()))()").map(parse).reduce(weight.concat, weight.empty); //{L:0,R:0}
var parsed = Array.from("((()))(").map(parse).reduce(weight.concat, weight.empty); //{L:0,R:1}
var parsed = Array.from(")((()))(").map(parse).reduce(weight.concat, weight.empty); //{L:1,R:1}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment