Search code examples
lambdaprologanonymous-functionswi-prolog

Is there something like anonymous predicates in SWI Prolog?


Can I define an anonymous predicate in SWI Prolog, bind it to a variable, and call it later? Something like this:

?- F = {(X, Y) :- Y is 2 * X}, call(F, 2.0, Y).

Solution

  • Alternatively, in SWI-Prolog, you can use library(yall). It can be autoloaded so you don't need to import anything:

    ?- F = [X, Y]>>( Y is 2*X ), call(F, 2.0, Y).
    F = [X, 4.0]>>(4.0 is 2*X),
    Y = 4.0.
    

    I think that in the general case it would be better to use a new variable for the result of calling the lambda:

    ?- F = [X, Y]>>( Y is 2*X ), call(F, 2.0, R).
    F = [X, Y]>>(Y is 2*X),
    R = 4.0.