Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# converting Array2D to array of arrays

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.

like image 752
Sid26 Avatar asked Jun 15 '16 17:06

Sid26


2 Answers

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] |]
            |]
like image 131
scrwtp Avatar answered Nov 15 '22 08:11

scrwtp


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.

like image 38
kaefer Avatar answered Nov 15 '22 07:11

kaefer