點燈坊

新しいことを始めるのに、遅すぎる挑戰はない

タグ : Sanctuary

如何解開 Future Either Maybe ?

Future Either Maybe 為常見的 Monad Stack,如呼叫 API 回傳 Future,再使用回傳 Either 的 Function 判斷 API 回傳值,又使用回傳 Maybe 的 Function 運算,就會出現 Future Either Maybe。

使用 Maybe 執行 Side Effect

實務上會遇到若 Argument 存在則執行 Side Effect,否則不執行,傳統會使用 if 判斷 Argument,事實上也可透過 Maybe 自動忽略 nullundefined 不執行 Side Effect。

map 的三種觀點

map 是 FP 最重要 Function,若以不同觀點來思考 map 就會有不同結果:除了本身的 map 外,還可當成 liftcompose 使用。

使用 map 將兩個 Function 綁定

map 是 FP 最具代表性的 Higher Order Function,僅管大部分 FP 原則都沒搞得很懂,但 map 一定都用得很熟;大部分人都將 map 用在 Array,但因為 First Class Function,map 也能將兩個 Function 綁定。

使用 map 提升 Unary Function

一般我們所寫的 Function 都只能處理 ECMAScript 的原生 Type,而無法處理 Maybe、Either、Future 這類 Monadic Type,透過 map 可將普通 Unary Function 提升成能處理 Functor 的 Function。

Fluture 整合 Sanctuary 的 Type Checking

由於 Fluture 遵循 Fantasy Land 規格,因此也可搭配 Sanctuary 使用,但由於 Sanctuary 不認識 Future,因此 Type Checking 會失敗,Fluture 已經提供 fluture-sanctuary-types,可使 Sanctuary 認識 Future。

使用 lift2 提升 Binary Function

一般我們所寫的 Function 都只能處理 ECMAScript 的原生 Type,而無法處理 Maybe、Either、Future 這類 Monadic Type,透過 lift2 可將普通 Binary Function 提升成能處理 Apply 的 Function。

當 Either 遇見 Future

當有 Function 回傳 Either,而後續的 Function 都在 Either 內執行時,卻又有 Function 回傳 Future,這就造成 Either 內有 Future 窘境,實務上該如何處理這種兩層 Monad 呢 ?

當 Maybe 遇見 Future

當有 Function 回傳 Maybe,而後續的 Function 都在 Maybe 內執行時,卻又有 Function 回傳 Future,這就造成 Maybe 內有 Future 窘境,實務上該如何處理這種兩層 Monad 呢 ?

當 Either 遇見 Promise

當有 Function 回傳 Either,而後續的 Function 都在 Either 內執行時,卻又有 Function 回傳 Promise,這就造成 Either 內有 Promise 窘境,實務上該如何處理這種兩層 Monad 呢 ?

當 Maybe 遇見 Promise

當有 Function 回傳 Maybe,而後續的 Function 都在 Maybe 內執行時,卻又有 Function 回傳 Promise,這就造成 Maybe 內有 Promise 的窘境,實務上該如何處理這種兩層 Monad 呢 ?

Maybe 初體驗

Sanctury 與 Ramda 最大的差別是 Ramda 有些 Function 會回傳 undefined,這導致有些 Function 一不小心會造成 Runtime Error,但 Sanctuary 一律回傳 Maybe,讓我們不用處理 undefined 也不會出錯。

Either 初體驗

當 Runtime 出現錯誤且希望執行隨時中斷時,Imperative 會使用 Exception,但 Function Pipeline 並不支援 Exception,需使用 Either 取代。