Skip to content

Commit

Permalink
Tests and documentation for generators with guards and nesting.
Browse files Browse the repository at this point in the history
  • Loading branch information
quinnj authored and JeffBezanson committed Jun 29, 2016
1 parent 3d84224 commit 4f9e3f8
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
5 changes: 3 additions & 2 deletions base/generator.jl
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@
Given a function `f` and an iterator `iter`, construct an iterator that yields
the values of `f` applied to the elements of `iter`.
The syntax `f(x) for x in iter` is syntax for constructing an instance of this
type.
The syntax `f(x) [if cond(x)::Bool] for x in iter` is syntax for constructing an instance of this
type. The `[if cond(x)::Bool]` expression is optional and acts as a "guard", effectively
filtering out values where the condition is false.
"""
immutable Generator{I,F}
f::F
Expand Down
37 changes: 37 additions & 0 deletions test/functional.jl
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,43 @@ let i = 1
@test i == 1
end

# generators and guards

let gen = (x for x in 1:10)
@test gen.iter == 1:10
@test gen.f(first(1:10)) == next(gen, start(gen))[1]
for (a,b) in zip(1:10,gen)
@test a == b
end
end

let gen = (x * y for x in 1:10, y in 1:10)
@test collect(gen) == collect(1:10) .* collect(1:10)'
@test first(gen) == 1
@test collect(gen)[1:10] == collect(1:10)
end

let gen = Base.Generator(+, 1:10, 1:10, 1:10)
@test first(gen) == 3
@test collect(gen) == collect(3:3:30)
end

let gen = (x for x in 1:10 if x % 2 == 0), gen2 = Filter(x->x % 2 == 0, x for x in 1:10)
@test collect(gen) == collect(gen2)
@test collect(gen) == collect(2:2:10)
end

let gen = ((x,y) for x in 1:10, y in 1:10 if x % 2 == 0 && y % 2 == 0),
gen2 = Filter(x->x[1] % 2 == 0 && x[2] % 2 == 0, (x,y) for x in 1:10, y in 1:10)
@test collect(gen) == collect(gen2)
end

# generators with nested loops (#4867)

@test [(i,j) for i=1:3 for j=1:i] == [(1,1), (2,1), (2,2), (3,1), (3,2), (3,3)]

@test [(i,j) for i=1:3 for j=1:i if j>1] == [(2,2), (3,2), (3,3)]

# partition(c, n)
let v = collect(Base.partition([1,2,3,4,5], 1))
@test all(i->v[i][1] == i, v)
Expand Down

0 comments on commit 4f9e3f8

Please sign in to comment.