Search code examples
prologdcg

Replace term with a variable in Prolog


I have a DCG in Prolog that I can query like so:

q(Tree, [name, of, company], []).

and get a response that shows me the path taken to parse the query:

Tree = q(['company (Class)', 'name (Attribute)'])

Now I would like to pose a query such as:

q(Tree, [name, of, acme], []).

and failing to match the term acme, I would like to create a variable Acme so that I get something like:

Acme = company
Tree = q(['company (Class)', 'name (Attribute)'])

I am using SWI-Prolog and am querying it from another language, that is why the query is all lowercase. My other option is creating a lexicon of all the valid terms and replacing all unknows in a query with a variable, but am hoping for a Prolog solution.

Thank you.


Solution

  • Do I understand correctly that you need all prefix-based lists? Would the following work for you:

    1 ?- p([name,of,company],L).
    L = [name, of, company] ;
    L = [name, of|_G456] ;
    L = [name|_G453] ;
    true.
    
    2 ?- p([name,of,department,of,company],M).
    M = [name, of, department, of, company] ;
    M = [name, of, department, of|_G551] ;
    M = [name, of, department|_G548] ;
    M = [name, of|_G545] ;
    M = [name|_G542] ;
    true.
    

    If this is the intended behavior, then the code that implements it can be

    p([],[]).
    p([X|Xs],[X|Ys]) :- p(Xs,Ys).
    p([_|_],_).