列表除外 - 过滤一串不等于任何item.A的字符串。另一个列表

时间:2014-01-28 22:53:39

标签: f# f#-3.0

我尝试创建过滤器函数接受两个列表参数,并在第二个列表中排除这些现有项(等于A)后返回第一个seq中的所有项目。

type R = { A: string; B: int; ...}
let filter (xxx: seq<string) (except: list<R>) =
    xxx
    |> Seq.filter (fun i ->
        // returns all the items in xxx which not equal to any except.A

4 个答案:

答案 0 :(得分:4)

最简单的代码是:

type R = { A: string; B: int; }
let filter where except =
    let except' = except |> List.map (fun x -> x.A) |> Set.ofList

    where
    |> Seq.filter (not << except'.Contains)

注意:

  • 由于计算仅使用R.A,因此出于性能原因,我们仅检索这些R.A值。
  • 将其转换为Set可以消除重复,因为它们只会降低性能并且不会影响最终结果。
  • 由于except'的类型被推断为Set<string>,我们可以使用成员方法except'.Contains代替Set.contains

答案 1 :(得分:3)

我认为有一件事要做

let filter (xxx: seq<string>) (except: list<R>) =
    xxx
    |> Seq.filter (fun i -> except |> List.exists (fun t -> t.A = i) |> not)

答案 2 :(得分:3)

流畅的LINQ实施:

let filter (where: seq<string>) except =
    let contains = set (where.Except(List.map (fun x -> x.A) except)) in
        where.Where contains.Contains

答案 3 :(得分:0)

现在有Seq.except

xs 
|> Seq.except ys
// All xs that are not in ys