haskell

时间:2016-11-06 15:46:28

标签: haskell functional-programming

我想找到连续元素之间的线段总长度。如何检查是否只有一个点并返回0.0作为输出。我在执行上述代码时也会出现缩进错误

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

请有人帮助我,我是哈斯克尔的新手

1 个答案:

答案 0 :(得分:1)

您忘记了实际添加压缩列表; sum将自动处理空列表。如果zipWith只有一个项目,则pts将返回一个空列表,因为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)