Skip to content

Instantly share code, notes, and snippets.

@houzyk
Last active August 6, 2023 09:17
Show Gist options
  • Save houzyk/d38c66f1efcb62ea9e2803bd75812c73 to your computer and use it in GitHub Desktop.
Save houzyk/d38c66f1efcb62ea9e2803bd75812c73 to your computer and use it in GitHub Desktop.
a-tale-of-numbers-and-functions
const zero = F => V => V;
const one = F => V => F(V);
const two = F => V => F(F(V));
const three = F => V => F(F(F(V)));
const add = N => M => F => V => N(F)(M(F)(V));
const multiply = N => M => F => V => N(M(F))(V);
const power = N => M => F => V => (M(N))(F)(V);
const successor = N => F => V => F(N(F)(V));
const predecessor = N => F => V => N(g => h => h(g(F)))(u => V)(u => u);
let trackerFuncCallCount = 0;
const trackerFunc = () => {
trackerFuncCallCount++; // increments for each function call
}
// ! ONLY RUN ONE OF THE BELOW FUNCTION CALLS AT A TIME.
// Else, you'll mess with trackerFuncCallCount.
// So, just uncomment one function call and run the code.
// zero(trackerFunc)(); // trackerFuncCallCount => 0
// one(trackerFunc)(); // trackerFuncCallCount => 1
// two(trackerFunc)(); // trackerFuncCallCount => 2
// three(trackerFunc)(); // trackerFuncCallCount => 3
// add(one)(two)(trackerFunc)(); // trackerFuncCallCount => 3
// add(three)(three)(trackerFunc)(); // trackerFuncCallCount => 6
// multiply(one)(two)(trackerFunc)(); // trackerFuncCallCount => 2
// multiply(three)(three)(trackerFunc)(); // trackerFuncCallCount => 9
// power(one)(two)(trackerFunc)(); // trackerFuncCallCount => 1
// power(three)(three)(trackerFunc)(); // trackerFuncCallCount => 27
// successor(one)(trackerFunc)(); // trackerFuncCallCount => 2
// successor(three)(trackerFunc)(); // trackerFuncCallCount => 4
// successor(successor(one))(trackerFunc)(); // trackerFuncCallCount => 3
// predecessor(one)(trackerFunc)(); // trackerFuncCallCount => 0
// predecessor(three)(trackerFunc)(); // trackerFuncCallCount => 2
// predecessor(predecessor(three))(trackerFunc)(); // trackerFuncCallCount => 1
console.log(trackerFuncCallCount);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment