Created
February 15, 2022 12:30
-
-
Save ElectricCoffee/d08a7808910e35c122e5b5d1f2d73e00 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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