Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Writer monad #10

Open
cwmyers opened this issue May 20, 2014 · 1 comment
Open

Writer monad #10

cwmyers opened this issue May 20, 2014 · 1 comment
Assignees
Milestone

Comments

@cwmyers
Copy link
Collaborator

cwmyers commented May 20, 2014

No description provided.

@cwmyers cwmyers added this to the 0.9 Release milestone May 20, 2014
@cwmyers cwmyers self-assigned this May 20, 2014
@ulfryk ulfryk modified the milestones: 0.10 Release, 0.9 Release Jun 9, 2016
@ulfryk
Copy link
Member

ulfryk commented Nov 19, 2018

As a scratch to start with:

interface Semigroup<T> {
    concat(a: T): T
}

class Writer<V, L extends Semigroup<L>> {

    public static of<X, Y extends Semigroup<Y>>(empty: Y) {
        return (value: X) => new Writer<X, Y>(value, empty)
    }

    constructor(
        private readonly value: V,
        private readonly log: L,
    ) { }

    public map<Z>(fn: (v: V) => Z): Writer<Z, L> {
        return new Writer(fn(this.value), this.log)
    }

    public flatMap<Z>(fn: (v: V) => Writer<Z, L>): Writer<Z, L> {
        const { value, log } = fn(this.value)

        return new Writer(value, this.log.concat(log))
    }

    public toString() {
        return `(${this.value}, "${this.log}")`
    }

    public equals(other: Writer<V, L>) {
        return String(this) === String(other)
    }

}

const unit = Writer.of<number, string>('')
const add5 = (a: number) => Writer.of<number, string>('added 5, ')(a + 5)
const add8 = (a: number) => Writer.of<number, string>('added 8, ')(a + 8)
const theOne = new Writer(1, 'Initial One, ')

console.assert(unit(3).flatMap(add5).equals(add5(3)), 'Left identity')
console.assert(theOne.flatMap(unit).equals(theOne), 'Right identity')
console.assert(theOne.flatMap(add5).flatMap(add8).equals(theOne.flatMap(one => add5(one).flatMap(add8))) , 'Associativity')

@ulfryk ulfryk modified the milestones: 0.10 Release, 1.0.0 Nov 20, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants