Last active
May 4, 2018 14:54
-
-
Save ddanielbee/426c965ba407ca39b669e2268ae0ada4 to your computer and use it in GitHub Desktop.
Functor Laws property based testing
This file contains 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
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