fp-ts:如何合并多个 Option 生产者?
fp-ts: How to combine multiple Option producers?
我正在寻找具有这种行为的 fp-ts
函数:
function compute1(arg: number): Option<number>;
function compute2(arg: number): Option<number>;
function compute3(arg: number): Option<number>;
function compute(arg: number): Option<number> {
const first = compute1(arg)
if (isSome(first)) return first
const second = compute2(arg)
if (isSome(second)) return second
const third = compute3(arg)
if (isSome(third)) return third
return none
}
// For example I am looking for this `or` function:
const compute = or([
compute1,
compute2,
compute3,
])
我找不到相应的函数 in the documentation of Option
here。
我认为您正在 Option 库中查找 getLastMonoid
。这将为您提供最正确的 some
值,如下面的 table 所示:
x
y
concat(x, y)
none
none
none
some(a)
none
some(a)
none
some(a)
some(a)
some(a)
some(b)
some(b)
然而,这仅对 Option
对有帮助,为了将其应用于 Option
的数组,您需要依赖 reduceRight
函数 Array。类似于 vanilla javascript 数组中的 reduce 函数,它将采用初始值 B 并将其传递给一个函数 f
,直到它遍历整个数组。
将所有这些放在一起,您的计算函数可以替换为以下内容:
import { getLastMonoid, some, none, Option } from "fp-ts/lib/Option";
import { reduceRight } from "fp-ts/lib/Array";
import { pipe } from "fp-ts/lib/function";
const M = getLastMonoid<number>();
const list = [some(1), some(2), some(3)];
const compute = (list: Option<number>[]): Option<number> =>
pipe(list, reduceRight(none, M.concat));
console.log(compute(list)); // some(3)
我正在寻找具有这种行为的 fp-ts
函数:
function compute1(arg: number): Option<number>;
function compute2(arg: number): Option<number>;
function compute3(arg: number): Option<number>;
function compute(arg: number): Option<number> {
const first = compute1(arg)
if (isSome(first)) return first
const second = compute2(arg)
if (isSome(second)) return second
const third = compute3(arg)
if (isSome(third)) return third
return none
}
// For example I am looking for this `or` function:
const compute = or([
compute1,
compute2,
compute3,
])
我找不到相应的函数 in the documentation of Option
here。
我认为您正在 Option 库中查找 getLastMonoid
。这将为您提供最正确的 some
值,如下面的 table 所示:
x | y | concat(x, y) |
---|---|---|
none | none | none |
some(a) | none | some(a) |
none | some(a) | some(a) |
some(a) | some(b) | some(b) |
然而,这仅对 Option
对有帮助,为了将其应用于 Option
的数组,您需要依赖 reduceRight
函数 Array。类似于 vanilla javascript 数组中的 reduce 函数,它将采用初始值 B 并将其传递给一个函数 f
,直到它遍历整个数组。
将所有这些放在一起,您的计算函数可以替换为以下内容:
import { getLastMonoid, some, none, Option } from "fp-ts/lib/Option";
import { reduceRight } from "fp-ts/lib/Array";
import { pipe } from "fp-ts/lib/function";
const M = getLastMonoid<number>();
const list = [some(1), some(2), some(3)];
const compute = (list: Option<number>[]): Option<number> =>
pipe(list, reduceRight(none, M.concat));
console.log(compute(list)); // some(3)