Doopy Doo
Doopy Doo

Reputation: 413

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?

Upvotes: 20

Views: 40886

Answers (2)

Mantu
Mantu

Reputation: 149

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 !!!').

Upvotes: 3

C. M. Sperberg-McQueen
C. M. Sperberg-McQueen

Reputation: 25034

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.

Upvotes: 24

Related Questions