Skip to content

Instantly share code, notes, and snippets.

@kana-sama
Last active October 3, 2017 00:39
Show Gist options
  • Select an option

  • Save kana-sama/e0dddbb9de77a3b1acd463cb9f747cd0 to your computer and use it in GitHub Desktop.

Select an option

Save kana-sama/e0dddbb9de77a3b1acd463cb9f747cd0 to your computer and use it in GitHub Desktop.
Tardis idea of using lazy value on js for lists
class Lazy {
constructor(value) {
this.value = value;
this.cache = null;
this.isCached = false;
}
exec() {
if (!this.isCached) {
this.cache = this.value();
this.isCached = true;
}
return this.cache;
}
}
const lazy = value => new Lazy(value);
const $ = lvalue => lvalue.exec();
const _1 = lazy(() => 1);
const _2 = lazy(() => 2);
const _3 = lazy(() => 3);
class Nil {}
class Cons { constructor( head, tail) { Object.assign(this, { head, tail }); } };
class Pair { constructor(first, second) { Object.assign(this, { first, second }); } };
const isNil = v => $(v) instanceof Nil;
const isCons = v => $(v) instanceof Cons;
const nil = lazy(() => new Nil());
const cons = ( head, tail) => lazy(() => new Cons( head, tail));
const pair = (first, second) => lazy(() => new Pair(first, second));
const max = (a, b) => lazy(() => {
return $(a) > $(b) ? $(a) : $(b);
});
const toArray = arr => {
if (isNil(arr)) {
return [];
}
return [
$($(arr).head),
...toArray($(arr).tail)
];
}
const repMax = (arr, rep) => {
if (isNil(arr)) {
return pair(rep, nil);
}
if (isNil($(arr).tail)) {
return pair($(arr).head, cons(rep, nil));
}
const result = repMax($(arr).tail, rep);
const m = max($(result).first, $(arr).head);
return pair(m, cons(rep, $(result).second));
}
const doRepMax = arr => {
const result = repMax(arr, lazy(() => $($(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