gpt4 book ai didi

javascript - 是否有可能以纯函数式的方式实现 Haskell 的 unzip 的 js 版本?

转载 作者:可可西里 更新时间:2023-11-01 01:53:42 24 4
gpt4 key购买 nike

我正在以纯函数式的方式实现一个 javascript 光线转换多边形中的点算法(背后没有特别的原因)。

我被卡住了,因为我需要从二维数组中获取两个数组(复制元组列表);类似于 Haskell 的 unzip

是否有可能从类似[[a,b],[c,d],[e,f]]开始获得[[a,c,e] ,[b,d,f]] 不使用过程式迭代器?

(我知道这是一个微不足道的问题,我可以按程序实现该功能然后忘记它,但我很想知道是否有解决方案)


编辑:澄清一下,我知道如何实现 zipunzip:我想知道是否可以在没有 for 的情况下实现它们> 循环和变量重新分配。

最佳答案

您的解压缩只是一个 zip,但有多个参数。大多数人不只使用相同功能的唯一原因是大多数时候 zip接收可变参数列表而不是数组,因此您需要使用 apply 解包在解压缩函数中。

在我正在使用的库 Dojo 中,它们实现了 zip 和 unzip as

unzip: function(/*Array*/ a){
// summary: similar to dojox.lang.functional.zip(), but takes
// a single array of arrays as the input.
// description: This function is similar to dojox.lang.functional.zip()
// and can be used to unzip objects packed by
// dojox.lang.functional.zip(). It is here mostly to provide
// a short-cut for the different method signature.

return df.zip.apply(null, a);
}

zip: function(){
// summary: returns an array of arrays, where the i-th array
// contains the i-th element from each of the argument arrays.
// description: This is the venerable zip combiner (for example,
// see Python documentation for general details). The returned
// array is truncated to match the length of the shortest input
// array.
var n = arguments[0].length,
m = arguments.length,
i = 1,
t = new Array(n),
j,
p;
for(; i < m; n = Math.min(n, arguments[i++].length));
for(i = 0; i < n; ++i){
p = new Array(m);
for(j = 0; j < m; p[j] = arguments[j][i], ++j);
t[i] = p;
}
return t;
},

请注意 zip 接收多个参数,因此它更像 Python zip 而不是 Haskell zip。


将此代码转换为没有变量赋值的“纯函数式”风格应该不难。您现有的代码应该已经在处理我发布的示例中前两个 for 的工作(以最小长度 chop zip 并遍历其中一个列表的索引)。剩下的就是对第三个 for 做类似的事情——从列表列表中收集第 i 个值,而不是从两个列表中收集两个值。

关于javascript - 是否有可能以纯函数式的方式实现 Haskell 的 unzip 的 js 版本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8519509/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com