Applicatives 提供了一種強大且富有表現力的方式來處理涉及上下文的函數和資料結構,例如可選值、非同步計算或列表。應用程式擴展了函子的概念,允許將上下文中包裝的函數應用到也包裝在上下文中的值。
applicative 是一種函子,它不僅支援將函數對應到包裝值(如函子),還允許將本身包裝在上下文中的函數應用到包裝在上下文中的值。應用程式提供了一種處理涉及多個函數值的操作的方法。
讓我們探索如何在 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 函數式程式設計簡介:Applicatives #10的詳細內容。更多資訊請關注PHP中文網其他相關文章!