In F# is there a concise way of converting a float[,] to float[][]? In case this seems like a stupid thing to do it is so I can use Array.zip on the resulting array of arrays. Any help greatly appreciated.
This should do the trick:
module Array2D =
let toJagged<'a> (arr: 'a[,]) : 'a [][] =
[| for x in 0 .. Array2D.length1 arr - 1 do
yield [| for y in 0 .. Array2D.length2 arr - 1 -> arr.[x, y] |]
|]
Keep in mind that Array2D
can have a base other than zero. For every dimension, we can utilize an initializing function taking its base and length. This may be a locally scoped operator:
let toArray arr =
let ($) (bas, len) f = Array.init len ((+) bas >> f)
(Array2D.base1 arr, Array2D.length1 arr) $ fun x ->
(Array2D.base2 arr, Array2D.length2 arr) $ fun y ->
arr.[x, y]
// val toArray : arr:'a [,] -> 'a [] []
I fail to see how to generalize for a subsequent application of Array.zip
, since that would imply a length of 2 in one dimension.
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