I am trying to write an efficient algorithm that will effectively let me merge data sets (like a sql join). I think I need to use Array.tryFindIndex, but the syntax has me lost.
Based on the data below, I am calling arrX my “host” array, and want to return an int array that has its length, and tells me the positions of each of its elements in arrY (returning -1 if its not in there). (Once I know these indices I can then use them on arrays of data that of length arrY.length)
let arrX= [|"A";"B";"C";"D";"E";"F"|]
let arrY = [|"E";"A";"C"|];
let desiredIndices = [|1; -1; 2; -1; 0; -1|]
It looks like I need to use an option type somehow, and I think a mapi2 in there as well.
Does anyone know how to get this done? (I think it could be a very useful code snippet for people who are merging data sets from different sources)
Thanks!
//This code does not compile, can't figure out what to do here
let d = Array.tryFindIndex (fun x y -> x = y) arrX
The
tryFindIndexfunction searches for a single element in the array specified as the second argument. The lambda function gets only a single parameter and it should returntrueif the parameter is the element you are looking for. The type signature of thetryFindIndexfunction shows this:(In your example, you’re giving it a function that takes two parameters of type
'a -> 'a -> bool, which is incompatible with the expected type). ThetryFindIndexfunction returns an option type, which means that it gives youNoneif no element matches the predicate, otherwise it gives youSome(idx)containing the index of the found element.To get the desired array of indices, you need to run
tryFindIndexfor every element of the input array (arrX). This can be done using theArray.mapfunction. If you want to get -1 if the element wasn’t found, you can use pattern matching to convertNoneto -1 andSome(idx)toidx:The same thing can be written using sequence expression (instead of
map), which may be more readable:Anyway, if you need to implement a join-like operation, you can do it more simply using sequence expressions. In the following example, I also added some values (in addition to the string keys), so that you can better see how it works:
The sequence expression simply loops over all
arrXelements and for each of them, it loops over allarrYelement. Then it tests whether the keys are the same and if they are, it produces a single element. This isn’t particularly efficient, but in most of the cases, it should work fine.