diff --git a/functional.lua b/functional.lua index 1b2d67e..3c19e27 100644 --- a/functional.lua +++ b/functional.lua @@ -209,11 +209,11 @@ function functional.group_by(t, f) return result end ---zips two sequences together into a new table, based on another function ---iteration limited by min(#t1, #t2) ---function receives arguments (t1, t2, i) ---nil results ignored -function functional.zip(t1, t2, f) +--combines two same-length sequences through a function f +-- f receives arguments (t1[i], t2[i], i) +-- iteration limited by min(#t1, #t2) +-- ignores nil results +function functional.combine(t1, t2, f) local ret = {} local limit = math.min(#t1, #t2) for i = 1, limit do @@ -227,6 +227,31 @@ function functional.zip(t1, t2, f) return ret end +--zips two sequences together into a new table, alternating from t1 and t2 +-- zip({1, 2}, {3, 4}) -> {1, 3, 2, 4} +-- iteration limited by min(#t1, #t2) +function functional.zip(t1, t2) + local ret = {} + local limit = math.min(#t1, #t2) + for i = 1, limit do + table.insert(ret, t1[i]) + table.insert(ret, t2[i]) + end + return ret +end + +--unzips a table into two new tables, alternating elements into each result +-- {1, 2, 3, 4} -> {1, 3}, {2, 4} +-- gets an extra result in the first result for odd-length tables +function functional.unzip(t) + local a = {} + local b = {} + for i, v in ipairs(t) do + table.insert(i % 2 == 1 and a or b, v) + end + return a, b +end + ----------------------------------------------------------- --specialised maps -- (experimental: let me know if you have better names for these!) diff --git a/sequence.lua b/sequence.lua index 54618cb..177a3e4 100644 --- a/sequence.lua +++ b/sequence.lua @@ -73,6 +73,7 @@ for _, v in ipairs({ "filter", "remove_if", "zip", + "combine", "stitch", "map_stitch", "cycle", @@ -127,4 +128,9 @@ function sequence:partition(f) return sequence(a), sequence(b) end +function sequence:unzip(f) + local a, b = functional.unzip(self, f) + return sequence(a), sequence(b) +end + return sequence