Result: linear flow like getFile(filename).map(parseJson).map(doOtherThings)...
When I'm using Either itself everything is nice and easy
function doSomethingCrazyHere(){
return "something crazy";
}
function safeUnsureFunction(){
try{
return Right(doSomethingCrazyHere());
}catch(e){
return Left(e);
}
}
then I can just do the following
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
problem is when I'm using IO like:
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 is for separating pure from not so pure functions right?
So I want to separate unpure file read with also Either file error handling. Is this possible?
How to have linear flow when using Eithers inside IO monads?
Is there any pattern in functional programming for this?
readFile(filename).map(JSON.parse).map(doSomethingElse)....
Only way for this could be to add safeRun method to the IO
so at the end we will have Either and we will gracefully recover from error
class safeIO {
// ...
safeRun(){
try{
return Right(this.run());
}catch(e){
return Left(e);
}
}
//...
}
Instead of safeReadFile that returns Either we must use normal 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
}
or take the try catch logic outside an IO to the unpure function itself without modyfing any IO
let unpure = function(){
try{
return Right(pure.run());
}catch(e){
return Left(e);
}
}
unpure(); // -> Either
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With