Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Feeding an array to printfn

Tags:

printf

f#

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?

like image 389
David Sanders Avatar asked Feb 22 '17 17:02

David Sanders


1 Answers

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"
like image 64
kvb Avatar answered Sep 24 '22 04:09

kvb