[Functional Programming] Monad

Darcy Daeseok YU ·2024년 11월 25일

Monad : 순수 함수형 프로그래밍에서 Side Effect를 안전하고 체계적으로 처리하기 위한 설계 패턴

*Side Effect : I/O, 상태변경 등의 발생

Monad 형태 or 예시
Javascript Array or Promise

[1, 2].map(a => a + 1).map(a => a - 1).forEach(a => console.log(a); // 1
[].map(a => a + 1).map(a => a - 1).forEach(a => console.log(a); // 2

Promise.resolve(e).then(e => e+1).then(e => e - 1).catch(err => err) 

MOre SPecific of Promise

const fetchNumber = () => Promise.resolve(10);

const double = (x) => {
  if (x < 0) throw new Error("Cannot double a negative number");
  return x * 2;
};

const increment = (x) => x + 1;

const handleError = (error) => console.error("Caught an error:", error);

fetchNumber()
  .then(double)          // Will work fine since 10 > 0
  .then(increment)       // Increment the result
  .then((result) => console.log("Final result:", result)) // Expected: 21
  .catch(handleError);   // Will not be triggered here

// Now simulate an error
Promise.resolve(-5)
  .then(double)          // Throws an error
  .then(increment)       // Skipped due to error
  .then((result) => console.log("Final result:", result)) // Skipped
  .catch(handleError);   // Catches and handles the error

Check the implementation of the Promise instance at the basic level.

코드를 입력하세요
profile
React, React-Native https://darcyu83.netlify.app/

0개의 댓글