點燈坊

失くすものさえない今が強くなるチャンスよ

使用 coalesce 將 Future 轉成 Maybe 或 Either

Sam Xiao's Avatar 2021-06-30

若要以 Function Pipeline 同時處理 Resolved 與 Rejected,可使用 coalesce,尤其將 Future 轉成 Maybe 或 Either 時特別好用。

Version

Fluture 14.0.0

coalesce

import { pipe, inc, negate } from 'ramda'
import { reject, resolve, fork, coalesce } from 'fluture'
import { error, log } from 'wink-fp'

let data = resolve (1)
// let data = reject (1)

let f = pipe (
  coalesce (negate) (inc), 
  fork (error) (log)
)

f (data) 

無論 data 為 Resolved 或 Rejected,都希望對其內部值處理,且最後結果都回歸 Resolved,此種需求剛好適合 coalesce

coalesce
(a -> c) -> (b -> c) -> Future a b -> Future d c
提供兩 function 同時處理 Rejected 與 Resolved

a -> c:傳入處理 Rejected 的 function

b -> c:傳入處理 Resolved 的 function

Future a b:data 為 Future

Future d c:無論 data 為 Rejected 或 Resolved,最後都回傳 Resolved

coalesce000

Maybe

import { pipe } from 'ramda'
import { Just, Nothing, K } from 'sanctuary'
import { reject, resolve, fork, coalesce } from 'fluture'
import { error, log } from 'wink-fp'

let data = resolve (1)
// let data = reject (1)

let f = pipe (
  coalesce (K (Nothing)) (Just), 
  fork (error) (log)
)

f (data) 

coalesce 常用來將 Future 轉成 Maybe :

  • K (Nothing):將 Rejected 轉成 Nothing
  • Just:將 Resolved 轉成 Just

coalesce001

Either

import { pipe } from 'ramda'
import { Left, Right } from 'sanctuary'
import { reject, resolve, fork, coalesce } from 'fluture'
import { error, log } from 'wink-fp'

let data = resolve (1)
// let data = reject (1)

let f = pipe (
  coalesce (Left) (Right), 
  fork (error) (log)
)

f (data) 

coalesce 常用來將 Future 轉成 Either :

  • Left:將 Rejected 轉成 Left
  • Right:將 Rejected 轉成 Right

coalesce002

Railwind Oriented Programming

coalesce003

coalesce 支援 Railway Oriented Programming,因為傳入一般 function,且同時處理 Rejected 與 Resolved,且回傳 Resolved,因此無論原來是 Rejected Track 或 Resolved Track,最後都會切回 Resolved Track。

Conclusion

  • coalesce 平常較少使用,但若想將 Future 轉成 Maybe 或 Either 則相當好用

Reference

Aldwin Vlasbolm, Functional Alternative to Promises
Fluture, coalesce