F# how to append/join array2D and combine 1D arrays to array2D

前端 未结 3 1823
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-18 08:40

in F#, array.append can join two arrays; is there a way to append 2 array2D objects into one or column-wise join several 1-D arrays into one array2D object?

相关标签:
3条回答
  • 2021-01-18 08:51

    The array2D function will turn any seq<#seq<'T>> into a 'T [,] so it should work for turning a bunch of 1D arrays into a 2D array.

    let arr1 = [| 1; 2; 3 |]
    let arr2 = [| 4; 5; 6 |]
    
    let combined = array2D [| arr1; arr2 |]
    
    0 讨论(0)
  • 2021-01-18 08:51

    I don't think there's anything built-in to handle this. You can define your own reusable method based on either Array2D.init or Array2D.blit, though. If you need to combine several columns into one logical whole, I think it would frequently be more convenient to use an array of arrays rather than a 2D array (and in general, the 1D array operations in .NET are significantly faster than the multi-dimensional array operations).

    0 讨论(0)
  • 2021-01-18 09:09

    As far as I can see, there is no F# library function that would turn several 1D arrays into a single 2D array, but you can write your own function using Array2D.init:

    let joinInto2D (arrays:_[][]) = 
      Array2D.init arrays.Length (arrays.[0].Length) (fun i j ->
        arrays.[i].[j])
    

    It takes an array of arrays, so when you call it, you'll give it an array containing all the arrays you want to join (e.g. [| arr1; arr2 |] to join two arrays). The function concatenates multiple 1D arrays into a single 2D array that contains one row for each input array. It assumes that the length of all the given arrays is the same (it may be a good idea to add a check to verify that, for example using Array.forall). The init function creates an array of the specified dimensions and then calls our lambda function to calculate a value for each element - in the lambda function, we use the row as an index in the array of arrays and the column as an index into the individual array.

    Here is an example showing how to use the function:

    > let arr1 = [| 1; 2; 3 |]
      let arr2 = [| 4; 5; 6 |];;
    
    > joinInto2D [| arr1; arr2 |];;
    val it : int [,] = [[1; 2; 3]
                        [4; 5; 6]]
    

    EDIT: There is already a function to do that - nice! I'll leave the answer here, because it may still be useful, for example if you wanted to join 1D arrays as columns (instead of rows, which is the behavior implemented by array2D.

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