Question

I have to make a program, which decides if two circles are overlapping in haskell. I have the following things defined:

-- | A 2D Point.
type Point = (Float,Float)

-- | A Circle is a pair of its center point and its radius.
type Circle = (Point,Float)

I need to make a distance function which calculates the distance between two points (hence the centeres of the 2 circles) and then a function which decides if they are overlapping by checking that the distance between the two centeres is smaller than the sum of the radiuses(or radii)

The problem is the centres are a touple and the radius is a single element heres the function i made for distance:

-- | Distance between two points.
distance :: Point -> Point -> Float
distance p1 p2 = ((snd p1 - fst p1)^2 + (snd p2 - snd p1)^2)^(1/2)

and now i need to do distance < 2 * radius but i cant combine them because the distance should be performed on a touple and the radius on a single element

heres what i tried :

-- | 'True' if the given circles overlap, else 'False'.
overlap :: Circle -> Circle -> Bool
overlap c1 c2 = [distance x,y | x<-(x,y):c1, y<-(x1,y1):c2] < [sum z,z1 | z<-(z):c1, z1<-(z1):c2]

but of course it doesnt work :(

the test code that should prove my function is

-- | Some example calls to try out the 'overlap' function.
main :: IO ()
main = do
    let circle1 = ((0,0),1)
        circle2 = ((5,6),1)
        circle3 = ((2,3),14)
    print "overlap circle1 circle2:"
    print (overlap circle1 circle2)
    print "overlap circle1 circle3:"
    print (overlap circle1 circle3)
    print "overlap circle3 circle2:"
    print (overlap circle3 circle2)
Was it helpful?

Solution

You have actually already solved your own problem, you just don't know it yet!

a function which decides if they are overlapping by checking that the distance between the two centeres is smaller than the sum of the radiuses(or radii)

I'll translate this sentence directly to Haskell:

a function which decides if they are overlapping
   |           by checking that the distance
   |               |    between the two centres
   |               |         |           |    is smaller than
   |               |         |           |       |      the sum of
   |               |         |           |       |           |
   |               |         |           |       |     the radiuses
   |               |         |           |       |     |     |    |
   v               v         v           v       v     v     v    v
overlap c1 c2 = distance (centre c1) (centre c2) < radius c1 + radius c2

To make this work, we need to define the two functions centre and radius, which get the centre point and the radius of a circle respectively.

centre c = fst c
radius c = snd c

It's as simple as that!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top