Search code examples
prolog

user defined square predicate


I am using SWI-Prolog V 6.2.3 on Windows 7. I have written the following predicates that calculate the absolute value and the square of an integer:

myabs(X,X):- X > = 0.

myabs(X,Y):- Y is -X.

mysq(X,S):- myabs(X,Y), S is Y * Y.

I get errors (operator error) for the following lines:

2 : Prolog does not seem to accept -X.

3 : Prolog does not seem to accept Y * Y (when replaced by 2 * 2, I don't get error)

I understand there are built-in predicates for these functions, but as I am new, these are small programs that help me learn.


Solution

  • you have a typo in rule 1: remove the space after >

    myabs(X,X):- X >= 0.
    myabs(X,Y):- Y is -X.
    mysq(X,S):- myabs(X,Y), S is Y * Y.
    

    then, after correction:

    ?- mysq(-3,X).
    X = 9.
    

    Are you aware that myabs is not required for squaring?

    ?- X = -3, Y is X*X.
    X = -3,
    Y = 9.
    

    edit as @false noted, also myabs/2 needs a correction, to prevent wrong results when input is positive and backtracking is involved. Adding a guard to second clause could do:

    myabs(X, Y):- X < 0, Y is -X.
    

    but I would prefer the if/then/else construct, i.e. replacing those 2 clauses with

    myabs(X, Y) :- X >= 0 -> Y is X ; Y is -X.