user11875772
user11875772

Reputation: 1

how to get a program to compile and display in console

I have my own append predicate, and i have made a query for it to append to lists. I keep getting a singleton variable [X] error and its the X variable in my query. how can I fix this so I can print to console?

append1([], List, List).
append1([X | T], List, [X | Y])
:-append1(T, List, Y).

append1([1,2,3], [5,6,7],X).

result should be 123567

Upvotes: 0

Views: 140

Answers (1)

CapelliC
CapelliC

Reputation: 60004

Assuming your program is stored in a Prolog file (usually a file with .pl extension, here append1.pl), you can change the last line to

:- append1([1,2,3],[5,6,7],X), writeln('X'=X).

That is, using a directive, you can force the evaluation, then issue a simple output of result. Running from a bash shell:

$ swipl append1.pl 
X=[1,2,3,5,6,7]
Welcome to SWI-Prolog (threaded, 64 bits, version 8.1.10-28-g8a26a53)
...
?- 

You can then force the interpreter to quit adding another directive :- halt. in append1.pl. Running again:

$ swipl append1.pl 
X=[1,2,3,5,6,7]

Edit

As noted in comment, a better solution from the portability viewpoint should use the ISO standard directive initialization/1. For instance, in append1.pl, replace the last line with

:- initialization((
  append1([1,2,3],[5,6,7],X), writeln('X'=X), halt
)).

Upvotes: 1

Related Questions