aoc2022/basics.m
2022-12-01 19:23:53 +01:00

62 lines
1.2 KiB
Mathematica

:- module basics.
:- interface.
:- type part ---> one; two.
:- pred part(string, part).
:- mode part(in, out) is semidet.
:- mode part(out, in) is det.
:- import_module io.
:- import_module list.
:- import_module string.
:- pred die(string::in) is erroneous.
:- pred die(string::in, list(poly_type)::in) is erroneous.
:- pred need(io.res(T)::in, T::out) is det.
:- pred read_lines_need(string::in, list(string)::out, io::di, io::uo) is det.
:- type main == (pred(io, io)).
:- inst main == (pred(di, uo) is det).
:- pred wrap_main(main::in(main), io::di, io::uo) is cc_multi.
:- import_module maybe.
:- func to_int_may(string) = maybe(int).
:- implementation.
part("1", one).
part("2", two).
:- import_module exception.
:- type die ---> death(string).
die(Str) :- throw(death(Str)).
die(Fmt, Args) :- die(format(Fmt, Args)).
wrap_main(Main, !IO) :-
try [io(!IO)] Main(!IO)
then true
catch death(Err) -> (
format("%s\n", [s(Err)], !IO),
set_exit_status(1, !IO)
).
need(ok(X), X).
need(error(E), _) :- die(error_message(E)).
read_lines_need(File, Lines, !IO) :-
read_named_file_as_lines(File, Res, !IO),
need(Res, Lines).
to_int_may(Str) = Out :-
if to_int(Str, N) then Out = yes(N) else Out = no.