How to run SWI-Prolog from the command line?

ISO directive: initialization. This should work. :- initialization main. main :- write(‘Hello World\n’). edit sorry, I skipped over most interesting details. Here is a sample script, let’s say saved in ~/test/main.pl #!/home/carlo/bin/swipl -f -q :- initialization main. main :- current_prolog_flag(argv, Argv), format(‘Hello World, argv:~w\n’, [Argv]), halt(0). and made executable with chmod +x ~/test/main.pl then I … Read more

Prolog append with cut operator

It sometimes really makes sense to introduce green cuts — even into append/3, but care must be taken that such a cut remains a green cut. That is, a cut that does improve efficiency (on a certain level) and does not affect answers. There is a very simple rule-of-thumb for introducing green cuts: If you … Read more

Should I avoid tail recursion in Prolog and in general?

Short answer: Tail recursion is desirable, but don’t over-emphasize it. Your original program is as tail recursive as you can get in Prolog. But there are more important issues: Correctness and termination. In fact, many implementations are more than willing to sacrifice tail-recursiveness for other properties they consider more important. For example steadfastness. But your … Read more

Prolog: First duplicate value

Here is a pure version using dif/2 which implements sound inequality. dif/2 is offered by B-Prolog, YAP-Prolog, SICStus-Prolog and SWI-Prolog. firstdup(E, [E|L]) :- member(E, L). firstdup(E, [N|L]) :- non_member(N, L), firstdup(E, L). member(E, [E|_L]). member(E, [_X|L]) :- member(E, L). non_member(_E, []). non_member(E, [F|Fs]) :- dif(E, F), non_member(E, Fs). The advantages are that it can also … Read more

‘if’ in prolog?

Yes, there is such a control construct in ISO Prolog, called ->. You use it like this: ( condition -> then_clause ; else_clause ) Here is an example that uses a chain of else-if-clauses: ( X < 0 -> writeln(‘X is negative. That’s weird! Failing now.’), fail ; X =:= 0 -> writeln(‘X is zero.’) … Read more

Knowing when to use cut in prolog

TL;DR: Don’t. The cut prunes Prolog’s search tree. That is, given a pure Prolog program without cut and the same program with cuts the only difference is that the program with cuts might spend less time in fruitless branches, and thus is more efficient ; might have fewer answers ; it might also terminate whereas … Read more