Skip to content

Instantly share code, notes, and snippets.

@Ivana-
Created July 13, 2020 00:47
Show Gist options
  • Save Ivana-/80a44b44be2adbf7efaf53eabb7060bc to your computer and use it in GitHub Desktop.
Save Ivana-/80a44b44be2adbf7efaf53eabb7060bc to your computer and use it in GitHub Desktop.
CPS in javascript (JavaScript Core, strict mode - for TCO)
"use strict";
///////////////////////////////////////////////////////////////////////////////////////////////////////////
// волшебная троица
const cons = (x, y) => [x,y]
const car = (l) => l[0]
const cdr = (l) => l[1]
const nil = cons(null, null)
const isnull = (l) => car(l) == null && cdr(l) == null
const show = (l) => {
if (Array.isArray(l)) {
var r = ''
while (!isnull(l)) {
r = r + ' ' + show(car(l))
l = cdr(l)
}
return '(' + r.substring(1) + ')'
} else return l
}
const listFromTo = (a, b) => {
var l = nil
while (b >= a) {
l = cons(b, l)
b -= 1
}
return l
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
const mapN = (f, l) => isnull(l) ? nil : cons(f(car(l)), mapN(f, cdr(l)))
const mapC = (f, l) => {
const go = (l, cont) => isnull(l) ? cont(nil) : go(cdr(l), (x) => cont(cons(f(car(l)), x)))
return go(l, (x) => x)
}
const a = listFromTo(1, 10)
const b = listFromTo(1, 50000)
// print(show(a))
print("mapC a: ", show(mapC((x) => x*10, a))) // OK
print("mapC b: ", show(mapC((x) => x*10, b))) // OK
print("mapN a: ", show(mapN((x) => x*10, a))) // OK
print("mapN b: ", show(mapN((x) => x*10, b))) // Exception: RangeError: Maximum call stack size exceeded.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment