Skip to content

Instantly share code, notes, and snippets.

@ppsdatta
Last active April 17, 2022 15:40
Show Gist options
  • Select an option

  • Save ppsdatta/fea2469dcde759b215dd356cb60b21df to your computer and use it in GitHub Desktop.

Select an option

Save ppsdatta/fea2469dcde759b215dd356cb60b21df to your computer and use it in GitHub Desktop.
// Combinators
const I = x => x
const K = (x, y) => x
const S = (b, u) => x => b(u(x), x)
const Sp = (b, u, v) => x => b(u(x), v(x))
const B = (u, v) => (x) => u(v(x))
const C = (b, u, v) => (x, y) => b(u(x, y), v(y))
// Helpers
const eq = (x, y) => x === y
const reverse = (s) => s.split("").reverse().join("")
const flip = f => (x, y) => f(y, x)
const max = xs => xs.sort()[xs.length - 1]
const min = xs => xs.sort()[0]
const pair = (x, y) => [x, y]
const partition_aux = (carr, parr, aux) => {
if (carr.length === 0 || parr.length === 0) return aux
return partition_aux(
carr.slice(1),
parr.slice(1),
(carr[0] === 0) ? [[...aux[0], parr[0]], aux[1]] : [aux[0], [...aux[1], parr[0]]]
)
}
const partition = (carr, parr) => partition_aux(carr, parr, [[], []])
const same_aux = (xs, ys, comp) => {
if (xs.length === 0 || ys.length === 0) return comp
return same_aux(xs.slice(1), ys.slice(1), [...comp, (xs[0] === ys[0])? 1 : 0])
}
const same_arr = (xs, ys) => same_aux(xs, ys, [])
// Applications
const isPalindrome1 = S(eq, reverse)
const isPalindrome2 = Sp(eq, reverse, I)
const minMaxPair = Sp(pair, min, max)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment