【发布时间】:2020-07-22 18:45:54
【问题描述】:
我是函数式编程的新手,在数组上运行遍历时遇到了很多困难。
当我阅读 this book 时,似乎我应该能够简单地在 Monad 之间遍历,但我无法用 fp-ts 来围绕这个概念。
有人可以使用array.traverse/sequence 或任何其他方式解释以下内容吗?
- 如何从
TaskEither<Error, string[]>转到TaskEither<Error, Either<Error, string>[]>;或者有没有更好的方法可以在保持输入简单的同时从单个错误变为嵌套错误? - 如何从
TaskEither<Error, Either<Error, string[]>>转到TaskEither<Error, Option<string[]>>或类似的东西;或者我们应该将该函数的结果映射到Either?
请考虑以下简化代码,以便更好地了解我们正在使用这些数组做什么:
// helper functions
declare function toItems(input: string): TaskEither<Error, string[]);
declare function toTitle(item: string): Either<Error, string>;
declare function clean(item: string): Option<string>;
// This is what I tried so far
const program = (input: string) => pipe(
toItems(input), // we have TaskEither<Error, string[]>
TE.map(items => array.traverse(either)(items, toTitle)), // now we have TaskEither<Error, Either<Error, string[]>>
TE.map(items => array.traverse(option)(items, clean)), // nothing works with clean() from here
)
【问题讨论】:
标签: arrays typescript functional-programming monads fp-ts