2
\$\begingroup\$

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),
    write(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):

SHELL:=/bin/bash

.PHONY: all
all: echo

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

.PHONY: clean
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.

\$\endgroup\$
3
\$\begingroup\$

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]).
test
true ;
test 
true ;
false.

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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