Haskell点之间的距离

Haskell点之间的距离

本文介绍了Haskell点之间的距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Haskell的新手,我必须做一个函数,该函数需要一个列表并递归计算距离.

For example:
distance [(0,0),(2,0),(2,5)]
->7
distance [(1,1),(3,4)]
->3.6055512

我这样画了两点之间的距离

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.6055512

I 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 - y2

But 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 - y2

Next 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点之间的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 05:45