Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prolog - print the value of a variable

I just cannot figure out how to print the value of X. Here is what I tried in the toplevel:

59 ?- read(X).
|: 2.
X = 2.

60 ?- write(X).
_G253
true.

What is _G253? I dont want the index number, I want the value X is bound to. What should I do in order to print the value of X?

like image 256
Doopy Doo Avatar asked Oct 16 '12 20:10

Doopy Doo


People also ask

How do you print the value of a variable in Prolog?

prolog - take as input and print the value of a variable. go:- write('Enter a name'),nl, read(Name),nl, print(Name). print(Name):- write(Name),write(', Hello !!! ').

How do you print text in Prolog?

o “print(x),print(y).” : The 'print' operator allows to use two 'print' predicate together, in this case, we can write the two print predicate together, if we input the value “print(x), print(y).” then it will combine variables from both together as 'xy'. For example: Input: “print(x),print(y).”

How do I print SWI from Prolog?

print(Term) :- write_term(Term, [ portray(true), numbervars(true), quoted(true) ]). The print/1 predicate is used primarily through the ~p escape sequence of format/2, which is commonly used in the recipes used by print_message/2 to emit messages.

What is writeln in Prolog?

writeln( +Term ) Equivalent to write(Term), nl. . The output stream is locked, which implies no output from other threads can appear between the term and newline.


1 Answers

When you type write(X). at the interactive prompt, and nothing else, X is not bound to anything in particular. If you want to read X from the user and then write it, try typing read(X), write(X). at the prompt.

?- read(X), write(X).
|: 28.
28
X = 28.

SWI Prolog does keep a history of top-level bindings; type help. to go into the manual, then search for bindings or just navigate to section 2.8 of the manual, 'Reuse of top-level bindings'. There, you can learn that the most recent value of any variable bound in a successful top-level goal is retained, and can be referred to using the name of the variable, prefixed with a dollar sign. So interactions like the following are possible:

?- read(X).
|: 42.
X = 42.

?- write($X).
42
true.

But a top-level goal that just happens to use the variable name X will be interpreted as using a fresh variable; to do otherwise would violate the normal semantics of Prolog.

like image 88
C. M. Sperberg-McQueen Avatar answered Oct 02 '22 06:10

C. M. Sperberg-McQueen