【问题标题】:Replace array element in fp-ts替换 fp-ts 中的数组元素
【发布时间】:2021-10-20 17:57:06
【问题描述】:

我将如何在下面的数组中用dog 替换字符串cat

我下面的示例是标准 js 和 fp-ts 的混合,很好奇 Array 模块中是否有可以解决这个问题的东西。

const animals = ['monkey','cat','lion']

const result = pipe(
    animals,
    A.findIndex((animal)=> animal === 'cat'),
    O.matchW(
      () => animals,
      (index) => //Looking for fp-ts solution here
    )
  )

//Expected Result: ['monkey','dog','lion']

【问题讨论】:

  • 您要仅替换第一个匹配项还是全部替换?
  • @DenisFrezzato 这是为了替换第一次出现

标签: fp-ts


【解决方案1】:

我会使用A.updateAt。请注意,我还包装了O.none 条件结果,因此它们两个条件都返回Option<string[]>

O.matchW(
  () => O.some(animals),
  (index) => A.updateAt(index, 'dog')(animals)
)

【讨论】:

  • Option<Error,string[]> 这是错误的,Option 有一个类型变量。
  • @DenisFrezzato 你完全正确,正确编辑了帖子。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-01
  • 2018-11-06
  • 2017-04-28
  • 1970-01-01
  • 1970-01-01
  • 2021-03-11
  • 2021-11-14
相关资源
最近更新 更多