A.I. programming in Prolog and Assembler

September 20, 2007

SWI-Prolog source code: Converting hours-and-minutes to integers (e.g. for use in CLP)

Filed under: CLP, Conversions, Prolog, source code, SWI-Prolog, time-predicates — Omadeon @ 5:31 pm

This short posting is about a useful piece of SWI-Prolog code I keep (re-)using, ever since I wrote it. It is a predicate that converts time (in an EXCEL-compatible format ‘HH:MM’ or ‘HH:MM:SS’) to integers expressing minutes only, e.g. integers suitable for use in CLP applications (Constraints Logic Programming over finite integer domains). I am developing a serious CLP application, during the last few weeks and I regard the following (bi-directional) conversion code as indispensable:

%%% Conversion of Hours-and-minutes to integers and vice-versa (e.g. for CLP problems)
%%% converts number of minutes to a valid time-string e.g. '03:05':
mins2hourmin(MINS,OUTX):- nonvar(MINS), MINS > 0,
    Hours is MINS // 60, Minsx is MINS mod 60,
    num2str2(Hours,S1x), num2str2(Minsx,S2x),
    swritef(OUTX,'%w:%w',[S1x,S2x]), !
    ;
    MINS = 0, OUTX = '00:00', !.
mins2hourmin(HMINx,HRi):- nonvar(HRi),
    sub_atom(HRi,0,2,_,A1x), atom_number(A1x,HOURx),
    sub_atom(HRi,3,2,_,A2x), atom_number(A2x,MINSx),
    HMINx is MINSx + 60*HOURx, !.
mins2hourmin(MINS1,OUTX):- nonvar(MINS1), MINS1 < 0,
    MINS is -MINS1,
    Hours is MINS // 60, Minsx is MINS mod 60,
    num2str2(Hours,S1x), num2str2(Minsx,S2x),
    swritef(OUTX,'-%w:%w',[S1x,S2x]), !.
%% the same predicate operating on Lists of time-entities: 
mins2hourmin_list([],[]):- !.
mins2hourmin_list([M|ML],[X|XL]):- mins2hourmin(M,X), !, mins2hourmin_list(ML,XL).


%%% an auxilliary predicate for mins2hourmin/2:
num2str2(N,Sx):- N >= 10, swritef(Sx,'%w',[N]), !
    ;
    swritef(Sx,'0%w',[N]), !.

	

Blog at WordPress.com.