softbrass
softbrass

Reputation: 45

How do I Prolog specify pair printing format

Pair data is nice to work with, but I found hard to present. I ask how to accomplish printing a set of vectors such that keys & values line up in a pleasantly. Leading zeros in the pair-values, would help. Sample data:

  [1-7,2-43,3-56,4-87,5-110,6-80,7-15]
  [1-1837,2-1873,3-1911,4-1946,5-1975,6-1994,7-2005]

I tried to figure out use of SWI format_predicate ; but couldn't. Then I thought to experiment inline; format('~n~w ~w~w~n', ['Pairs: ',1-246,1-2, ' EOL']).

End result should deal with pairs of the form KK-VVVV:

01-0007 02-0043 03-0056 04-0087 05-0110 06-0080 07-0015 398 People 7 Gens.
01-1837 02-1873 03-1911 04-1946 05-1975 06-1994 07-2005 Spanning 168 Years 

Final Answers:

fpair(A-B) :- format('~`0t~d~2|-~`0t~d~7| ', [A,B])
applist(_,[]). applist(P,[X|L]) :- Q =.. [P,X],call(Q),applist(P,L).    
dojustone(X):- format('~@ ',[fpair(X)]).    
dolist(X):- applist(dolist,X).

Upvotes: 2

Views: 199

Answers (1)

CapelliC
CapelliC

Reputation: 60014

I use a @ specifier for complex formats, it allows to output specific terms. For instance

?- format('~s~n~@~n~@~n~w~n', ['Pairs: ',fpair(1-246),fpair(1-2), '    EOL']).

that is, fpair/1 is an user predicate, called by @, capturing its output.

To get fixed width fields, I use the tab specification, built from two specifiers working together. Finally, to prefix with 0s, I would use

fpair(A-B) :-
    format('~`0t~d~6| ~`0t~d~12|', [A,B]).

Without knowing a priori the maximum number of digits, we must use a guess. I used 6 here.

Upvotes: 2

Related Questions