post-cover
Creating an OCaml Library
First library for any language!
Written Thu Jul 27 2023
By Michael Freno
36 Hits
Creating an OCaml Library
First library for any language!

So I've never made a library before...

So I started very simple, and focused on solving a rough edge while learning OCaml. Learning a new language I often am running through Advent of Code, and while doing so I need to print various data structures to the terminal and was frustrated by how difficult it was in OCaml when printing anything more complex than a primitive, using the Format Module. This is pretty rough if you just want something quick and dirty. It was doable for Advent of Code, but then I then started 99 problems and that was not so great as I was running through problems very quickly and just needed an output.

Doing the following:

  let int_list_to_str ?(prefix = "") list =
    let s = prefix ^ String.concat "; " (List.map string_of_int list) in
    Printf.sprintf "[%s]" s
  in

Just to print out int list was rough, so I created a library real quick.

It was actually not that bad. The programming side likely took less than half the time, with the majority of the time figuring out an Open SSL install error, setting up SSH keys and documenting the code (thankfully that wasn't too bad with the help of ChatGPT). Anyway, the more complicated data printing is probably more useful, so here is the code for printing an Hash table with string keys and float list as values

let hashtable_string_float_list ?(prefix = "") ?(precision = 2) ht =
  let float_list_to_str ?(prefix = "") ?(precision = 2) list =
    let float_to_str f = Printf.sprintf "%.*f" precision f in
    let s = prefix ^ String.concat "; " (List.map float_to_str list) in
    Printf.sprintf "[%s]" s
  in
  print_string (prefix ^ "{");
  Hashtbl.iter
    (fun k v ->
      let float_list = float_list_to_str ~precision v in
      Printf.printf "(%s, %s); " k float_list)
    ht;
  print_endline "}"

And this code would be called like this:

Quick_print.hashtable_string_float_list ~prefix:"MyHashTable: " ~precision:2 hash_table in
(* output = MyHashTable: {(excuse me, [4.99; 5.88; 6.77]); (sir, [7.10; 8.01; 9.00]); (this is a wendy's, [1.12; 2.12; 3.23]); } *)

Each function is named by its type left -> right. They all have an optional parameter (prefix) to print inline before the data structure. Floats also have an optional precision parameter to specify the number of digits trailing the decimal, which defaults to 2.

It's simple, trades customization for ease of use, so mainly useful for testing and learning purposes. I mainly made this library for myself, for future debugging and learning sessions, but hopefully someone somewhere gets some use out of it! The library can be found here.

Comments
No Comments Yet