Skip to content

Instantly share code, notes, and snippets.

@agrif
Last active December 24, 2015 04:59
Show Gist options
  • Select an option

  • Save agrif/6747349 to your computer and use it in GitHub Desktop.

Select an option

Save agrif/6747349 to your computer and use it in GitHub Desktop.
checking if something is a square, in haskell
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