Gonzalo Garcia
Gonzalo Garcia

Reputation: 25

Compute Union (Set) of arrays while maintaining order

I've spent enough time trying to solve this problem and i could not.
I have this arrays:

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

and I want make the union of these arrays without repeated elements appear

   let C=[|1;2;3;4;5;6;7;8|]

I think with Array.append A B, but I can't remove the repeated elements.

Upvotes: 1

Views: 294

Answers (2)

p.s.w.g
p.s.w.g

Reputation: 149050

Generally, if you want to create a collection only containing distinct elements you probably should consider using a Set instead.

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

let C = Set(A) + Set(B) 
// 1; 2; 3; 4; 5; 6; 7; 8 

Alternatively, using Seq.concat and Seq.distinct will do essentially the same thing, but return a seq:

let C = [ A ; B ] 
        |> Seq.concat 
        |> Seq.distinct

Now with either of these solutions, if you want to turn this back to an array just use Seq.toArray.

Upvotes: 5

desco
desco

Reputation: 16782

let A = [|1;2;3;4;5|]
let B = [|3;4;5;6;7;8|]
let C = Set.ofArray A + Set.ofArray B :> seq<_>

Upvotes: 0

Related Questions