Search code examples
prolog

Prolog, Is it possible to use variable to call clause?


I have the following problem in Prolog. I have rules

foo(L).
boo(L).
doo(L).

which all return a different list, and a rule: bar(X), which returns "foo" or "boo" or "doo" as X. Now I want call the appropriate function by saying something like:

bar(X),
X().

This does not work, is there any similar way to do this? Otherwise I have to add a rapidly increasing amount of code, because I will declare more rules like foo(L) in the future.

Thanks in advance.


Solution

  • In SWI-Prolog there is the =../2 operator which works like: foo(bar) =.. [foo, bar]
    Use this in combination with call/1 and it works. Sometimes the following works as well:

    foo(L).
    boo(L).
    doo(L).
    
    bar(X).
    Goal =.. [X, L].
    Goal.   % If this does not work, use call(Goal).