アプリカティブは、オプションの値、非同期計算、リストなどのコンテキストを伴う関数やデータ構造を操作する強力かつ表現力豊かな方法を提供します。アプリカティブはファンクターの概念を拡張し、コンテキストでラップされた関数を、同様にコンテキストでラップされた値に適用できるようにします。
アプリカティブはファンクターの一種で、ラップされた値に対する関数のマッピング (ファンクターと同様) をサポートするだけでなく、コンテキスト内でラップされている関数自体をコンテキスト内でラップされている値に適用することもできます。アプリカティブは、複数の関数値を含む演算を処理する方法を提供します。
JavaScript でアプリカティブを実装して使用する方法を見てみましょう。
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 は ap メソッドを実装します。このメソッドは、Maybe コンテキストでラップされた関数を、別のMaybe コンテキストでラップされた値に適用します。これにより、オプションの値を含む操作を連鎖させることができます。
アプリカティブは、複数の非同期操作を組み合わせたり、複数のオプションの値を処理したりするなど、複数のコンテキストが関係する計算を扱う場合に特に役立ちます。
アプリカティブが複数の 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)
この例では、適用パターンを使用して複数の Promise を結合します。この例には解析に関する論理的な問題がありますが、アプリカティブを使用してコンテキストに関係する操作をシーケンスする方法を示しています。
アプリカティブは、複数のオプションの値を組み合わせる場合にも役立ちます。
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 中国語 Web サイトの他の関連記事を参照してください。