Gonzalo Garcia
Gonzalo Garcia

Reputation: 25

How to know if two arrays have at least one equal element (f#)

I have a question about compare Arrays. I have two arrays:

   let A = [|1;2;3;4;5|]
   let B = [|2;7|]

I want to now if they have at least one equal element. If they have return True. I try with a function like this:

   let exists = Array.exists2 (fun elem1 elem2 -> elem1 = elem2)
   exists A B

In this case should return true. But it have a problem because it's only work when the arrays have the same length. How could do a function that works with differents lengths?

Upvotes: 1

Views: 210

Answers (3)

desco
desco

Reputation: 16782

let exists a b = Array.exists (Set.ofArray a).Contains b

Upvotes: 2

Petr
Petr

Reputation: 4280

It could be simpler:

let exists a b = (Set.ofArray a, Set.ofArray b) ||> Set.intersect |> (<>) Set.empty

Upvotes: 4

John Palmer
John Palmer

Reputation: 25516

One way would be to calculate the intersection of the two sets

let aset,bset = Set.ofArray A, set.ofArray B
Set.Intersect aset,bset |> Set.toSeq |> Seq.length |> function |0 -> false _ -> true

Upvotes: 0

Related Questions