Search code examples
prolog

Writing a math function in Prolog


I need to write a function in Prolog, but I don't understand how to return the value of R and put it in the final function. I get that Prolog doesn't return values, but I still can't figure it out.

This is a functionThis is what I have now:

run:- write('Input X, Z:'), nl,
    read(X), number(X),
    read(Z), number(Z),
    func(X,Y),
    write('Y='), write(Y), nl.
countR(X,Z,R):- X^2>=Z, R is Z*X.
countR(X,Z,R):- X^2<Z, R is Z*e^-X.
func(X,Y):- X>R, Y is 1-X^R.
func(X,Y):- X=<R, Y is 1-X^-R.

Solution

  • It would be like:

    run:- write('Input X, Z:'), nl,
        read(X), number(X),
        read(Z), number(Z),
        func(X,Z,Y),
        write('Y='), write(Y), nl.
    
    countR(X,Z,R) :-
        Xsq is X^2,
        Xsq >= Z,
        R is Z*X.
    
    func(X,Z,Y) :- 
        countR(X, Z, R),
        X > R,
        Y is 1-X^R.
    

    "func holds for X, Z and Y if countR holds for X, Z, R and X is greater than R and Y is 1-X^R"

    and same pattern for the other cases.