若先有 Function 回傳 Maybe,再根據 Maybe 內的 Value 呼叫 API,就會出現 Maybe Future。
Version
Sanctuary 3.1.0
Fluture 14.0.0
Maybe Future
import { reject, fork, encase } from 'fluture'
import { env as flutureEnv } from 'fluture-sanctuary-types'
import { create, env } from 'sanctuary'
import { error, log } from 'wink-fp'
let { pipe, map, Just, Nothing, add, I, maybe } = create ({ checkTypes: true, env: env.concat (flutureEnv) })
let data = Just (1)
// let data = Nothing
pipe ([
map (add (1)),
map (encase (add (2))),
maybe (reject (0)) (I),
fork (error) (log)
]) (data)
第 8 行
let data = Just (1)
// let data = Nothing
data
為 Maybe。
11 行
pipe ([
map (add (1)),
map (encase (add (2))),
maybe (reject (0)) (I),
fork (error) (log)
]) (data)
使用 pipe
組合 IIFE:
map (add (1))
:將 Maybe 與一般 function 綁定,回傳 Maybemap (encase (add (2)))
:將 Maybe 與回傳 Future 的 function 綁定,回傳 Myabe Futuremaybe (reject (0)) (I)
:從外層開始依序解開 Maybe 與 Future,因此先使用maybe
解開 Maybe,唯接下來會以fork
解開 Future,因此 Nothing 必須以reject (0)
表示,不能只是0
,Sanctuary 會抱怨 type 不對fork (error) (log)
:最後再解開 Future
Conclusion
- 無論是 Future Maybe 或 Maybe Future,拆開的關鍵都是先解 Maybe,最後解 Future,永遠將
fork
放在pipe
內最後一行