-
-
Save kana-sama/9224b4c8d7c4841e77a114e12c97c1d4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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