[英]fp-ts: How to combine multiple Option producers?
I am looking for an fp-ts
function that has this behavior:我正在寻找具有此行为的
fp-ts
function:
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,
])
I was not able to find a corresponding function in the documentation of Option
here .我在
Option
here 的文档中找不到相应的 function 。
I think you are looking for getLastMonoid
within the Option library.我认为您正在 Option 库中寻找
getLastMonoid
。 This will give you the right most some
value as shown in the table below:这将为您提供最正确的
some
值,如下表所示:
x ![]() |
y![]() |
concat(x, y)![]() |
---|---|---|
none![]() |
none![]() |
none![]() |
some(a)![]() |
none![]() |
some(a)![]() |
none![]() |
some(a)![]() |
some(a)![]() |
some(a)![]() |
some(b)![]() |
some(b)![]() |
However, this only helps you for pairs of Option
, in order to apply it to an array of Option
, you will need to rely on the reduceRight
function inside Array .但是,这仅对成对的
Option
有帮助,为了将其应用于Option
数组,您需要依赖Array中的reduceRight
function 。 Similar to the reduce function inside vanilla javascript arrays, it will take an initial value B and pass it through a function f
until it has gone through the entire array. Similar to the reduce function inside vanilla javascript arrays, it will take an initial value B and pass it through a function
f
until it has gone through the entire array.
Putting all this together, your compute function can be replaced with the below:将所有这些放在一起,您的计算 function 可以替换为以下内容:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.