I'm printing a Tic-Tac-Toe board. I have an array of characters for each cell of the board and a format string for the board. I'm currently doing:
let cells = [| 'X'; 'O'; 'X'; 'O'; 'X'; 'O'; ' '; ' '; ' ' |]
printfn ".===.===.===.\n\
| %c | %c | %c |\n\
.===.===.===.\n\
| %c | %c | %c |\n\
.===.===.===.\n\
| %c | %c | %c |\n\
.===.===.===.\n" cells.[0] cells.[1] cells.[2] cells.[3] cells.[4] cells.[5] cells.[6] cells.[7] cells.[8]
Is there a way to feed the cells array to printfn without explicitly enumerating all 9 items in the array? Could I use Array.fold or kprintf somehow?
Funk's answer is pretty good, but I think you can make it simpler by introducing a join
function to concatenate elements (individual cells or rows) with separators between them and surrounding them.
let join s arr = sprintf "%s%s%s" s (String.concat s arr) s
Then you can do this:
cells
|> Seq.chunkBySize 3
|> Seq.map (Seq.map (sprintf " %c ") >> join "|")
|> Seq.map (fun s -> s + "\n")
|> join ".===.===.===.\n"
|> printfn "%s"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With