【发布时间】:2021-12-04 01:41:13
【问题描述】:
我有以下pipe
pipe(
getProduct(), //step 1
chain((it) => E.right(Object.assign({}, it, { tax: 0.1 }))), //step 2
chain((it) => E.right(Object.assign({}, it, { delivery: 0.15 }))), //step 3
//chain((it) => E.left('ERROR')), //step 4
E.fold( //final step
(e) => {
console.log(`error: ${e}`)
},
(it) => {
console.log(
`ok ${it.count} ${it.pricePerItem} ${it.tax} ${it.delivery}`
)
}
)
)
在哪里
getProduct = () => E.right({ count: 10, pricePerItem: 5 })
第 1 步产生输出 { count: 10, pricePerItem: 5 }
步骤 2 将步骤 1 的输出作为输入并产生输出{ count: 10, pricePerItem: 5, tax: 0.1 }
步骤 3 获取步骤 2 的输出 { count: 10, pricePerItem: 5, tax: 0.1 } 并产生输出 { count: 10, pricePerItem: 5, tax: 0.1, delivery: 0.15 }
第 4 步只是一个占位符,它可能会生成 left 以指示错误情况。我只是忽略了它。
它在pipe 中按预期工作。但我不想那样。
我希望第 2 步接受输入 { count: 10, pricePerItem: 5 } 并将 tax 添加到其中。同时,我希望第 3 步采用相同的输入 { count: 10, pricePerItem: 5 } 并将 delivery 添加到其中。
然后我希望第 4 步获取第 2 步和第 3 步的输出并将它们合并回来。
我在bind 和/或do notation 中看到了一些相关内容,例如在此answer 中,但不太确定。
那么与始终在管道中运行相比,流如何分支和合并?
更新 命令式编程中的等价物如下:
const products = getProducts()
const productsWithTax = getProductsWithTax(products)
const productsWithDelivery = getProductsWithDelivery(products)
const productsWithTaxAndDelivery = getWithTaxAndDelivery(productsWithTax, productsWithDelivery)
重点是我不想要true 管道。
【问题讨论】:
-
而您期望在单线程环境中并行执行...如何?
-
不,不是并行执行。请参阅我的更新以获取命令式编程中的等效项
标签: functional-programming fp-ts