Skip to content

Instantly share code, notes, and snippets.

@ddanielbee
Last active May 4, 2018 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ddanielbee/426c965ba407ca39b669e2268ae0ada4 to your computer and use it in GitHub Desktop.
Save ddanielbee/426c965ba407ca39b669e2268ae0ada4 to your computer and use it in GitHub Desktop.
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