Array submission in printfn

I am printing a Tic-Tac-Toe board. I have an array of characters for each cell in the board and a format string for the board. I'm doing now:

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 pass an array of printfn cells without explicitly listing all 9 elements in the array? Can I use Array.fold or kprintf in some way?

+5
source share
3 answers

The answer to Funk is pretty good, but I think you can make it simpler by introducing a join function to combine the elements (individual cells or rows) with separators between them and their environment.

 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" 
+5
source

This is far from sexual, but there is a pattern that can be found.

 cells |> Array.toList |> List.chunkBySize 3 |> List.fold (fun acc list -> acc + (list |> List.fold (fun acc char -> acc + sprintf "| %c " char) "") + "|\n.===.===.===.\n") ".===.===.===.\n" |> printf "%s" 
+4
source

Each subsequent use of a function argument leads to a different type. For instance:

 let f1 = printfn "%d %d %d" // f1 : int -> int -> int -> unit let f2 = f1 0 // f2 : int -> int -> unit let f3 = f2 1 // f3 : int -> unit let r = f3 2 // r : unit 

Note that f1 , f2 , f3 and r are of different types. Different types mean that you cannot insert them into a general data structure such as a list or sequence.

(honestly, there is a way around this with method overloads, but this tends to break the compiler and is generally not needed for real applications)

I would choose a different route:

 for i in 0..2 do printf ".===.===.===.\n|" for j in 0..2 do printf "%c |" cells.[i*3+j] printfn "" printfn ".===.===.===." 
+3
source

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


All Articles