Lists except - filter a seq of string which not equal any item.A of another list

StackOverflow https://stackoverflow.com/questions/21418674

  •  04-10-2022
  •  | 
  •  

Question

I'm trying to create a filter function accept two list parameters and return all the items in the first seq after excluded these existing (equal to A) in the second list.

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
Was it helpful?

Solution 2

I think one thing would be to do

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

OTHER TIPS

The simplest code would be:

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)

Notes:

  • Since the computation only uses R.A, we retrieve these R.A values only once for performance reasons.
  • Converting it to Set would eliminate duplicates as they only degrade performance and not affect the final result.
  • Since the type of except' is inferred as Set<string>, we can use member method except'.Contains instead of Set.contains.

Fluent LINQ implementation:

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

There is now Seq.except:

xs 
|> Seq.except ys
// All xs that are not in ys
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top