diff options
| -rw-r--r-- | README.md | 2 | ||||
| -rw-r--r-- | ch03/3_b_9.hs | 31 |
2 files changed, 28 insertions, 5 deletions
@@ -62,7 +62,7 @@ more visible in the list the first exercise of a group is in bold italics. | 3_b_7 | yes | | | | 3_b_8 | yes | | | | 3_b_9 | yes | | | -| 3_b_10 | | | | +| 3_b_10 | yes, in 3_b_9 | | | | 3_b_11 | | | | | 3_b_12 | | | | | **_4_a_1_** | | 84 | 4. Functional programming | diff --git a/ch03/3_b_9.hs b/ch03/3_b_9.hs index c6595de..d276c7b 100644 --- a/ch03/3_b_9.hs +++ b/ch03/3_b_9.hs @@ -1,9 +1,32 @@ --- 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. +-- 1. 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. +-- +-- 2. Write a function that calculates the turn made by three 2D points and +-- returns a Direction. data Direction = DLeft | DRight | DStraight deriving (Show) + +type Point = (Int, Int) + +-- The algorithm for computing the direction is taken from +-- https://en.wikipedia.org/wiki/Graham_scan +direction :: Point -> Point -> Point -> Direction +direction (x1, y1) (x2, y2) (x3, y3) + | cross_product_z > 0 = DLeft + | cross_product_z < 0 = DRight + | otherwise = DStraight + where cross_product_z = (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1) + +-- [1 of 1] Compiling Main ( 3_b_9.hs, interpreted ) +-- Ok, one module loaded. +-- ghci> direction (1,1) (2,2) (3,3) +-- DStraight +-- ghci> direction (1,1) (2,2) (3,4) +-- DLeft +-- ghci> direction (1,1) (2,2) (3,2) +-- DRight |
