tags:

views:

111

answers:

2

Im running prolog via poplog on unix and was wondering if there was a way to read in multiple words (such as encase it into a string). For instance, read(X) will only allow X to be 1 term. However, if I encase the user input with "", it will return a list of character codes, is this the correct method as I can not find a way to convert it back to a readable string.

I would also like to be able to see if the multiworded string contains a set value (for instance, if it contains "i have been") and am unsure of how i will be able to do this as well.

+1  A: 

read/1 reads one Prolog item from standard input. If you enter a string enclosed in ", it will indeed read that string as one object, which is a list of ASCII or Unicode codepoints:

?- read(X).
|: "I have been programming in Prolog" .
X = [73, 32, 104, 97, 118, 101, 32, 98, 101|...].

Note that period after the string to signify end-of-term. To convert this into an atom (a "readable string"), use atom_codes:

?- read(X), atom_codes(C,X).
|: "I have been programming in Prolog" .
C = 'I have been programming in Prolog'.

Note single quotes, so this in one atom. But then, an atom is atomic (obviously) and thus not searchable. To search, use strings consistently (no atom_codes) and something like:

/* brute-force string search */
substring(Sub,Str) :- prefix_of(Sub,Str).
substring(Sub,[_|Str]) :- substring(Sub,Str).

prefix_of([],_).
prefix_of([X|Pre],[X|Str]) :- prefix_of(Pre,Str).

Then

read(X), substring("Prolog",X)

succeeds, so the string was found.

larsmans
(But in general, stay clear from standard Prolog I/O, it's horrible. Use IPC or embedding so you can write I/O in a language that properly supports it.)
larsmans
A: 

It seems that the most basic and straightforward answer to your question is that you need to enclose your input in single quotes, i.e.:

read('Multiple Words In A Single Atom').

The double quotes, as you said, always convert to ASCII codes.

KenB