简体   繁体   English

fp-ts:选项<t> [] 到选项<t[]>带映射步骤</t[]></t>

[英]fp-ts: Option<T>[] to Option<T[]> with mapping step

I'm wondering if there is a more concise and efficient way to achieve the following code:我想知道是否有更简洁有效的方法来实现以下代码:

import { pipe } from 'fp-ts/function'
import * as A from 'fp-ts/Array'
import * as E from 'fp-ts/Option'

pipe(
  O.some(['foo', 'bar', 'baz']), // O.Option<string[]>
  O.map(A.map(mapFn)), // O.Option<Array<O.Option<string>>>
  O.chain(A.sequence(O.Applicative)), // O.Option<Array<string>>
)

Perhaps the root enclosing Option is detracting from the main point, but I'm basically trying to achieve the following transformation T[] -> Option<T[]> through mapping with mapFn which does T -> Option<T> .也许根包围Option偏离了要点,但我基本上是试图通过mapFn T[] -> Option<T[]>来实现以下转换 T- T -> Option<T>

I would be happy with this working example, although I can't help but notice that the A.map step completes entirely before the A.sequence step.我会对这个工作示例感到满意,尽管我不禁注意到A.map步骤完全在A.sequence步骤之前完成。 If I could combine these two steps, then as soon as an element is mapped to O.None it would break (and not map the following elements unnecessarily).如果我可以将这两个步骤结合起来,那么一旦一个元素映射到O.None它就会中断(而不是 map 不必要的以下元素)。

While writing this question, I discovered the traverseArray utility function which exists on Option and Either .在写这个问题时,我发现了OptionEither上存在的traverseArray实用程序 function 。

Now I'm able to perform the following and achieve the improved efficiency I mentioned at the end of the question.现在我能够执行以下操作并实现我在问题末尾提到的提高效率。 Whenever an element is mapped to a None , then traversal ends and passes a None to the next stage in the pipe.每当一个元素映射到None时,遍历结束并将None传递到 pipe 中的下一个阶段。

pipe(
  O.some(['foo', 'bar', 'baz']), // O.Option<string[]>,
  O.chain(O.traverseArray(mapFn)), // O.Option<string[]>,
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM