繁体   English   中英

使用 fp-ts 删除 Either 数组中的重复项

[英]Remove duplicates in array of Either with fp-ts

使用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>[]
    )
);

游乐场链接

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

在您的情况下,您似乎想要对Array<Either<IItem, IItem>>进行重复数据删除。 这意味着,为了使用uniq ,您将需要一个Eq<Either<IItem, IItem>>的实例。 你得到的方法是使用fp-ts/lib/Either中的getEq 它要求您为您的Either参数化的每种类型提供一个Eq实例,一个用于左侧情况,另一个用于右侧情况。 因此,对于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
})

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

// 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>>定义的“相等”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM