如何在javascript函数编程中使用IO和任意一个函子实现线性流?

如何在javascript函数编程中使用IO和任意一个函子实现线性流?,javascript,io,functional-programming,functor,either,Javascript,Io,Functional Programming,Functor,Either,结果:线性流,如getFile(filename).map(parseJson).map(doOtherThings). 当我使用或本身时,一切都很简单 function doSomethingCrazyHere(){ return "something crazy"; } function safeUnsureFunction(){ try{ return Right(doSomethingCrazyHere()); }catch(e){ re

结果:线性流,如
getFile(filename).map(parseJson).map(doOtherThings).

当我使用
本身时,一切都很简单

function doSomethingCrazyHere(){
  return "something crazy";
}

function safeUnsureFunction(){
    try{
       return Right(doSomethingCrazyHere());
    }catch(e){
       return Left(e);
    }
}
那么我就可以做下面的事情了

safeUnsureFunction().map((result)=>{
  // result is just result from doSomethingCrazyHere function
  // everything is linear now - I can map all along
  return result;
})
.map()
.map()
.map()
.map();
// linear flow
问题是当我使用IO时,像:

function safeReadFile(){
  try{
    return Right(fs.readFileSync(someFile,'utf-8'));
  }catch(e){
    return Left(error);
  }
}

let pure=IO.from(safeReadFile).map((result)=>{
  // result is now Either
  // so when I want to be linear I must stay here
  // code from now on is not linear and I must generate here another chain

  return result.map(IdontWant).map(ToGo).map(ThisWay).map(ToTheRightSideOfTheScreen);
})
.map((result)=>{
  return result.map(This).map(Is).map(Wrong).map(Way);
})
.map(IwantToBeLienearAgain)
.map(AndDoSomeWorkHere)
.map(ButMapFromIOreturnsIOallOverAgain);

let unpure=function(){
  return pure.run();
}
IO用于区分纯函数和非纯函数,对吗

所以我想用两种错误处理方法来分离非纯文件读取。这可能吗

在IO单子中使用Eithers时,如何实现线性流

函数式编程中是否有这种模式


readFile(filename).map(JSON.parse).map(doSomethingElse)…

唯一的方法是将
safeRun
方法添加到
IO
因此,在最后我们将有
,我们将优雅地从错误中恢复

class safeIO {
  // ...

  safeRun(){
    try{
      return Right(this.run());
    }catch(e){
      return Left(e);
    }
  }

  //...
}
我们必须使用普通
readFile

function readFile(){
    return fs.readFileSync(someFile,'utf-8');
}

let pure = safeIO.from(readFile)
.map((result)=>{
  // result is now file content if there was no error at the reading stage
  // so we can map like in normal IO
  return result;
})
.map(JSON.parse)
.map(OtherLogic)
.map(InLinearFashion);

let unpure = function(){
  return pure.safeRun(); // -> Either Left or Right
}
或者将
try catch
逻辑置于
IO
之外,进入
unpure
函数本身,而不修改任何
IO

let unpure = function(){
  try{
    return Right(pure.run());
  }catch(e){
    return Left(e);
  }
}
unpure(); // -> Either
我可以看看这里