2016-12-13 9 views
3

결과 : getFile(filename).map(parseJson).map(doOtherThings)...IO와 선형 흐름을 구현하는 방법과 자바 스크립트를 사용한 함수 프로그래밍에서 펑터를 사용 하시겠습니까?

같은 선형 흐름 내가 Either 자체가 모든 것을 사용하고 좋은 쉽게 다음

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 Monads 내부에서 Eithers를 사용할 때 선형 흐름을 유지하는 방법은 무엇입니까?

함수 프로그래밍에 어떤 패턴이 있습니까? 이것에 대한

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

+0

을 modyfing없이 unpure 함수 자체에 IO 외부 try catch 로직을 –

답변

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 
} 

또는여기 https://github.com/fantasyland/fantasy-land 모습을 가질 수있는 IO

let unpure = function(){ 
    try{ 
    return Right(pure.run()); 
    }catch(e){ 
    return Left(e); 
    } 
} 
unpure(); // -> Either