Skip to content

Instantly share code, notes, and snippets.

@acquitelol
Last active April 22, 2025 01:58
Show Gist options
  • Select an option

  • Save acquitelol/de6662034916270ed603880ec04aa017 to your computer and use it in GitHub Desktop.

Select an option

Save acquitelol/de6662034916270ed603880ec04aa017 to your computer and use it in GitHub Desktop.
An implementation of division in pure-functional style but in JavaScript
const succ = n => f => x => f (n (f) (x))
const pred = n => f => x => n (g => h => h (g (f))) (u => x) (u => u)
const sub = m => n => n (pred) (m)
// these functions are using js primitives so theyre not pure anyway
// which means i can use js features like binops and ternaries
const churchToJs = n => n (x => x + 1) (0)
const jsToChurch = n => n === 0 ? False : succ (jsToChurch (n - 1))
const True = x => y => x
const False = x => y => y
const If = cond => x => y => cond (x) (y) () // requires to be unwrapped b/c lazy
const isZero = n => n (_ => False) (True)
const gte = m => n => isZero (sub (n) (m))
const Y = f => (x => f (y => x (x) (y))) (x => f (y => x (x) (y)))
const div = m => n => Y (f => m => If (gte (m) (n)) (() => succ (f (sub (m) (n)))) (() => False)) (m)
console.log (churchToJs (div (jsToChurch (10)) (jsToChurch (2)))) // 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment