【问题标题】:fp-ts: How to combine multiple Option producers?fp-ts:如何组合多个 Option 生产者?
【发布时间】:2023-03-10 10:41:01
【问题描述】:

我正在寻找具有此行为的 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

【问题讨论】:

    标签: typescript fp-ts


    【解决方案1】:

    我认为您正在 Option 库中寻找 getLastMonoid。这将为您提供最正确的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)

    但是,这仅对 Option 对有帮助,为了将其应用于 Option 数组,您需要依赖 Array 中的 reduceRight 函数。类似于 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)
    

    【讨论】:

      猜你喜欢
      • 2021-12-10
      • 2022-01-07
      • 2023-02-01
      • 1970-01-01
      • 2021-12-04
      • 2021-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多