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.
You can use read for that. For example you could write read(X), animal(X). into the prolog interpreter or write this into a script file: :- read(X), animal(X).
Show activity on this post. /*SWI prolog code*/ string1(progga). string2(ikra). go:- write("Enter your name"), nl, read(X),nl, string1(Y), X=@=Y,nl, write("Matched"); write("not Matched"),go2. /*Another way to*/ go2:- string1(A), string2(B), A=@=B,nl, write("Matched"); write("not Matched").
main :- open('myFile. txt', read, Str), read_file(Str,Lines), close(Str), write(Lines), nl. read_file(Stream,[]) :- at_end_of_stream(Stream). read_file(Stream,[X|L]) :- \+ at_end_of_stream(Stream), read(Stream,X), read_file(Stream,L).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With