In order to learn a bit more of Prolog, I implemented the echo command for SWI-Prolog.

I want a correct implementation, that is, it satisfies the following requirements:

  • It makes only one I/O call so that messages will not be garbled if multiple processes write to the same file.
  • If it is called without arguments, it just prints an empty line (newline).
  • It does not print any additional spaces. Only spaces between the arguments. No leading space. No trailing space.

Here's the Prolog code that I came up with.

main(Argv) :-
    echo('', Argv).

echo(S, []) :-
    string_concat(S, '\n', S1),
echo(S, [Last]) :-
    string_concat(S, Last, S1),
    echo(S1, []).
echo(S, [H|T]) :-
    string_concat(S, H, S1),
    string_concat(S1, ' ', S2),
    echo(S2, T).

I compile and test with the following Makefile (GNU make on Linux):


.PHONY: all
all: echo

%: %.pl
    swipl -q -t main -o $@ -c $^

.PHONY: clean
    $(RM) echo

.PHONY: test
test:: echo
    diff (</bin/echo) <(./echo)
    diff (</bin/echo foo) <(./echo foo)
    diff (</bin/echo foo bar) <(./echo foo bar)

It can be run like this: ./echo foo bar.


1 Answer 1


Please consider using format/2 for formatting output.

You do not need so many concatenations!

Also, check out the following sample query and interaction:

?- main([test]).
true ;
true ;

This shows that internally, there are choice-points left, and in fact even alternative solutions.

Ideally, the predicate should be deterministic, i.e., succeed exactly once.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.