在元组Haskell的元组中提取元组

时间:2014-05-11 15:22:36

标签: haskell tuples geometry overlapping

我必须制作一个程序,它决定两个圆圈是否在haskell中重叠。 我定义了以下内容:

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

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

我需要制作一个距离函数来计算两个点之间的距离(因此是2个圆圈的中心),然后是一个函数,通过检查两个中心之间的距离是否小于总和来决定它们是否重叠半径(或半径)

问题是中心是一个外观,半径是一个单一元素 继承了我为距离做的功能:

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

现在我需要做距离< 2 *半径,但我不能将它们组合起来,因为距离应该在一个元素上进行,而半径在单个元素上进行

继承人我的尝试:

-- | '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]

但当然它不起作用:(

应该证明我的功能的测试代码是

-- | 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)

1 个答案:

答案 0 :(得分:9)

你实际上已经解决了自己的问题,但你还不知道呢!

  

通过检查两个中心之间的距离是否小于半径之和(或半径)来确定它们是否重叠的函数

我将这句话直接翻译成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

为了完成这项工作,我们需要定义两个函数centreradius,它们分别得到圆心的中心点和半径。

centre c = fst c
radius c = snd c

就这么简单!