Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print an array of arrays?

I'm getting stuck printing an array of array although I have checked the previous answer on how to print an array. I can't wrap my head around the functional way to do this in OCaml.

Ocaml: printing out elements in an array of int lists

Suppose I have an array of array. How do I simply print this array?

mutable ch               : t array array;
like image 416
oldselflearner1959 Avatar asked Jan 23 '26 10:01

oldselflearner1959


2 Answers

Another way to print an array is to use the Format module for pretty printing coupled to the Fmt library that provides combinator for defining printing functions:

For instance, if you have an array of array of integers:

let a = [| [|1; 2|]; [|3;4|] |]

We can define a printer for such values with

let int_array_array_printer = let open Fmt in
  array (array int)

Then we can print the array using the Format module:

;; Format.printf "@[<v>%a@]@."
   int_array_array_printer a

In the format string @[<v>%a@]@., the different elements can be decomposed into

  • @[<v> open a vertical box and thus print a newline between each elements
  • %a: the next element will use its own pretty printing function
  • @] close the vertical box
  • @. flush the buffer and add a new line.
like image 93
octachron Avatar answered Jan 26 '26 00:01

octachron


let ch = [| [|"a"; "b"|]; [|"c"|] |]
let () = ch |> Array.iter (Array.iter print_endline)

This uses partial function application to keep it short. If we unwrap it a bit:

let () = ch |> Array.iter (fun xs -> xs |> Array.iter (fun x -> print_endline x))
like image 24
glennsl Avatar answered Jan 25 '26 23:01

glennsl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!