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]), !.

		
Advertisements

3 Comments »

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

    Pingback by The ultimate high productivity programming language is PROLOG (Η πιο παραγωγική Γλώσσα Προγραμματισμού είναι η PROLOG) « OMADEON — October 17, 2008 @ 7:34 am

  2. salut, je veut un programe en swi prolog sur l’anakyse d’un expression bien parenthèsé

    Comment by nina — February 5, 2010 @ 6:30 pm

  3. Very useful, indeed. Thanks a lot for sharing this piece of code with us!

    Comment by chessfarrell — December 11, 2010 @ 2:37 pm


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: