點燈坊

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

使用 alt 對 Future 執行 || 判斷

Sam Xiao's Avatar 2021-07-01

若想對 Future 執行類似 ECMAScript 的 || 判斷,可使用 alt

Version

Fluture 14.0.0

Resolved Future

import { pipe } from 'ramda'
import { resolve, fork, alt } from 'fluture'
import { error, log } from 'wink-fp'

let data = resolve (1)

let f = pipe (
  alt (resolve (2)),
  fork (error) (log)
)

f (data) 

data 為 Rejected Future 時,則回傳另一個 Future (可為 Rejected Future 或 Resolved Future),否則回傳原 Future,此時可使用 alt 判斷,類似 ECMAScript 的 ||

alt
Alt f => f a -> f a -> f a
若為 Rejected Future,則回傳新 Future,否則回傳原 Future

  • f a:傳入新 Future,可為 Rejected Future 或 Resolved Future
  • f a:data 為 Future
  • f a:回傳新 Future 或原 Future

alt000

Rejected Future

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

let data = reject (1)

let f = pipe (
  alt (resolve (2)),
  fork (error) (log)
)

f (data) 

data 為 Resolved Future,則直接回傳原 Future。

alt001

Railway Oriented Programming

alt002

alt 支援 Railway Oriented Programming,因為傳入可能是 Rejected Future 或 Resolved Future,因此可能切到 Rejected Track 或 Resolved Track。

Conclusion

  • alt 很類似 ECMAScript 的 || operator,但只適用於 Future

Reference

Aldwin Vlasbolm, Functional Alternative to Promises
Fluture, alt