JSFiddle - React, Tailwind, and code Playground

by dimitrs_papadimitriou

JavaScript

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

const ok = (v) => ({
  v: v,
  map: (f) => ok(f(v)), 
  cata: (alg) => alg.ok(v),  
});

const error = (v) => ({
  v: v,
  map: () => error(v), 
  cata: (alg) => alg.error(v),  
});
 
var EitherCoyoAsync = function(actions, g) {
  this.g = g; 
  
  this.map = (f) => new EitherCoyoAsync(actions, x => f(this.g(x))); 
  
  this.bind = f =>{  
    var initialPromise = this;
    return new EitherCoyoAsync(function(resolve, reject) {
     actions(x => f(initialPromise.lower(x)).cata({ok:resolve,error:reject}) , x=>reject(x))
    }, x => x);
    
  }

  this.cata = alg => actions(x => alg.ok(this.lower(x)), alg.error); 
 
  this.cataP = alg => {
    var initialPromise = this;

    return new Promise(function(resolve, reject) {
      actions(x => resolve(alg.ok( initialPromise.lower(x)) ) , x=>reject(alg.error(x)))
     }) ;
}
  this.lower = (v) => this.g(v);
}

Promise.prototype.toEither = function() {
  var initialPromise = this;
  var either = new EitherCoyoAsync(function(resolve, reject) {
    initialPromise.then(resolve).catch(reject)
  }, x => x);
  return either;
}

  new Promise(function(resolve, reject) { resolve(4)})
 .toEither()    
 .cataP({
    ok:  v =>  v+1 ,
    error: v =>  "left" + v 
  })  
   .toEither()    
  .then(console.log).catch(console.log);





  using System;
  using System.Threading.Tasks;
  
  namespace C
  {
  
      public static partial class ƒ
      {
  
          public static EitherCoyoAsync<T> ToEither<T>(this Task<T> value) { return new EitherCoyoAsync<T>(value); }
  
      }
  
      public class EitherMonadCustomDemo
      {
          public static void Main()
          {
              Task.Run(() => 1).ToEither().Cata();
          }
      }
  
      public class Algebra<T>
      {
          Action<T> Ok { get; set; }
         ...