支援 chain
的 Object 稱為 Chain,可使用 chain
將 Chain 與回傳 Chain 的 Function 綁定改變 Chain。
Version
Sanctuary 3.1.0
Array
import { compose, of, add, chain } from 'sanctuary'
let data = [1, 2]
let inc = compose (of (Array)) (add (1))
chain (inc) (data) // ?
data
為 Array,inc
為回傳 Array 的 function,可使用 chain
將 Array 與 inc
綁定改變 Array。
chain
Chain m => (a -> m b) -> m a -> m b
將 Chain 與回傳 Chain 的 function 綁定改變 Chain
a -> m b
:回傳 Chain 的 function
m a
:data 為 Chain
m b
:回傳新 Chain
Array 亦是 Chain,因此
chain
也適用
Maybe
Just
import { compose, Just, add, chain } from 'sanctuary'
let data = Just (1)
let inc = compose (Just) (add (1))
chain (inc) (data) // ?
data
為 Maybe,inc
為回傳 Maybe 的 function,可使用 chain
將 Maybe 與 inc
綁定改變 Maybe。
Nothing
import { compose, Just, Nothing, add, chain } from 'sanctuary'
let data = Nothing
let inc = compose (Just) (add (1))
chain (inc) (data) // ?
若 data
為 Nothing,則傳入 chain
的 function 不會執行。
Either
Right
import { compose, Right, add, chain } from 'sanctuary'
let data = Right (1)
let inc = compose (Right) (add (1))
chain (inc) (data) // ?
data
為 Either,inc
為回傳 Either 的 function,可使用 chain
將 Either 與 inc
綁定改變 Either。
Left
import { compose, Left, Right, add, chain } from 'sanctuary'
let data = Left (1)
let inc = compose (Right) (add (1))
chain (inc) (data) // ?
若 data
為 Left,則傳入 chain
的 function 不會執行。
Future
Resolved
import { Future, resolve, fork } from 'fluture'
import { create, env } from 'sanctuary'
import { env as flutureEnv } from 'fluture-sanctuary-types'
import { log, error } from 'wink-fp'
let { pipe, compose, add, chain } = create ({ checkTypes: true, env: env.concat (flutureEnv) })
let data = resolve (1)
let inc = compose (resolve) (add (1))
pipe ([
chain (inc),
fork (error) (log)
]) (data)
data
為 Future,inc
為回傳 Future 的 function,可使用 chain
將 Future 與 inc
綁定改變 Future。
Rejected
import { resolve, reject, fork } from 'fluture'
import { create, env } from 'sanctuary'
import { env as flutureEnv } from 'fluture-sanctuary-types'
import { log, error } from 'wink-fp'
let { pipe, compose, add, chain } = create ({ checkTypes: true, env: env.concat (flutureEnv) })
let data = reject (1)
let inc = compose (resolve) (add (1))
pipe ([
chain (inc),
fork (error) (log)
]) (data)
若 data
為 Rejected,則傳入 chain
的 function 不會執行。
Conclusion
- 支援
chain
的 Object 稱為 Chain chain
為 Monadic Programming 重要 function,在不同語言有不同稱呼,Haskell 稱為bind
,ECMAScript 稱為chain
或flatMap
,C# 則稱為selectMany
,事實上指的是同一個 functionchain
除了能用在 Array 外,也能用在 Maybe、Either 與 Future,因為這些也都是 Chain