Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Array.map on an array of arrays

Tags:

arrays

f#

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!

like image 598
Mathias Avatar asked Jan 16 '23 14:01

Mathias


1 Answers

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

like image 153
John Palmer Avatar answered Jan 24 '23 20:01

John Palmer