Reputation: 4608
Let say I have this two-dimensional array:
let a = Array2D.create 2 2 "*"
What is an idiomatic way to turn that into the following string?
**\n
**\n
My thought would be that I need to iterate over the rows and then map string.concat
over the items in each row. However I can't seem to figure out how to iterate just the rows.
Upvotes: 1
Views: 91
Reputation: 7735
Alternatively, you may use StringBuilder
and involve Array2D.iteri
function:
let data' = [|[|"a"; "b"; "c"|]; [|"d"; "e"; "f"|]|]
let data = Array2D.init 2 3 (fun i j -> data'.[i].[j])
open System.Text
let concatenateArray2D (data:string[,]) =
let sb = new StringBuilder()
data
|> Array2D.iteri (fun row col value ->
(if col=0 && row<>0 then sb.Append "\n" else sb)
.Append value |> ignore
)
sb.ToString()
data |> concatenateArray2D |> printfn "%s"
This prints:
abc
def
Upvotes: 0
Reputation: 243051
I think you'll have to iterate over the rows by hand (Array2D
does not have any handy function for this),
but you can get a row using splicing syntax. To get the row at index row
, you can write array.[row, *]
:
let a = Array2D.create 3 2 "*"
[ for row in 0 .. a.GetLength(0)-1 ->
String.concat "" a.[row,*] ]
|> String.concat "\n"
This creates a list of rows (each turned into a string using the first String.concat
) and then concatenates the rows using the second String.concat
.
Upvotes: 3