2016-12-13 2 views
3

結果:getFile(filename).map(parseJson).map(doOtherThings)...IOとリニアフローを実装する方法と関数型プログラミングでjavascriptを使用する方法

のような直線流IがEitherを使用しています自体すべてが、私はちょうど私が「ときは、次の

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)....

+0

をmodyfingずにunpure関数自体にIOtry catchロジックを取ることは、ここにhttps://github.com/fantasyland/fantasy-land顔をしているかもしれません –

答えて

1

唯一の方法は、その最後に、我々はEitherを持っていますIOsafeRunメソッドを追加することができ、私たちは優雅に返しsafeReadFile

class safeIO { 
    // ... 

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

    //... 
} 

代わりにエラーから回復しますEither通常使用する必要があります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 
} 

または任意のIO

let unpure = function(){ 
    try{ 
    return Right(pure.run()); 
    }catch(e){ 
    return Left(e); 
    } 
} 
unpure(); // -> Either 
関連する問題