Skip to content

Commit

Permalink
Tests and documentation for guards on comprehensions. Fixes #550. You…
Browse files Browse the repository at this point in the history
…r move Jeff. [ci skip]
  • Loading branch information
quinnj committed Jun 25, 2016
1 parent beab3b6 commit 04e56db
Show file tree
Hide file tree
Showing 2 changed files with 34 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
31 changes: 31 additions & 0 deletions test/misc.jl
Original file line number Diff line number Diff line change
Expand Up @@ -387,3 +387,34 @@ end
optstring = sprint(show, Base.JLOptions())
@test startswith(optstring, "JLOptions(")
@test endswith(optstring, ")")

# generators and guards

let gen = (x for x in 1:10)
@test typeof(gen) <: Generator
@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 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 if x % 2 == 0 for x in 1:10), 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) if x % 2 == 0 && y % 2 == 0 for x in 1:10, y in 1:10), 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

0 comments on commit 04e56db

Please sign in to comment.