run a prolog code with swipl in a command line

2.2k views Asked by At

I am searching for swipl the similar feature as perl -e In particular, I want to run prolog code in this fashion:

swipl --wanted-flag "fact(a). message:-writeln('hello')." -g "message" -t halt

This is possible to do with

 swipl -f file -g "message" -t halt

where the prolog clauses are written in file

I am running swipl on the server side that takes user input as prolog clauses, therefore writing a file on the server is not a good idea.

1

There are 1 answers

1
AudioBubble On

One thing you can do is to use load_files/2 with the option stream, and load from standard input, not from an argument (you can still pass the entry point as an argument, I guess):

Say in a file fromstdin.pl you have:

main :-
    load_files(stdin, [stream(user_input)]),
    current_prolog_flag(argv, [Goal|_]),
    call(Goal),
    halt.
main :- halt(1).

and with this you can do:

$ echo 'message :- format("hello~n").' | swipl -q -t main fromstdin.pl -- message
|: hello

The comments by @false to this answer and the question will tell you what this |: is, if you are wondering, but if it annoys you, just do:

$ echo 'message :- format("hello~n").' \
    | swipl -q -t main fromstdin.pl -- message \
    | cat
hello

instead.

This will let you read any Prolog from standard input and call an arbitrary predicate from it. Whether this is a clever thing to do, I don't know. I would also not be surprised if there is a much easier way to achieve the same.