Haskell点之间的距离

编程入门 行业动态 更新时间:2024-10-27 21:14:09
本文介绍了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点之间的距离

本文发布于:2023-10-27 22:32:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1534741.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:距离   Haskell

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!