Skip to content

Instantly share code, notes, and snippets.

@ElectricCoffee
Created February 15, 2022 12:30
Show Gist options
  • Save ElectricCoffee/d08a7808910e35c122e5b5d1f2d73e00 to your computer and use it in GitHub Desktop.
Save ElectricCoffee/d08a7808910e35c122e5b5d1f2d73e00 to your computer and use it in GitHub Desktop.
class Monoid<T>{
mzero: T;
mplus: (a: T, b: T) => T;
constructor(mzero: T, mplus: (a: T, b: T) => T) {
this.mzero = mzero;
this.mplus = mplus;
}
}
const add = new Monoid<number>(0, (a, b) => a + b);
const mul = new Monoid<number>(1, (a, b) => a * b);
const arr = new Monoid<any[]>([], (a, b) => a.concat(b));
const foldM = <T>(monoid: Monoid<T>, data: T[]) => data.reduce(monoid.mplus, monoid.mzero);
let a = [[1], [2, 3], [4], [5]];
let b = [1, 2, 3, 4, 5];
alert(foldM(arr, a));
alert(foldM(add, b));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment