Add a generic main function.

This commit is contained in:
2024-12-02 09:46:15 +00:00
parent bc9c30ad5f
commit efdde2441b
4 changed files with 31 additions and 26 deletions

View File

@@ -3,3 +3,20 @@ let distance1 a b = abs (a - b)
let strings_from_file fname =
In_channel.with_open_text fname In_channel.input_lines
let main prep parts =
try
match Sys.argv with
| [| _; fname |] ->
let lines = prep fname in
let do_part i (fmt, fn) =
Printf.printf "Part %d = %s\n" i (fmt (fn lines))
in
List.iteri do_part parts;
exit 0
| _ ->
Printf.printf "Usage: %s <fname>\n" Sys.executable_name;
exit 2
with e ->
Printf.printf "An error occured: %s\n" (Printexc.to_string e);
exit 1

View File

@@ -8,3 +8,11 @@ val distance1 : int -> int -> int
val strings_from_file : string -> string list
(** [strings_from_file fname] returns a list of strings from the file
[fname]. Each string represents a line from the file. *)
val main : (string -> 'a) -> (('b -> string) * ('a -> 'b)) list -> unit
(** [main prep parts] executes an advent of code problem. [prep fname] should
be a function that returns the input from [fname]. Each elemet of
[parts] is a pair of functions. The first converts the output to a string
(for example [string_of_int]). The second executes the given part.
Output is given as if done by:
[print_string ( prep fname |> snd |> fst )] *)