How do I run a prolog file from the command line and not drop to the repl?
Asked Answered
D

2

1

I am trying to execute a prolog script from teh command line. I am basing my attempts on what I found at How to run SWI-Prolog from the command line? however that is not working for any non-trivial example (i.e. anything other than that "hello world" example).

:- initialization(main, program).

main :-
    parent(pam,bob).
    parent(tom,bob).
    parent(tom,liz).
    parent(bob,ann).
    parent(bob,pat).
    parent(pat,jim).
    parent(X,jim).
    halt.

I execute this with $ swipl -q -s temp.p and get the following errors

Warning: temp.p:10:
    Singleton variables: [X]
ERROR: temp.p:11:
    No permission to modify static procedure `halt/0'
    Defined at /opt/local/lib/swipl/boot/init.pl:3867

How do I execute this from the command line, get the results, but not drop to the repl?

Degradation answered 14/11, 2019 at 22:51 Comment(0)
A
4

Your biggest problem is that your source code has quite a few issues. I have fixed them like so:

parent(pam,bob).
parent(tom,bob).
parent(tom,liz).
parent(bob,ann).
parent(bob,pat).
parent(pat,jim).

main :-
    parent(X,jim),
    format('~a is the parent of jim~n', [X]),
    halt.

Now that the program does not have errors, you can execute it without returning to the repl by supplying the goal on the command line:

$ swipl -q -s temp.pl -g main
pat is the parent of jim
$
Anamorphosis answered 15/11, 2019 at 16:37 Comment(0)
I
0

To "just run a script" without manually specifying the goal, you can use initialization as in the question, with a few tweaks.

If we create an executable parentage.pl file with the following contents:

#!/usr/bin/env swipl
parent(pam,bob).
parent(tom,bob).
parent(tom,liz).
parent(bob,ann).
parent(bob,pat).
parent(pat,jim).
:- initialization parent(X,jim), writeln(X), halt.

Then we can run it and it outputs the solution, as expected:

# ./parentage.pl 
pat
Indomitable answered 23/3, 2022 at 21:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.