Search code examples
prolog

Assigning a variable to a "return" value of a function in Prolog


I know that functions in prolog don't "return" a value and moreover, functions don't exist (?), but instead we have predicates. However, I'm trying to write code to use Newton's method to find roots of a real-valued function. My code looks something like this:

newton(0,_).
newton(N,X) :-
    N > 0,
    write(X), nl,
    Y is f(X),
    Y_prime is f_prime(X),
    X_new is X - ((Y)/(Y_prime)),
    S is N-1,
    newton(S,X_new).

By simply writing, for example, 3*(X*X*X)-6*X+3 instead of f(X) and 6*(X*X)-6 instead of f_prime(X) we get a code that works perfectly when calling something like:

newton(10, 2).

However I would like to add some kind of previous statements (or predicates) like:

f(X,Y):-
    Y is 3*(X*X*X) - (X*X) + 6.
f_prime(X,Y):-
    Y is 6*(X*X) - 2*X.

And use these to somehow assign a value to Y and Y_prime in the main newton predicate. Is there a way to do this?


Solution

  • The same way you do with querying newton(N,X)

    newton(0,_).
    newton(N,X) :-
        N > 0,
        write(X), nl,
        f(X, Y),                      % <--
        f_prime(X, Y_prime),          % <--
        X_new is X - ((Y)/(Y_prime)),
        S is N-1,
        newton(S,X_new).