管理功能编程和fp-t中的错误



我对函数式编程非常陌生,尤其是fp-ts

我最近遇到的困难是玩数组,将它们链接到不同的Monad中,同时保留与每一步相关的一些细节。

假设我们有一个

  1. 以字符串形式获取一些数据
  2. 如果可能的话,将该字符串解析为CCD_ 2的数组;类型可以是Option<ITitle[]>
  3. 将它们映射到执行一些异步更新的可能的CCD_ 4的阵列中;类型可以是TaskEither<IError, ITitle>
  4. 打印结果(如果可用(,包括故障及其特定错误
// error definition
enum ErrorType {
NotFound = 'NOT_FOUND',
Timeout = 'TIMEOUT',
ParseFailure = 'PARSE_FAILURE',
UpdateFailure = 'UPDATE_FAILURE',
Unknown = 'UNKNOWN',
}
// our types
interface ITitle {
title: string;
meta: unknown;
}
interface IError {
msg: string;
type: ErrorType;
}
// helper functions
declare function findTitles(): TaskEither<IError, string>;
declare function parseTitles(items: string): Option<ITitle[]>; // or Either<IError, ITitle[]> whatever fits best
declare function updateTitle(title: ITitle): TaskEither<IError, ITitle>;

更新:
我正在用更具体的细节更新问题,问题是:

const program = pipe(
findTitles(),
TE.map(parseTitles), // Now we get TaskEither<IError, Option<ITitle[]>>;
TE.chain(titles =>
// Problem is var titles is still wrapped in Option and this won't work
// What if the titles is Either<IError, ITitle[]>?
// How do we preserve the error if titles is an Either?
array.traverse(taskEither)(titles, title => updateTitle(title))
),
// How to log the result including the errors?
// Or in another word how do we run traverse and fold the Eithers?
)

TE.map(parseTitles)给我们一个TaskEither<IError, Option<ITitle[]>>,问题出现在chain回调中,其中titles仍封装在Option中,这将不起作用

您可以使用fromOption:添加另一个将Option展开到TaskEither中的chain

const program = pipe(
findTitles(),
TE.map(parseTitles), // Now we have TaskEither<IError, Option<ITitle[]>>;
TE.chain(TE.fromOption(() => ErrorType.NotFound)) // Now we have TaskEither<IError, ITitle[]>
TE.chain(titles =>
array.traverse(taskEither)(titles, title => updateTitle(title))
),
)

fromEither:

const program = pipe(
findTitles(),
TE.map(parseTitles), // Now we have TaskEither<IError, Either<IError, ITitle[]>>;
TE.chain(TE.fromEither) // Now we have TaskEither<IError, ITitle[]>
TE.chain(titles =>
array.traverse(taskEither)(titles, title => updateTitle(title))
),
)

最新更新