2014-05-11 29 views
3

我必須製作一個程序,它決定兩個圓圈在haskell中是否重疊。 我已經定義了以下事情:在元組元組中提取元組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個圈的centeres),然後它決定如果它們通過檢查重疊的函數之間的距離的距離函數這兩個centeres之間的距離大於半徑(或圓角)的總和較小

問題是中心是一個touple和半徑是單個元件 繼承人我爲距離取得的函數:

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

,現在我需要做的距離< 2 *半徑,但我不能將它們組合起來,因爲距離應在touple執行和一個單獨的元素半徑

繼承人是我的嘗試:

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

有一個'sqrt'函數可能比'^(1/2)'更具可讀性。 –

回答

9

測試代碼10你實際上已經解決了你自己的問題,你只是不知道它!

它決定如果它們通過檢查這兩個centeres之間的距離大於半徑(或圓角)的總和較小的重疊的函數

我將直接轉化這句話的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 

就這麼簡單!

+1

非常感謝您的幫助<3 – Fatalgoddess