简体   繁体   中英

F# Array.findindex

I am pretty new to F# and am having a few issues debugging some code. The following piece of code creates a matrix which contains positional indices. I have two arrays both contain strings; one array is brought in off a .CSV, the other is hard coded.

indexmatrix= Matrix |> Array.map (fun (j, _) -> load |> Array.findIndex (fun x -> x=j))

I am getting the error of: System.Collections.Generic.KeyNotFoundException, which implies that a match cannot be found, according to F# when I hover over the function. Could the issue be that the values are not stored correctly in the CSV? Or something I am not thinking of?

Thanks

Let's start with a working example:

let Matrix = [| (0,0); (1,0); (2,0)|]
let load = [| 0; 1; 2 |]
let indexMatrix =
  Matrix 
  |> Array.map (fun (j, _) ->
                  load 
                  |> Array.findIndex (fun x -> x = j))

// val indexMatrix : int [] = [|0; 1; 2|]

And break it by removing a required value from load array:

let load = [| 0; 2 |] // missing the corresponding 1
let indexMatrix =
  Matrix 
  |> Array.map (fun (j, _) ->
                  load 
                  |> Array.findIndex (fun x -> x = j))

Which will throw the KeyNotFoundException :

System.Collections.Generic.KeyNotFoundException: Exception of type 'System.Collections.Generic.KeyNotFoundException' was thrown.

Could the issue be that the values are not stored correctly in the CSV?

Possibly, but ultimately what this means is there are tuples in Matrix whose first items have no corresponding values in load , which is why the Array.findIndex call throws. In order for this code to work, load must contain a value equal to the first item in every tuple in Matrix .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM