简体   繁体   中英

Reading in multiple words for prolog

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.

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 the 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 is 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(Pre, Str) :- append(Pre, _, Str).

Then

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

succeeds, so the string was found.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM