2016-11-06 104 views
1

我想要查找連續元素之間線段長度的總和。如何檢查是否只有一個點並返回0.0作爲輸出。我還得到當我執行上面的代碼時出現縮進錯誤。haskell中線段長度的總和

lengthSum :: Floating a => [(a, a)] -> a 
lengthSum pts = zipWith (sqrt (x'*x' + y'*y')) pts $ tail pts 
    where 
     x' = fst(pts) - fst(head(tail(pts))) 
     y' = snd(pts) - snd(head(tail(pts))) 

Input: lengthSum [(0, 0)] 
Expected Output: 0.0 
Input: lengthSum [(0, 0), (0, 1), (3, 5)] 
Expected Output: 7.0 

請誰能幫助我,我在Haskell

+0

我複製,粘貼和加載代碼時不會出現縮進錯誤。這幾乎總是表明你在混合空格和製表符。如果確實如此,則用空格替換代碼中的所有選項卡。 – duplode

回答

1

你忘了實際添加了壓縮列表新手; sum將自動處理空列表。如果pts只有一個項目,則zipWith將返回空列表,因爲tail pts將爲空。但是,您需要分別處理空的輸入。 (我已經定義了一個輔助函數,使用模式匹配來簡化代碼)。

lengthSum :: Floating a => [(a,a)] -> a 
lengthSum [] = 0 
lengthSum pts = sum $ zipWith distance pts (tail pts) 
    where distance (x1,y1) (x2,y2) = sqrt ((x1-x2)^2 + (y1-y2)^2) 
+0

非常感謝,真的很有幫助:) –