Skip to content

Commit

Permalink
renamed functional.zip to functional.combine; functional.zip and new …
Browse files Browse the repository at this point in the history
…functional.unzip are now "more traditional" simple sequence operations
  • Loading branch information
1bardesign committed Jan 11, 2024
1 parent ae98047 commit 3d03d32
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 5 deletions.
35 changes: 30 additions & 5 deletions functional.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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!)
Expand Down
6 changes: 6 additions & 0 deletions sequence.lua
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ for _, v in ipairs({
"filter",
"remove_if",
"zip",
"combine",
"stitch",
"map_stitch",
"cycle",
Expand Down Expand Up @@ -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

0 comments on commit 3d03d32

Please sign in to comment.