Skip to content

Instantly share code, notes, and snippets.

@sphynx
Last active August 29, 2015 14:02
Show Gist options
  • Save sphynx/0bb6bb337e0a296dbf7c to your computer and use it in GitHub Desktop.
Save sphynx/0bb6bb337e0a296dbf7c to your computer and use it in GitHub Desktop.
module Q where
data Quarter = NE | NW | SE | SW deriving Show
type Vector = (Float, Float)
quarter :: Vector -> Vector -> Quarter
quarter look target = detect $ angle look - angle target
detect :: Float -> Quarter
detect x
| x < 0 = detect $ x + 2*pi
| x >= 0 && x < pi/2 = NE
| x >= pi/2 && x < pi = SE
| x >= pi && x < 3*pi/2 = SW
| x >= 3*pi/2 && x < 2*pi = NW
| otherwise = error "detect"
fix :: Float -> Float -> Float -> Float
fix x y res
| x >= 0 && y >= 0 = res
| x <= 0 && y >= 0 = pi - res
| x >= 0 && y <= 0 = 2*pi - res
| x <= 0 && y <= 0 = pi + res
angle :: Vector -> Float
angle (x, y) = fix x y $ asin $ y / hypo (x, y)
hypo :: Vector -> Float
hypo (x, y) = sqrt $ x ** 2 + y ** 2
{-
Tests:
> quarter (1,1) (0,1)
NW
> quarter (1,1) (-1,0)
SW
> quarter (1, 0) (2,-1)
NW
-}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment