F# converting Array2D to array of arrays

眉间皱痕 提交于 2019-12-18 08:26:16

问题


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.


回答1:


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] |]
            |]



回答2:


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.



来源:https://stackoverflow.com/questions/37842353/f-converting-array2d-to-array-of-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!