在使用fp-ts的函数式编程中,删除Either数组重复项的最佳方法是什么?

这是我的尝试:

import { either as E, pipeable as P } from "fp-ts";
import { flow } from "fp-ts/lib/function";

interface IItem {
  type: "VALID" | "INVALID";
  value: string;
}

// Building some fake data
const buildItem = (value?: string): E.Either<unknown, string> =>
  value != null ? E.right(value) : E.left({ type: "INVALID", value: "" });

// We will always have an array of Either
const items = [
  buildItem("aa"),
  buildItem("ab"),
  buildItem(),
  buildItem("ac"),
  buildItem("ab"),
  buildItem("ac"),
  buildItem(),
  buildItem("aa")
];

const checkList: string[] = [];
export const program = flow(
  () => items,
  x =>
    x.reduce(
      (acc, item) =>
        P.pipe(
          item,
          E.chain(value => {
            if (checkList.indexOf(value) < 0) {
              checkList.push(value);
              return E.right({ type: "VALID", value: value } as IItem);
            }
            return E.left({ type: "INVALID", value: value } as IItem);
          }),
          v => acc.concat(v)
        ),
      [] as E.Either<unknown, IItem>[]
    )
);


Playground link

最佳答案

通常,在fp-ts中,可以使用Array<A>中的uniqfp-ts/lib/Array中删除​​重复项。给定一个Eq<A>和一个Array<A>,它将返回一个Array<A>,其中所有A都是唯一的。

在您的情况下,您似乎要删除Array<Either<IItem, IItem>>。这意味着,要使用uniq,您将需要Eq<Either<IItem, IItem>>的实例。您获得的方法是使用getEq中的fp-ts/lib/Either。它要求您为Eq参数化的每种类型提供一个Either实例,一种用于左例,另一种用于右例。因此,对于Either<E, R>getEq将使用一个Eq<E>和一个Eq<R>并给您一个Eq<Either<E, R>>。在您的情况下,ER是相同的(即IItem),因此您只需使用同一个Eq<IItem>实例两次。

您所需的Eq<IItem>实例很可能如下所示:

// IItem.ts |
//-----------
import { Eq, contramap, getStructEq, eqString } from 'fp-ts/lib/Eq'

export interface IItem {
  type: "VALID" | "INVALID";
  value: string;
}

export const eqIItem: Eq<IItem> = getStructEq({
  type: contramap((t: "VALID" | "INVALID"): string => t)(eqString),
  value: eqString
})


一旦有了它,就可以使用Array<Either<IItem, IItem>>uniq进行重复数据删除,如下所示:

// elsewhere.ts |
//---------------
import { array, either } from 'fp-ts'
import { Either } from 'fp-ts/lib/Either'
import { IItem, eqIItem } from './IItem.ts'

const items: Array<Either<IItem, IItem>> = []

const uniqItems = uniq(either.getEq(eqIItem, eqIItem))(items)


然后,uniqItems常量将是一个Array<Either<IItem, IItem>>,其中两个Either<IItem, IItem>均不等于Eq<Either<IItem, IItem>>定义的“相等”。

关于javascript - 使用fp-ts删除Either数组中的重复项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61300952/

10-10 00:42