Search code examples
prologquote

.how to write single quote( ' ) in write predicate in Prolog?


I want to add short info in the beginning of the program and i goes like this

message :-
    nl,nl,
    write('  To start type  '), nl,
    write(' ?- solve(Input1,Input2,Output3) '), nl.
:- message.

And this is fine...but i need write(' ?- solve('Input1','Input2',Output3) '), nl so when i run the program it should print To start type ?- solve(' Input1 ' ,' Input2 ' ,Output3 )

thanks in advance :)


Solution

  • Escape the quote with backslash.

    For example, to output a single single-quote:

    ?- write('\'').
    '
    true.
    

    As a general rule, you should of course avoid side-effects entirely. A good solution is to describe the output using a DCG. This makes it amenable to test cases, which are hard to write if output only appears on the terminal.

    write/1 is particularly rarely used. If you really need to output something, use format/2. This sounds scary if you know DOS, but it really isn't.

    An important advantage of format/2 is that it lets you conveniently mesh static text with flexible arguments, for example:

    ?- member(X, [friend,foe,love]),
       format("hello my '~q'!\n", [X]),
       false.
    

    Yielding:

    hello my 'friend'!
    hello my 'foe'!
    hello my 'love'!
    

    Note that the issue of single quotes didn't even arise in this case. The analogous issue with " can again be solved by using \:

    ?- format("a \"test\"", []).
    a "test"