Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Function 将一个列表映射到另一个列表(在Haskell的抽象解决方案中)';映射减少';?_Function_Haskell - Fatal编程技术网

Function 将一个列表映射到另一个列表(在Haskell的抽象解决方案中)';映射减少';?

Function 将一个列表映射到另一个列表(在Haskell的抽象解决方案中)';映射减少';?,function,haskell,Function,Haskell,假设我们有一个坐标列表,如: (1,2) (0,3) (4,1) (0,3) (-2,3) (6,5) 我们想要得到下面的列表,它被定义为每个连续坐标的总和。(对不起,定义不正确)像这样: (1,5) (4,4) (4,4) (-2,6) (4,8) 因此存在一个集合a=(a,b,c,…,n),其中a,b,c,…,n是R^2中的坐标。 存在一个函数f,使得f(a)=B=(a+B,B+c,c+d,…,n-1+n) ~ 你会如何用Haskell这样的函数式语言写这样的东西?一个将f应用于给定A的程序

假设我们有一个坐标列表,如:
(1,2)
(0,3)
(4,1)
(0,3)
(-2,3)
(6,5)

我们想要得到下面的列表,它被定义为每个连续坐标的总和。(对不起,定义不正确)像这样:
(1,5)
(4,4)
(4,4)
(-2,6)
(4,8)

因此存在一个集合a=(a,b,c,…,n),其中a,b,c,…,n是R^2中的坐标。
存在一个函数f,使得f(a)=B=(a+B,B+c,c+d,…,n-1+n)

~


你会如何用Haskell这样的函数式语言写这样的东西?一个将f应用于给定A的程序将给出B。

你可以使用
zip
用它的尾部来压缩列表,你会得到像
[((1,2),(0,3)),((0,3),(4,1)),…]这样的成对。然后,您可以使用
map
将每对线对替换为其总和。或者您可以在一个函数中使用
zipWith
,它基本上是
zip
+
map
,除了指定给
zipWith
的函数具有类型
a->b->c
,而不是
(a,b)->c

summedCoords = zipWith (\ (a,b) (c,d) -> (a+c, b+d)) coords (tail coords)

您可以编写这样的泛型函数

g:: (a -> a -> b) -> [a] -> [b]
g f (x1:x2:xs) = (f x1 x2):(g (x2:xs))
g _ (x1:[]) = []
并将其传递给add函数

f = g f' where 
    f' (a,b) (a',b') = (a+a', b+b')

我想你是指
summedCoords coords=zipWith(\(a,b)(c,d)->(a+c,b+d))coords(tail coords)
?:)@申:是的,我绝对喜欢。谢谢