I´ve written a function in Haskell that takes three points in the plane,
and checks if they´re on a straight line, or make a right or left turn.
Here´s the code:
detDirection :: Point -> Point -> Point -> Direction
detDirection a@(Point (x1, y1)) b@(Point (x2, y2)) c
= if (collinear1 a b c)
then Straight
else let
ab = Vector [x2 - x1, y2 - y1]
angleAbX = angle ab (Vector [1, 0])
(Point (x1, y1)) = turnAtP a b angleAbX
(Point (x2, y2)) = turnAtP a c angleAbX
in if (y1 > y2)
then Right
else Left
I´ve tested collinear1, angle, turnAtP in GHCi, and they all terminate immediately.
detDirection, however, keeps running forever.
Can someone tell me where the problem here is?
In Haskell,
letis a recursive binding, that is, you can refer to variables declared in theletexpression in the defining expressions of the other variables. So, when you writethe
x1,x2,y1, andy2on the first line do not refer to the function arguments but to the same names declared later on in theletexpression. Just change the twoPointlines to bind some different variables, likeand modify your later computation accordingly, and your infinite looping will go away.