Skip to content

Instantly share code, notes, and snippets.

@Ivana-
Last active January 6, 2019 17:35
Show Gist options
  • Save Ivana-/8069f64a6ed26bd7f3c24e3bafaab674 to your computer and use it in GitHub Desktop.
Save Ivana-/8069f64a6ed26bd7f3c24e3bafaab674 to your computer and use it in GitHub Desktop.
webinar 2 Javascript
print("\n\n\n")
// волшебная троица
const cons = (x, y) => [x,y]
const car = (l) => l[0]
const cdr = (l) => l[1]
// scons(h, t) = cons(h, lz(() => t))
const lz = (x) => x
// хвост потока
const stail = (s) => {
const t = cdr(s)
return (typeof t === "function") ? t() : t
}
// часть потока в вектор
const stake = (n, s) => {
r = []
while (n>0) {
r.push(car(s))
s = stail(s)
n = n-1
}
return r
}
const ones = cons(1, lz(() => ones))
print(stake(10, ones))
const intfrom = (n) => cons(n, lz(() => intfrom(n+1)))
print(stake(10, intfrom(1)))
const ssum = (a, b) => cons(car(a)+car(b), lz(() => ssum(stail(a), stail(b))))
const fibs = cons(0, cons(1, lz(() => ssum(stail(fibs), fibs))))
print(stake(10, fibs))
const smap = (f, s) => cons(f(car(s)), lz(() => smap(f, stail(s))))
const sk = (k, s) => smap((x) => k*x, s)
const n = 50
print("\nчисла Хэмминга:")
const merge = (a, b) =>
(car(a) < car(b)) ? cons(car(a), lz(() => merge(stail(a), b))) :
(car(a) > car(b)) ? cons(car(b), lz(() => merge(a, stail(b)))) :
cons(car(a), lz(() => merge(stail(a), stail(b))))
const hamm = cons(1, lz(() => merge(sk(2,hamm), merge(sk(3,hamm), sk(5,hamm)))))
print(stake(n, hamm))
// потоковые аналоги списковых функций
const sfilter = (f, s) =>
f(car(s)) ? cons(car(s), lz(() => sfilter(f, stail(s)))) : sfilter(f, stail(s))
// тестовые примеры
print("\nряд Фибоначчи (НЕ экспоненциальный расчет):")
const fibgen = (a,b) => cons(a, lz(() => fibgen(b, a+b)))
const fibs1 = fibgen(0,1)
print(stake(n, fibs1))
print("\nчетные числа:")
const evens = sfilter((x) => x%2 === 0, intfrom(0))
print(stake(n, evens))
print("\nпростые числа через решето Эратосфена:")
const sieve = (s) => {
const r = sfilter((x) => x % car(s) != 0, stail(s))
return cons(car(s), lz(() => sieve(r)))
}
const primesErat = sieve(intfrom(2))
print(stake(n, primesErat))
print("\nпростые числа через гипотезу Бертрана:")
const primesBert = () => cons(2, lz(() => sfilter(isprime, intfrom(3))))
const isprime = (n) => {
const iter = (ps) =>
(car(ps)*car(ps) > n) ? true :
(n % car(ps) === 0) ? false :
iter(stail(ps))
return iter(primesBert())
}
print(stake(n, primesBert()))
print("\nчастичные суммы натурального ряда:")
const partialsums = (s) => {
const go = (a, s) => cons(a+car(s), lz(() => go(a+car(s), stail(s))))
return go(0, s)
}
print(stake(n, partialsums(intfrom(1))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment