Variable Names in SWI Prolog

前端 未结 1 1892
长情又很酷
长情又很酷 2021-01-18 09:11

I have been using the chr library along with the jpl interface. I have a general inquiry though. I send the constraints from SWI Prolog to an instance of a java class from w

相关标签:
1条回答
  • 2021-01-18 09:42

    (This question has nothing to do with CHR nor is it specific to SWI).

    The variable names you use when writing a Prolog program are discarded completely by the Prolog system. The reason is that this information cannot be used to print variables accurately. There might be several independent instances of that variable. So one would need to add some unique identifier to the variable name. Also, maintaining that information at runtime would incur significant overheads.

    To see this, consider a predicate mylist/1.

    ?- [user].
    |: mylist([]).
    |: mylist([_E|Es]) :- mylist(Es).
    |: % user://2 compiled 0.00 sec, 4 clauses
    true.
    

    Here, we have used the variable _E for each element of the list. The toplevel now prints all those elements with a unique identifier:

    ?- mylist(Fs).
    Fs = [] ;
    Fs = [_G295] ;
    Fs = [_G295, _G298] .
    Fs = [_G295, _G298, _G301] .
    

    The second answer might be printed as Fs = [_E] instead. But what about the third? It cannot be printed as Fs = [_E,_E] since the elements are different variables. So something like Fs = [_E_295,_E_298] is the best we could get. However, this would imply a lot of extra book keeping.

    But there is also another reason, why associating source code variable names with runtime variables would lead to extreme complexities: In different places, that variable might have a different name. Here is an artificial example to illustrate this:

    p1([_A,_B]).
    
    p2([_B,_A]).
    

    And the query:

    ?- p1(L), p2(L).
    L = [_G337, _G340].
    

    What names, would you like, these two elements should have? The first element might have the name _A or _B or maybe even better: _A_or_B. Or, even _Ap1_and_Bp2. For whom will this be a benefit?

    Note that the variable names mentioned in the query at the toplevel are retained:

    ?- Fs = [_,F|_], mylist(Fs).
    Fs = [_G231, F] ;
    Fs = [_G231, F, _G375] ;
    Fs = [_G231, F, _G375, _G378] 
    

    So there is a way to get that information. On how to obtain the names of variables in SWI and YAP while reading a term, please refer to this question.

    0 讨论(0)
提交回复
热议问题