Last active
December 24, 2015 04:59
-
-
Save agrif/6747349 to your computer and use it in GitHub Desktop.
checking if something is a square, in haskell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Data.List | |
| -- checks if a list of points forms a square, by checking: | |
| -- * if |b - a| == |c - a|, | |
| -- * if 0 == (b - a) . (c - a), and | |
| -- * if a + (b - a) + (c - a) == d | |
| -- (a, b, c, d are sorted by distance from a) | |
| isSquare (a:as) = and [ | |
| mag2 (b - a) == mag2 (c - a), | |
| 0 == (b - a) `dot` (c - a), | |
| b + (c - a) == d | |
| ] where sortfunc x y = compare (mag2 $ x - a) (mag2 $ y - a) | |
| [b, c, d] = sortBy sortfunc as | |
| -- a convenience class for dealing with 2d vectors | |
| data Vec a = Vec a a deriving (Eq, Show, Read) | |
| -- addition and subtraction | |
| instance (Num a) => Num (Vec a) where | |
| (Vec a b) + (Vec c d) = Vec (a + c) (b + d) | |
| negate (Vec a b) = Vec (-a) (-b) | |
| -- magnitude squared | |
| mag2 (Vec a b) = a*a + b*b | |
| -- dot products | |
| (Vec a b) `dot` (Vec c d) = a*c + b*d | |
| -- main function to read points and check them | |
| main = do | |
| putStrLn "list of points to check in form [(a, b), ...]: " | |
| pts <- getLine | |
| print $ isSquare [Vec a b | (a, b) <- read pts] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment