jarinel

fib

Oct 1st, 2018
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Tuple {
  2.   constructor(state, value) {
  3.    this.state = state;
  4.     this.value = value;
  5.   }
  6. }
  7.  
  8. class Nothing {
  9.   map = mapper => this;
  10.   get = () => 'nothing';
  11.   or = (value) => new Just(value);
  12. }
  13.  
  14. class Just {
  15.   constructor(value) {
  16.     this.value = value;
  17.   }
  18.  
  19.   map = mapper => new Just(mapper(this.value));
  20.   get = () => this.value;
  21.   or = (value) => this;
  22. }
  23.  
  24. class Memo {
  25.   data = {};
  26.   get = (key) => this.data[key] == null ? new Nothing() : new Just(this.data[key]);
  27.   add = (key, value) => {
  28.       this.data[key] = value;
  29.       return this;
  30.     };
  31. }
  32.  
  33. class State {
  34.   constructor(runState) {
  35.    this.runState = runState;
  36.   }
  37.  
  38.   static unit = value => new State(state => new Tuple(state, value));
  39.   static getState = getFromState => new State(state => new Tuple(state, getFromState(state)));
  40.   static transition = (mapper, value) => new State(state => new Tuple(mapper(state), value));
  41.   flatMap = mapper => new State(state => {
  42.     const temp = this.runState(state);
  43.     return mapper(temp.value).runState(temp.state);
  44.   })
  45.   map = mapper => this.flatMap(value => State.unit(mapper(value)));
  46.   eval = state => this.runState(state).value;
  47. }
  48.  
  49. const fib = n => State.getState(memo => memo.get(n))
  50.   .flatMap(maybe => maybe.map(value => State.unit(value)).or(
  51.     fib(n - 1).flatMap(prev => fib(n - 2)
  52.                                   .map(v => v + prev)
  53.                                   .flatMap(value => State.transition(memo => memo.add(n, value), value))
  54.               )
  55.   ).get())
  56.  
  57. const memo = new Memo();
  58. memo.add(0, 1);
  59. memo.add(1, 1);
  60.  
  61. console.log([...Array(9).keys()].map(n => fib(n).eval(memo)))
Advertisement
Add Comment
Please, Sign In to add comment