Search code examples
prolog

writing a Prolog isSquare function


I am trying to write a simple function that checks if a list of entered coordinates are a square in prolog for example: isSquare(x1,y1,x2,y2,x3,y3,x4,y4) and the response would be either true or false

I currently have the following

isSquare(x1, y1, x2, y2, x3, y3, x4, y4)
        Slope1 = (y2 - y1) / (x2 - x1)
        Slope2 = (y3 - y2) / (x3 - x2)
        Slope3 = (y4 - y3) / (x4 - x3)
        Slope4 = (y1 - y4) / (x1 - x4)
        
        If Slope1 * Slope2 == Slope3 * Slope4 
                return true
        else 
                return false

but i have hit a wall, I would appreciate any guidance as I am totally new to prolog and am learning as I go


Solution

  • There are some problems here. First of all Prolog uses predicates, not functions. A predicate does not "return" something. It either succeeds or fails. It can also get stuck in an infinite loop or raise an exception, but let us ignore that for now.

    Furthermore variables start with an Uppercase, so x1 is not a variable, but a constant. There is an if-then-else syntax, but that is ( condition -> then-body; else-body ), and we do not need this here.

    In order to evaluate expressions, one uses is/2. You can also use (=:=)/2 here to evaluate both operands and check if the result is equal, so we can rewrite the predicate to.

    The head and body of the predicate are separated by a :-, and one uses a comma (,) for something that is logically similar to an and. So the predicate looks like:

    isSquare(X1, Y1, X2, Y2, X3, Y3, X4, Y4) :-
            Slope1 = (Y2 - Y1) / (X2 - X1),
            Slope2 = (Y3 - Y2) / (X3 - X2),
            Slope3 = (Y4 - Y3) / (X4 - X3),
            Slope4 = (Y1 - Y4) / (X1 - X4),
            Slope1 * Slope2 =:= Slope3 * Slope4.