Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array of tuples into 2d array

Tags:

f#

I just wonder is there a better approach to convert 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 i j -> if j <> 0 then (fst list.[i]) else (snd list.[i]));;
like image 857
wałdis iljuczonok Avatar asked Mar 24 '23 19:03

wałdis iljuczonok


1 Answers

A more concise way is to use array2D:

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

But is there any reason why you don't use an array of arrays from beginning for easy initialization e.g.

let arr =
  [|[|"a"; "1"|]; 
    [|"b"; "2"|]; 
    [|"c"; "3"|]|]
  |> array2D
like image 78
pad Avatar answered Apr 01 '23 19:04

pad