Add a zip_with function.

This commit is contained in:
Danila Fedorin 2020-12-06 20:51:20 -08:00
parent 15f578525d
commit cfd4d1447a
2 changed files with 37 additions and 0 deletions

29
spec/util_spec.cr Normal file
View File

@ -0,0 +1,29 @@
require "./spec_helper"
describe Array do
describe "#union" do
it "works with no elements" do
([] of Set(Int32)).union.should eq(Set(Int32).new)
end
it "correctly performs a union" do
[Set { 1 }, Set { 2 }, Set {1, 2, 3}].union.should eq(Set { 1,2,3})
end
end
describe "#intersect" do
expect_raises(Enumerable::EmptyError) do
([] of Set(Int32)).intersect
end
it "correctly performs an intersection" do
[Set {1}, Set {1,2}, Set {1,2,3}].intersect.should eq(Set{1})
end
end
describe "#zip_with" do
it "performs as expected" do
[1,2,3].zip_with([2,3,4]) { |l,r| l*r }.should eq([2,6,12])
end
end
end

View File

@ -1,4 +1,12 @@
class Array(T)
def zip_with(other : Array(R), &block : T, R -> U) forall R, U
dest = [] of U
zip(other) do |l, r|
dest << yield l, r
end
dest
end
def union
reduce(T.new) do |l, r|
l | r