aoc2022/basics.m

77 lines
1.4 KiB
Mathematica
Raw Normal View History

2022-12-01 02:56:19 -05:00
:- module basics.
:- interface.
2022-12-01 17:59:19 -05:00
:- type part ---> one; two.
2022-12-01 02:56:19 -05:00
:- pred part(string, part).
:- mode part(in, out) is semidet.
2022-12-01 13:23:53 -05:00
:- mode part(out, in) is det.
:- import_module io.
:- import_module list.
:- import_module string.
2022-12-05 04:14:29 -05:00
:- type lines == list(string).
2022-12-01 13:23:53 -05:00
:- 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.
2022-12-05 04:14:29 -05:00
:- pred read_lines_need(string::in, lines::out, io::di, io::uo) is det.
2022-12-01 13:23:53 -05:00
2022-12-01 17:59:19 -05:00
:- pred wrap_main(pred(io, io), io, io).
:- mode wrap_main(pred(di, uo) is cc_multi, di, uo) is cc_multi.
:- mode wrap_main(pred(di, uo) is det, di, uo) is cc_multi.
2022-12-01 13:23:53 -05:00
2022-12-03 00:33:45 -05:00
:- import_module char.
:- type chars == list(char).
:- import_module int.
:- func sum(list(int)) = int.
2022-12-01 13:23:53 -05:00
:- import_module maybe.
:- func to_int_may(string) = maybe(int).
2022-12-01 02:56:19 -05:00
:- implementation.
part("1", one).
part("2", two).
2022-12-01 13:23:53 -05:00
:- 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).
2022-12-03 00:33:45 -05:00
sum(Xs) = foldl(plus, Xs, 0).
2022-12-01 13:23:53 -05:00
to_int_may(Str) = Out :-
if to_int(Str, N) then Out = yes(N) else Out = no.