Skip to content

Instantly share code, notes, and snippets.

@OlegLustenko
Forked from kana-sama/1.js
Created October 2, 2017 07:30
Show Gist options
  • Save OlegLustenko/7ff1701b195f6dbd861081a6c43943e9 to your computer and use it in GitHub Desktop.
Save OlegLustenko/7ff1701b195f6dbd861081a6c43943e9 to your computer and use it in GitHub Desktop.
class Nil {}
class Cons { constructor( head, tail) { Object.assign(this, { head, tail }); } };
class Pair { constructor(first, second) { Object.assign(this, { first, second }); } };
const _1 = () => 1;
const _2 = () => 2;
const _3 = () => 3;
const nil = () => new Nil();
const cons = (head, tail) => () => new Cons(head, tail);
const pair = (first, second) => () => new Pair(first, second);
const toArray = arr => {
const arr_ = arr();
if (arr_ instanceof Nil) {
return [];
}
return [arr_.head(), ...toArray(arr_.tail)];
}
const max = (a, b) => () => {
const a_ = a();
const b_ = b();
return a_ > b_ ? a_ : b_;
}
const repMax = (arr, rep) => {
const arr_ = arr();
if (arr_ instanceof Nil) {
return pair(rep, nil);
}
const head_ = arr_.head();
const tail_ = arr_.tail();
if (tail_ instanceof Nil) {
return pair(() => head_, cons(rep, nil));
}
const result_ = repMax(() => tail_, rep)();
const m = max(result_.first, () => head_);
return pair(m, cons(rep, result_.second));
}
const doRepMax = arr => {
const result_ = repMax(arr, () => result_.first())();
return result_.second;
}
const x = cons(_1, cons(_3, cons(_2, nil)));
const y = doRepMax(x);
console.log(toArray(y)); // [3, 3, 3]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment