开发者

Reading in multiple words for prolog

开发者 https://www.devze.com 2022-12-20 05:18 出处:网络
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).

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开发者_如何学C 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, i.e.:

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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消