prolog passing a function as a variable, how to add arguments?

Ihmahr picture Ihmahr · May 12, 2012 · Viewed 8.5k times · Source

I have this arbitrary function that I need to call many times with different variables. btw, this is SWI-Prolog

perform(V1,V2,V3,Function,Result):-
    % 
    % do little stuf.
    %
    Function(Arg1,Arg2,Result).

This gives a syntax error.

But passing a function as a variable without adding arguments works fine as in the following code:

perform(Function):-
    Function.

sayHello:-
    write('hello').

:-perform(sayHello).

So how to add arguments to a variable function?

Answer

Alexander Serebrenik picture Alexander Serebrenik · May 12, 2012

Specifically in SWI-Prolog you can use call . Quoting the manual:

call(:Goal, +ExtraArg1, ...)

Append ExtraArg1, ExtraArg2, ... to the argument list of Goal and call the result. For example, call(plus(1), 2, X) will call plus(1, 2, X), binding X to 3. The call/[2..] construct is handled by the compiler. The predicates call/[2-8] are defined as real (meta-)predicates and are available to inspection through current_predicate/1, predicate_property/2, etc. Higher arities are handled by the compiler and runtime system, but the predicates are not accessible for inspection.

where the plus indicates that the argument must be fully instantiated to a term that satisfies the required argument type, and the colon indicates that the agument is a meta-argument (this also implies "+").