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?

1

2 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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest