Intersection Between Two F # Lists

I am looking for a function that intersects two lists and creates a new list, I have this function: let intersect xy = Set.intersect (Set.ofList x) (Set.ofList y) , which do what I ant, but I don’t I want to use any built-in functions in F #

+4
source share
2 answers

It is best to use library material, but if you cannot

If we assume that input lists are sorted (use List.sort or write your own):

 let rec intersect ab = match a with |h::t -> match b with |h2::t2 -> if h=h2 then h::(intersect t t2) else if h>h2 then intersect tb else intersect a t2 |[] -> [] |[] -> [] 
+5
source

I agree that converting lists to sets is not appropriate in this case.

Here is another alternative that works without converting to a set, but uses the built-in Enumerable.Intersect function:

 open System.Linq let intersect (xs:'a seq) (ys: 'a seq) = xs.Intersect(ys) 

You can call this function with FSharpList .

+4
source

All Articles