我这样画了两点之间的距离
distance (x1 , y1) (x2 , y2) = sqrt (x'*x' + y'*y') where x' = x1 - x2 y' = y1 - y2但是不知道如何使用可变的列表大小,谢谢
解决方案我们可以将此函数重命名为distance2以指定它计算两点之间的距离:
distance2 :: Floating a => (a, a) -> (a, a) -> a distance2 (x1 , y1) (x2 , y2) = sqrt (x'*x' + y'*y') where x' = x1 - x2 y' = y1 - y2接下来,我们可以使用 zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] 可以同时迭代两个列表,并将一个函数应用于元素.在这里,我们遍历列表及其尾部.因此,这将产生一个距离列表.我们可以使用 总结这些距离:
distance2 :: Floating a => [(a, a)] -> a distance [] = 0 distance xa@(_:xs) = sum (zipWith distance2 xa xs)im new to haskell and i have to do a function that takes a list and calculates the distance recursively.
For example: distance [(0,0),(2,0),(2,5)] ->7 distance [(1,1),(3,4)] ->3.6055512I made the distance between just two points like this
distance (x1 , y1) (x2 , y2) = sqrt (x'*x' + y'*y') where x' = x1 - x2 y' = y1 - y2But dont know how do to it with a variable list size, thanks
解决方案We can rename this function to distance2 to specify that it calculates the distance between two points:
distance2 :: Floating a => (a, a) -> (a, a) -> a distance2 (x1 , y1) (x2 , y2) = sqrt (x'*x' + y'*y') where x' = x1 - x2 y' = y1 - y2Next we can make use of zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] to iterate concurrently over two lists, and apply a function to the elements. Here we iterate over the list, and its tail. This will thus produce a list of distances. We can make use of sum :: (Num a, Foldable f) => f a -> a to sum up these distances:
distance2 :: Floating a => [(a, a)] -> a distance [] = 0 distance xa@(_:xs) = sum (zipWith distance2 xa xs)
更多推荐
Haskell点之间的距离
发布评论