Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

f# Finding the difference between 2 obj[]lists

Tags:

arrays

list

f#

I have 2 obj[]lists list1 and list2. List1 has a length of 8 and list2 has a length of 10. There are arrays in list1 that only exist in list1. That also goes the same for list2. But there are array that exist in both. I'm wondering how to get the arrays that exist in list1. At the moment when I run my code I get a list of the arrays that exist in both lists, but it's missing the data unique to list1. I'm wondering how to get that unique list1 data. Any suggestions?

let getProdOnly (index:int)(list1:obj[]list)(list2:obj[]list) =
    let mutable list3 = list.Empty
    for i = 0 to list1.Length-1 do
        for j = 0 to list2.Length-1 do
            if list1.Item(i).GetValue(index).Equals(list2.Item(j).GetValue(index)) then
                System.Diagnostics.Debug.WriteLine("Exists in List 1 and 2")
            else
                list3 <- list1.Item(i)
like image 571
Mark Avatar asked Dec 19 '22 12:12

Mark


1 Answers

Something like this:

let ar1 = [|1;2;3|]
let ar2 = [|2;3;4|]
let s1 = ar1 |> Set.ofArray
let s2 = ar2 |> Set.ofArray
Set.difference s1 s2
//val it : Set<int> = set [1]

There are also a bunch of Array related functions, like compareWith, distinct, exists if you want to work with Arrays directly.

But as was pointed out in previous answers, this type of imperative code is not very idiomatic. Try to avoid mutable variables, try to avoid loops. It could probably rewritten with Array.map for example.

like image 124
s952163 Avatar answered Jan 02 '23 09:01

s952163