I have an array of arrays P, which represents a Matrix, as an array of row vectors (that representation is more convenient for my purposes), and I want to extract the column-vector j of that array. My first pass was:
let column (M: float[][]) (j: int) =
Array.map(fun v -> v.[j]) M
This fails to compile, telling me that v.[j] is using operator expr.[idx] on an object of indeterminate type. This is puzzling to me, because hovering over v recognizes v as a float[], which I believe is a row vector.
Furthermore, the following code works:
let column (M: float[][]) (j: int) =
Array.map(fun v -> v) M
|> Array.map (fun v -> v.[j])
I fail to understand how the second example is different from the first one. The first map in the second example looks redundant: I am mapping an array to itself, and yet this seems to resolve the type determination problem.
Any help understanding what I am doing wrong or not seeing would be much appreciated!
The problem is that F# type inference is strictly left to right so that the compiler sees
let column (M: float[][]) (j: int) =
Array.map(fun v -> v.[j])
At this point, it knows absolutely nothing about v
so it throws an error. This is why the forward pipe operator |>
is so common - rewriting your code as
let column (M: float[][]) (j: int) =
M |> Array.map(fun v -> v.[j])
Is fine. This is also why your second example works
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With