typescript - 在 fp-ts 中将 IO 映射到 Either 数组
有人能帮我弄清楚如何在 fp-ts 中做到这一点吗?
const $ = cheerio.load('some text');
const tests = $('table tr').get()
.map(row => $(row).find('a'))
.map(link => link.attr('data-test') ? link.attr('data-test') : null)
.filter(v => v != null);
我可以用TaskEither完成所有操作,但我不知道如何将它与IO混合使用,或者也许我根本不应该使用IO?
这是到目前为止我想出来的:
const selectr = (a: CheerioStatic): CheerioSelector => (s: any, c?: any, r?: any) => a(s, c, r);
const getElementText = (text: string) => {
return pipe(
IO.of(cheerio.load),
IO.ap(IO.of(text)),
IO.map(selectr),
IO.map(x => x('table tr')),
// ?? don't know what to do here
);
}
更新:
我必须提到并澄清,对我来说最具挑战性的部分是如何将类型从 IO 改为 Either 的数组,然后过滤或忽略 left,并继续使用 Task 或 TaskEither
TypeScript 错误是 类型 'Either<Error, string[]>' 不能赋值给类型 'IO<unknown>'
const getAttr = (attrName: string) => (el: Cheerio): Either<Error, string> => {
const value = el.attr(attrName);
return value ? Either.right(value) : Either.left(new Error('Empty attribute!'));
}
const getTests = (text: string) => {
const $ = cheerio.load(text);
return pipe(
$('table tbody'),
getIO,
// How to go from IO<string> to IOEither<unknown, string[]> or something similar?
// What happens to the array of errors do we keep them or we just change the typings?
IO.chain(rows => A.array.traverse(E.either)(rows, flow($, attrIO('data-test)))),
);
答案#1
如果你想“正确”地做,那么你需要将所有非确定性(非纯)函数调用包装在 IO 或 IOEither 中(取决于它们是否可能失败)。
所以首先让我们定义哪些函数调用是“纯”的,哪些不是。我发现最容易理解的方式是这样的——如果一个函数对于相同的输入总是给出相同的输出,并且不会产生任何可观察的副作用,那么它就是纯函数。
“相同输出”并不意味着引用相等,它意味着结构/行为的相等。因此,如果你的函数返回另一个函数,这个返回的函数可能不是同一个函数对象,但它必须表现得一样(原函数才会被认为是纯函数)。
所以从这些角度来看,以下是正确的:
cherio.load是纯粹的$是纯的.get不是纯的.find不是纯的.attr不是纯的.map是纯的.filter是纯的
现在让我们为所有非纯函数调用创建包装器:
const getIO = selection => IO.of(selection.get())
const findIO = (...args) => selection => IO.of(selection.find(...args))
const attrIO = (...args) => element => IO.of(element.attr(...args))
需要注意的一点是,这里我们在元素数组上应用了非纯函数(以封装版本的 .attr 或 attrIO)。如果我们只是对数组使用 attrIO 映射,我们会得到 Array<IO<result>>,但这并不是非常有用,我们想要的是 IO<Array<result>>。要实现这一点,我们需要使用 traverse 而不是 map https://gcanti.github.io/fp-ts/modules/Traversable.ts.html。
所以如果你有一个数组 rows 并且你想在它上面应用 attrIO,你可以这样做:
import { array } from 'fp-ts/lib/Array';
import { io } from 'fp-ts/lib/IO';
const rows: Array<...> = ...;
// normal map
const mapped: Array<IO<...>> = rows.map(attrIO('data-test'));
// same result as above `mapped`, but in fp-ts way instead of native array map
const mappedFpTs: Array<IO<...>> = array.map(rows, attrIO('data-test'));
// now applying traverse instead of map to "flip" the `IO` with `Array` in the type signature
const result: IO<Array<...>> = array.traverse(io)(rows, attrIO('data-test'));
然后把所有东西组装在一起:
import { array } from 'fp-ts/lib/Array';
import { io } from 'fp-ts/lib/IO';
import { flow } from 'fp-ts/lib/function';
const getIO = selection => IO.of(selection.get())
const findIO = (...args) => selection => IO.of(selection.find(...args))
const attrIO = (...args) => element => IO.of(element.attr(...args))
const getTests = (text: string) => {
const $ = cheerio.load(text);
return pipe(
$('table tr'),
getIO,
IO.chain(rows => array.traverse(io)(rows, flow($, findIO('a')))),
IO.chain(links => array.traverse(io)(links, flow(
attrIO('data-test'),
IO.map(a => a ? a : null)
))),
IO.map(links => links.filter(v => v != null))
);
}
现在 getTests 会给你返回一个 IO,其中包含原始代码中 tests 变量中的相同元素。
免责声明:我还没有通过编译器运行代码,可能存在一些拼写错误或错误。你可能还需要付出一些努力来让它完全强类型化。
编辑:
如果你想保留有关错误的信息(在这种情况下,是某个 a 元素缺少 data-test 属性),你有几种选择可以做到这一点。目前 getTests 返回一个 IO<string[]>。为了在这里适应错误信息,你可以这样做:
IO<Either<Error, string>[]>- 一个返回数组的 IO,每个元素要么是错误,要么是值。要使用它,你仍然需要稍后进行过滤以去除错误。这是最灵活的解决方案,因为你不会丢失任何信息,但它也感觉有点没用,因为在这种情况下Either<Error, string>基本上与string | null相同。
import * as Either from 'fp-ts/lib/Either';
const attrIO = (...args) => element: IO<Either<Error, string>> => IO.of(Either.fromNullable(new Error("not found"))(element.attr(...args) ? element.attr(...args): null));
const getTests = (text: string): IO<Either<Error, string>[]> => {
const $ = cheerio.load(text);
return pipe(
$('table tr'),
getIO,
IO.chain(rows => array.traverse(io)(rows, flow($, findIO('a')))),
IO.chain(links => array.traverse(io)(links, attrIO('data-test')))
);
}
IOEither<Error, string[]>- 一个返回错误或值数组的 IO。在这里,最常见的做法是在遇到第一个缺失属性时返回错误,如果所有值都没有错误则返回值数组。因此,同样地,如果存在任何错误,这种解决方案会丢失正确值的信息,并且除了第一个错误外,还会丢失所有其他错误的信息。
import * as Either from 'fp-ts/lib/Either';
import * as IOEither from 'fp-ts/lib/IOEither';
const { ioEither } = IOEither;
const attrIOEither = (...args) => element: IOEither<Error, string> => IOEither.fromEither(Either.fromNullable(new Error("not found"))(element.attr(...args) ? element.attr(...args): null));
const getTests = (text: string): IOEither<Error, string[]> => {
const $ = cheerio.load(text);
return pipe(
$('table tr'),
getIO,
IO.chain(rows => array.traverse(io)(rows, flow($, findIO('a')))),
IOEither.rightIO, // "lift" IO to IOEither context
IOEither.chain(links => array.traverse(ioEither)(links, attrIOEither('data-test')))
);
}
IOEither<Error[], string[]>- 一个 IO,它返回一个错误数组或者一个值数组。如果存在错误,它会聚合所有错误;如果没有错误,它会聚合所有值。如果存在任何错误,这种解决方案会丢失正确值的信息。
这种方法在实际中比上述方法更少见,而且实现起来更棘手。一种常见的使用场景是验证检查,为此有一个单子转换器 https://gcanti.github.io/fp-ts/modules/ValidationT.ts.html。我对此没有太多经验,所以无法在这个话题上说更多。
IO<{ errors: Error[], values: string[] }>- 一个返回包含错误和数值对象的 IO。这种解决方案也不会丢失任何信息,但实现起来稍微复杂一些。
做这件事的标准方法是为结果对象 { errors: Error[], values: string[] } 定义一个 monoid 实例,然后使用 foldMap 聚合结果:
import { Monoid } from 'fp-ts/lib/Monoid';
type Result = { errors: Error[], values: string[] };
const resultMonoid: Monoid<Result> = {
empty: {
errors: [],
values: []
},
concat(a, b) {
return {
errors: [].concat(a.errors, b.errors),
values: [].concat(a.values, b.values)
};
}
};
const attrIO = (...args) => element: IO<Result> => {
const value = element.attr(...args);
if (value) {
return {
errors: [],
values: [value]
};
} else {
return {
errors: [new Error('not found')],
values: []
};
};
const getTests = (text: string): IO<Result> => {
const $ = cheerio.load(text);
return pipe(
$('table tr'),
getIO,
IO.chain(rows => array.traverse(io)(rows, flow($, findIO('a')))),
IO.chain(links => array.traverse(io)(links, attrIO('data-test'))),
IO.map(results => array.foldMap(resultMonoid)(results, x => x))
);
}
