F# converting Array2D to array of arrays

后端 未结 2 1876
眼角桃花
眼角桃花 2020-12-21 00:54

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 array

相关标签:
2条回答
  • 2020-12-21 01:20

    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] |]
                |]
    
    0 讨论(0)
  • 2020-12-21 01:30

    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.

    0 讨论(0)
提交回复
热议问题