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.

asked Nov 28, 2017 at 20:36
\$\endgroup\$

1 Answer 1

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.

answered Dec 10, 2017 at 10:07
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.