0

A newbie query

given N a number , I would like to create a variable XN in prolog . N=3,createvar(N,test),write(X3). must produce test as the answer .

Is this possible

Rephrasing the Q

I need some thing similar to length(S,N). which creates a N anoymous variables .

false
  • 10,264
  • 13
  • 101
  • 209
  • I don't know if it's possible or impossible, but [Prolog variables are not the same as other languages](https://stackoverflow.com/a/9026201) and may not make it easy to bind `X3` inside `createvar()` which is also usable outside. (Before you edited your question it suggests a list of values which sum ` – TessellatingHeckler May 10 '21 at 03:47
  • I removed the origial Q because I thought I had whittled the q down to this issue . let me rephrase the q again – Sunil Chandras May 10 '21 at 11:23

1 Answers1

0

Just add a new variable name to your clause. When reading left-to-right, a new variable name indicates a "fresh variable" that is "as yet unbound" / "so far uninstantiated".

No need to declare a variable explicity. They are just names for places selected from an infinite (or at least RAM-sized) sea of places. For example

foo(X) :- bar(X,Y),baz(Y,X).
                ^
                |
                You needed a new variable, you now have it.

A "fresh variable" named Y has been added to the set of variables used in this clause by naming it in the call to bar(X,Y).

In particular, the variable name _ can be used to name fresh variables without inventing new names. Any variable named _ is different from all other variables

X=[_,_,_,_,_].

You created 5 fresh variables by naming them _. Note that X is initially also a fresh variable but then gets unified with the (tip of) the 5-element list.

When printing, SWI Prolog gives uninstantiated variables unique names derived from the position in some internal datastructure:

?- X=[_,_,_,_,_].
X = [_6480,_6486,_6492,_6498,_6504].
David Tonhofer
  • 14,559
  • 5
  • 55
  • 51
  • Thanks This is same as given before. Does not answer the requirement explicitly – Sunil Chandras May 10 '21 at 14:22
  • I think OP is asking about "variable variables" [PHP](https://www.php.net/manual/en/language.variables.variable.php), [Python](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – TessellatingHeckler May 10 '21 at 15:20
  • 1
    @SunilChandras @TessallatingHeckler In that case, there is only [`nb_setval/2`](https://eu.swi-prolog.org/pldoc/doc_for?object=nb_setval/2) and [`b_setval/2`](https://eu.swi-prolog.org/pldoc/doc_for?object=b_setval/2) and friends which **set** thread-local global variables. Use only in special cases! – David Tonhofer May 10 '21 at 15:56