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

Simplifying syntax and implementation #41

Open
rodinhart opened this issue Apr 1, 2022 · 1 comment
Open

Simplifying syntax and implementation #41

rodinhart opened this issue Apr 1, 2022 · 1 comment

Comments

@rodinhart
Copy link

My suggestion for protocols

// polyfill
const protocol = (name: string, ...methods: string[]) => (() => {
    const symbols = Object.fromEntries(methods.map(key => [key, Symbol(`${name}.${key}`)]))

    return Object.assign(
        (Class: any, impl: Record<string, Function>) => {
            for (const [key, val] of Object.entries(impl)) {
                Class.prototype[symbols[key]] = val
            }
        },
        symbols
    )
})()

/*
    const Functor = protocol {
        fmap
    }

    OR

    protocol Functor {
        fmap
    }
*/
const Functor = protocol("Functor", "fmap")

/*
    String implements Functor {
        fmap: function(f) { return [...this].map(x => f(x)).join("") }
    }

    OR

    implement Functor for String {
        fmap: function(f) { return [...this].map(x => f(x)).join("") }
    }
*/
Functor(String, {
    fmap: function (f: (s: string) => string) { return [...this].map(x => f(x)).join("") }
})

console.log("Hello World"[Functor.fmap]((x: string) => x.toUpperCase()) // "HELLO WORLD"
@rodinhart
Copy link
Author

Although, I would want to go more functional (like Clojure):

const getTag = (x: any): string => {
    const t = typeof x

    if (t === "function") {
        return x.name
    }

    if (t !== "object") {
        return t
    }

    if (x === null) {
        return "null"
    }

    return x.constructor.name
}
const protocol = (...fns: string[]) => {
    const reg: Record<string, Record<string, Function>> = {}

    return fns.reduce((r, fn) => {
        r[fn] = (x: any, ...rest: any[]) => reg[getTag(x)][fn](x, ...rest)

        return r
    }, (x: any, impl: Record<string, Function>) => {
        reg[getTag(x)] = impl
    })
}


/*
    const Functor = protocol {
        fmap
    }
*/
const Functor = protocol("fmap")

/*
    implement null for Functor {
        fmap: (m, f) => null
    }
*/
Functor(null, {
    fmap: (m, f) => null
})

/*
    implement Array for Functor {
        fmap: (m, f) => m.map(x => f(x))
    }
*/

Functor(Array, {
    fmap: (m, f) => m.map(x => f(x))
})

const sq = (x: number) => x * x
console.log(Functor.fmap(null, sq), Functor.fmap([2, 3, 5], sq)) // null, [4, 9, 25]

Arguably, this doesn't require new syntax.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant