Add a zip_with function.
This commit is contained in:
parent
15f578525d
commit
cfd4d1447a
29
spec/util_spec.cr
Normal file
29
spec/util_spec.cr
Normal 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
|
|
@ -1,4 +1,12 @@
|
||||||
class Array(T)
|
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
|
def union
|
||||||
reduce(T.new) do |l, r|
|
reduce(T.new) do |l, r|
|
||||||
l | r
|
l | r
|
||||||
|
|
Loading…
Reference in New Issue
Block a user