将IO映射到fp-t中的任一的数组



有人能帮我弄清楚如何在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并继续使用TaskTaskEither

TypeScript错误为Type 'Either<Error, string[]>' is not assignable to type '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)))),
);

如果你想"正确"地执行,那么你需要将所有非确定性(非纯(函数调用封装在IO或IOErther中(取决于它们是否会失败(。

因此,首先让我们定义哪些函数调用是"纯"的,哪些不是。我发现最容易想到的是这样的——如果函数ALWAYS为相同的输入提供相同的输出,并且没有引起任何可观察到的副作用,那么它是纯的。

"相同输出"并不意味着引用平等,它意味着结构/行为平等。因此,如果你的函数返回另一个函数,这个返回的函数可能不是同一个函数对象,但它的行为必须相同(原始函数被认为是纯函数(。

因此,在这些术语中,以下是正确的:

  • 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))

需要注意的一点是,这里我们将非纯函数(包装版本中的.attrattrIO(应用于元素数组。如果我们只是在数组上映射attrIO,我们会得到Array<IO<result>>,但它不是非常有用,我们需要IO<Array<result>>。为了实现这一点,我们需要traverse而不是maphttps://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,该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。在这里,最常见的做法是在获得第一个丢失的属性时返回Error,如果所有值都没有错误,则返回一个值数组。因此,如果存在任何错误,此解决方案将丢失有关正确值的信息,并且将丢失除第一个错误之外的所有错误的信息
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。如果有错误,这个会聚合错误,如果没有错误,则聚合值。如果出现任何错误,此解决方案将丢失有关正确值的信息

这种方法在实践中比上述方法更为罕见,而且实现起来更为棘手。一个常见的用例是验证检查,为此有一个monad转换器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))
);
}

最新更新