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 after Echo in prolog with single print

main(Argv) :-

echo(Argv) :-
    atomic_list_concat(Argv, ' ', A),
    format('~a~n', A).


  • Use format with ~n to print the line separator string of the underlying platform (LF on Unix, CRLF on Windows)
  • Use atomic_list_concat to concatenate all Strings from the command line arguments in one go.



.PHONY: all
all: echo

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

.PHONY: clean
    $(RM) echo

.PHONY: test
test: testEmpty testOne testTwo testWithWhitespace

testEmpty: ARGS:=
testOne: ARGS:=foo
testTwo: ARGS:=foo bar
testWithWhitespace: ARGS:=foo "   bar    " quux " a b  c "

.PHONY: testEmpty testOne testTwo testWithWhitespace
testEmpty testOne testTwo testWithWhitespace: echo
    diff <(echo $(ARGS)) <(./echo $(ARGS))

Anything else that can be improved?


Your Answer

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

Browse other questions tagged or ask your own question.