JSFiddle - React, Tailwind, and code Playground

by dimitrs_papadimitriou

JavaScript

var IO = fn => ({
  map: f => IO(() => f(fn())),
  chain: f => IO(() => f(fn()).run()),
  run: () => fn()
});
var Id = v => ({ v: v, map: f => Id(f(v)), chain: f => f(v) });

//foldMap :: Monoid m => (a -> m) -> t a -> m
const Free = {
  Pure: x => ({
    map: f => Free.Pure(f(x)),
    chain: f => f(x),
    foldMap: (_, typeRep) => {
      return typeRep(x);
    }
  }),
  Impure: (command, g) => ({
    map: f => Free.Impure(command, y => g(y).map(f)),
    chain: f => Free.Impure(command, y => g(y).chain(f)),
    foldMap: (interpreter, typeRep) => {
      return command
        .evaluate(interpreter)
        .chain(result => g(result).foldMap(interpreter, typeRep));
    }
  })
};

Promise.prototype.chain = function(func) {
  var initialPromise = this;
  return new Promise(function(resolve) {
    initialPromise.then(result => func(result).then(x => resolve(x)));
  });
};

Promise.prototype.map = function(mapping) {
  var initialPromise = this;
  return new Promise(function(resolve) {
    initialPromise.then(result => resolve(mapping(result)));
  });
};

var interpreter = {
  get: o => Promise.resolve(o.v),
  set: o => Promise.resolve(o)
};

var b = v =>
  Free.Impure({ evaluate: interpreter => interpreter.b(v) }, Free.Pure);

var d = a =>
  Free.Impure({ evaluate: interpreter => interpreter.d(a) }, Free.Pure);

var interpreter = f => ({
  b: o => IO(() => f(o)),
  d: o =>
    IO(() => {
      console.log(o);
    })
});

var coalg = n => (n >  0 ? b(n) : d );




var ana = n =>  coalg(n).chain(v => ana(v-1));
 

var result = ana(1000000000000);
 //var result = b(5).chain(v => b(v  ).chain( v => b(v  ).chain(v => b(v  ).chain(v => b(v ).chain(d))))) ;

var t = result.foldMap(interpreter(x => x + 1), o => IO(() => o)).run();

//  const repeat = n => f => x => done =>
//   n === 0
//     ? IO(() => x).chain(done)
//     : IO(() => f(x)).chain(x => repeat(n - 1)(f)(x)(done));
//https://gist.github.com/dypsilon/6b242998ba3474fc239255d42b28dd02

// var r = (x, s) => (x ==...