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.