gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 15:18:24 24 4
gpt4 key购买 nike

我必须编写一个程序,它决定两个圆在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com