codelidoo
codelidoo

Reputation: 219

Prolog get string input from users and avoiding program termination in case of faulty input

I'm trying to write a simple shell in prolog. I currently query the user for input using read/1.

However I have two issues I would like to resolve.

1) user can only enter terms.

the query requires the user to enter a term and requires the input to end with a period. This is to restricting as I wish the user to be able to enter commands like 'set Variable to Value' (I will parse this string). Is there any way to read such strings in prolog? (if possible without any overhead, such as list respresentation, quotes or an ending period?)

2) if the user enters something incorrect (such as a space), I get a syntax error and the shell ends. What is a quick and proper way to handle these errors and avoid program termination?

All help is most appreciated!

Upvotes: 0

Views: 1859

Answers (2)

Giulio Piancastelli
Giulio Piancastelli

Reputation: 15807

Reading input is not restricted to terms, but can be performed on a per character or per byte basis by means of get_char/1 and get_byte/1. Not exactly compelling, not even that easy to work with. As an example, you may take a look at a small snippet from The Art of Prolog where the authors define a predicate to read a list of words from standard input (definitions for some specific procedures are missing, i.e. to be provided by the reader on the basis of his needs).

Prolog supports error handling by means of catch/3, which you may use to catch errors sprouted during the reading operations and react properly.

Upvotes: 2

CapelliC
CapelliC

Reputation: 60034

The best 'tool' available: DCG. For instance, using SWI-Prolog:

:- [library(http/dcg_basics),
    library(dialect/sicstus)
   ].


myshell :-
  read_line(L),
  phrase(command(C), L).

command(set(Variable, Value)) -->
  "set ", string(Variable), " to ", string(Value).

Upvotes: 3

Related Questions