haskell - 从元组的元组中提取元组 Haskell

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

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

问题是中心是一个元组,半径是一个元素 这是我为距离所做的函数:

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

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

这是我尝试过的:

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

最佳答案

你其实已经解决了自己的问题,只是你还不知道而已!

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)

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

就这么简单!

关于haskell - 从元组的元组中提取元组 Haskell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23594404/

相关文章:

algorithm - 一些有效的方法来实现这种 map 的插入和查找?

python - 在 python 中没有 for 循环的情况下重复函数几次

python - 从字符串和整数的元组中,获取元组内最接近给定值的数字

java - 计算 3D 椭圆轨道上的点

geometry - 如何测试一个点是否在二维整数坐标中的凸多边形内部?

r - 在 R 中绘制半圆

Haskell函数应用替换括号

haskell - 高效的并行策略

list - 在列表列表中追加列表 - Haskell

c# - 如何在 C# 中存储数据元组?