애플리케이션은 선택적 값, 비동기 계산 또는 목록과 같이 컨텍스트와 관련된 함수 및 데이터 구조로 작업할 수 있는 강력하고 표현력이 풍부한 방법을 제공합니다. 애플리케이션은 펑터의 개념을 확장하여 컨텍스트에 래핑된 함수를 컨텍스트에 래핑된 값에 적용할 수 있도록 합니다.
애플리케이션은 래핑된 값(예: 펑터)에 대한 함수 매핑을 지원할 뿐만 아니라 컨텍스트에 래핑된 함수 자체를 컨텍스트에 래핑된 값에 적용할 수 있도록 허용하는 펑터 유형입니다. 애플리케이션은 여러 기능 값과 관련된 작업을 처리하는 방법을 제공합니다.
자바스크립트에서 애플리케이션을 구현하고 사용하는 방법을 살펴보겠습니다.
Maybe 유형은 선택적 값을 나타내는 데 자주 사용됩니다. 응용 작업을 지원하도록 Maybe를 확장해 보겠습니다.
class Maybe { constructor(value) { this.value = value; } static of(value) { return new Maybe(value); } map(fn) { return this.value === null || this.value === undefined ? Maybe.of(null) : Maybe.of(fn(this.value)); } ap(maybe) { return this.value === null || this.value === undefined ? Maybe.of(null) : maybe.map(this.value); } } // Usage const add = (a) => (b) => a + b; const maybeAdd = Maybe.of(add); const maybeTwo = Maybe.of(2); const maybeThree = Maybe.of(3); const result = maybeAdd.ap(maybeTwo).ap(maybeThree); console.log(result); // Maybe { value: 5 }
이 예에서 Maybe는 Maybe 컨텍스트에 래핑된 함수를 다른 Maybe 컨텍스트에 래핑된 값에 적용하는 ap 메서드를 구현합니다. 이를 통해 선택적 값과 관련된 연결 작업이 가능합니다.
애플리케이션은 여러 비동기 작업을 결합하거나 여러 선택적 값을 처리하는 등 여러 컨텍스트가 포함된 계산을 처리할 때 특히 유용합니다.
Applicative가 여러 Promise를 결합하는 데 어떻게 도움이 되는지 살펴보겠습니다.
const fetchData = (url) => { return new Promise((resolve) => { setTimeout(() => { resolve(`Data from ${url}`); }, 1000); }); }; const add = (a) => (b) => a + b; const promiseAdd = Promise.resolve(add); const promiseTwo = fetchData('url1').then((data) => parseInt(data.split(' ')[2])); const promiseThree = fetchData('url2').then((data) => parseInt(data.split(' ')[2])); const result = promiseAdd .then((fn) => promiseTwo.then((a) => fn(a))) .then((fn) => promiseThree.then((b) => fn(b))); result.then(console.log); // Output after 2 seconds: NaN (since "from" cannot be parsed as an int)
이 예에서는 적용 패턴을 사용하여 여러 약속을 결합합니다. 이 예에는 구문 분석과 관련된 논리적 문제가 있지만 컨텍스트와 관련된 작업 순서를 지정하는 데 애플리케이션을 사용할 수 있는 방법을 보여줍니다.
애플리케이션은 여러 선택적 값을 결합하는 데에도 유용합니다.
const add = (a) => (b) => a + b; const maybeAdd = Maybe.of(add); const maybeFive = Maybe.of(5); const maybeNull = Maybe.of(null); const result1 = maybeAdd.ap(maybeFive).ap(maybeFive); // Maybe { value: 10 } const result2 = maybeAdd.ap(maybeFive).ap(maybeNull); // Maybe { value: null } console.log(result1); // Maybe { value: 10 } console.log(result2); // Maybe { value: null }
이 예에서는 적용 패턴을 사용하여 여러 Maybe 값을 결합하고 null 존재를 적절하게 처리합니다.
위 내용은 JavaScript의 함수형 프로그래밍 소개: 응용프로그램 #10의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!