Convert a tuple array to a 2d array

I'm just wondering if there is a better approach for converting an array of tuples into a two-dimensional array?

let list = [|("a", "1"); ("b", "2"); ("c", "3")|];; let arr = Array2D.init (Array.length list) 2 (fun ij -> if j <> 0 then (fst list.[i]) else (snd list.[i]));; 
+4
source share
2 answers

A more concise way is array2D :

 [|("a", "1"); ("b", "2"); ("c", "3")|] |> Seq.map (fun (x, y) -> [|x; y|]) |> array2D 

But is there a reason why you are not using an array of arrays from the beginning for easy initialization, for example.

 let arr = [|[|"a"; "1"|]; [|"b"; "2"|]; [|"c"; "3"|]|] |> array2D 
+6
source

I agree with @pad that the easiest option is to use the array2D function. I usually prefer to use sequence expressions over higher-order functions (e.g. Seq.map ), so I will probably write:

 let arr = array2D [ for char, num in list -> [ char; num ] ] 

This is essentially the same as the answer from @pad. It creates a list of lists, which is the data structure expected by array2D (it would be more convenient to write external as seq { .. } , but I used lists for simplicity).

+1
source

Source: https://habr.com/ru/post/1482979/


All Articles