Skip to content

Instantly share code, notes, and snippets.

@erikprice
Created March 5, 2014 03:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erikprice/9360897 to your computer and use it in GitHub Desktop.
Save erikprice/9360897 to your computer and use it in GitHub Desktop.
Graham Scan in Haskell
grahamScan :: [Point] -> [Point]
grahamScan pts
| length pts < 3 = error "Not a polygon"
| otherwise = reverse $ scan rest (b:[a])
where (a:b:rest) = pts
scan [] acc = acc
scan pts acc = case d of
TurnsRight _ _ _ -> scan ps (c:a:stack)
_ -> scan ps (c:b:a:stack)
where (c:ps) = sortBy sortByYThenX pts
(b:a:stack) = acc
d = makeDirection a b c
-- Note that `garyScan` expects the input to be sorted via `sortByYThenX`.
garyScan :: [Point] -> [Point]
garyScan (a:b:c:rest) = case d of
TurnsRight _ _ _ -> garyScan (a:c:rest)
_ -> a : garyScan (b:c:rest)
where d = makeDirection a b c
garyScan pts = pts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment