Note: I program primarly in Prolog so this example was created for Prolog but useful for most programming languages.
Most programmers are familiar with the practice of debugging by inserting print statements, e.g. format/2 predicate in Prolog, to display variable values or indicate the execution of a code section. However, once the debugging is done, these print statements need to be manually removed. A more effective approach is to convert these statements into a more flexible and useful form, such as disabling them in an optimized build, outputting them only under certain conditions, or logging them to a file.
ChatGPT can convert Prolog code that uses format/2 predicates to utilize SWI-Prolog’s debug/3 predicates.
Prompt
Convert format/2 predicates below to debug/3 predicate, for the debug/3 topic arguement use
http(open)
open_socket(Address, StreamPair, Options) :-
format('http_open: Connecting to ~p ...', [Address]),
tcp_connect(Address, StreamPair, Options),
stream_pair(StreamPair, In, Out),
format('\tok ~p ---> ~p', [In, Out]),
set_stream(In, record_position(false)),
( option(timeout(Timeout), Options)
-> set_stream(In, timeout(Timeout))
; true
).
ChatGPT Completion
Here’s the converted code with the
debug/3
predicate:
open_socket(Address, StreamPair, Options) :-
debug(http(open), 'Connecting to ~p ...', [Address]),
tcp_connect(Address, StreamPair, Options),
stream_pair(StreamPair, In, Out),
debug(http(open), 'ok ~p ---> ~p', [In, Out]),
set_stream(In, record_position(false)),
( option(timeout(Timeout), Options)
-> set_stream(In, timeout(Timeout))
; true
).
In this code, the
debug/3
predicate is used instead of theformat/2
predicate. The first argument ofdebug/3
is the topic, which is set tohttp(open)
in this case. The second argument is the message to be printed, which is the same as the string used in theformat/2
predicate. The third argument is the list of values to be inserted into the message string, which is also the same as the list used in theformat/2
predicate.