Skip to content

Instantly share code, notes, and snippets.

@jb55
Created October 20, 2010 18:34
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 jb55/637019 to your computer and use it in GitHub Desktop.
Save jb55/637019 to your computer and use it in GitHub Desktop.
import Data.List
import Data.Maybe
type Point = (Int, Int)
data Line = Line Point Point
deriving (Eq, Show, Ord)
fx (Line (n, _) _) = n
fy (Line (_, n) _) = n
sx (Line _ (n, _)) = n
sy (Line _ (_, n)) = n
dx l = (sx l) - (fx l)
dy l = (sy l) - (fy l)
merge :: [Line] -> Line
merge ls = Line (smallX, smallY) (bigX, bigY)
where
optimize optFn ch = foldl optFn (ch $ head ls) (map ch ls)
smallX = optimize min fx
smallY = optimize min fy
bigX = optimize max sx
bigY = optimize max sy
slope :: Line -> Rational
slope l = (toRational $ dy l) / (toRational $ dx l)
slopes ls = zip ls (map slope ls)
groupLines :: [Line] -> [[Line]]
groupLines = groupBy check
where
check l1 l2 = (slope l1) == (slope l2) && l1 `isCoLinear` l2
isCoLinear l1 l2 = False
joinLines = (map merge) . groupLines
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment