Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Functor Laws property based testing
const jsc = require("jsverify");
// Necessary Utils
const id = x => x;
const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x);
// Functor Properties
const functorIdentity = f => f.fmap(id).toString() === f.toString();
const functorCompose = (f, g, x) =>
x
.fmap(g)
.fmap(f)
.toString() === x.fmap(compose(f, g)).toString();
// Test functor laws of a Maybe implementation
const Nothing = () => ({
fmap: fn => Nothing(),
inspect: () => "Nothing",
toString: () => "Nothing"
});
const Just = x => ({
fmap: fn => Just(fn(x)),
inspect: () => `Just(${x})`,
toString: () => `Just(${x})`
});
const arbitraryMaybe = jsc.bless({
generator: () => {
switch (jsc.random(0, 1)) {
case 0:
return Nothing();
case 1:
return Just(jsc.integer);
}
}
});
describe("Law abidding Maybe Functor", () => {
it("fulfils identity", () => {
expect(jsc.checkForall(arbitraryMaybe, functorIdentity)).toBe(true);
});
it("fulfils composition", () => {
expect(
jsc.checkForall(jsc.fn(jsc.integer), jsc.fn(jsc.integer), arbitraryMaybe, functorCompose)
).toBe(true);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.