I have recently started learning functional programming and Haskell. I have encountered this problem:
Consider three two-dimensional points a, b, and c. If we look at the angle formed by the line segment from a to b and the line segment from b to c, it either turns left, turns right, or forms a straight line. Define a Direction data type that lets you represent these possibilities. Write a function that calculates the turn made by three 2D points and returns a Direction.
I have heard that one of the goals of the Haskell language is to create elegant solutions.
This is my solution:
data Direction = LeftTurn | RightTurn | Straight deriving Show findDirection (x, y) (x1, y1) (x2, y2) | (x, y) == (x1, y1) = Straight | (x1, y1) == (x2, y2) = Straight | (x, y) == (x2, y2) = Straight | x == x1 && x1 == x2 = Straight | x1 == x && y1 > y && x2 > x = RightTurn | x1 == x && y1 > y && x2 < x = LeftTurn | x1 == x && y1 < y && x2 < x = RightTurn | x1 == x && y1 < y && x2 > x = LeftTurn | x1 > x && y2 > y_on_line = LeftTurn | x1 > x && y2 < y_on_line = RightTurn | x1 > x && y2 == y_on_line = Straight | x1 < x && y2 > y_on_line = RightTurn | x1 < x && y2 < y_on_line = LeftTurn | x1 < x && y2 == y_on_line = Straight where y_on_line = slope * x2 + y_intercept slope = (y1 - y) / (x1 - x) y_intercept = y - slope * x
This looks like it is too long to be considered an elegant solution.