Skip to content

Commit 04e56db

Browse files
committed
Tests and documentation for guards on comprehensions. Fixes #550. Your move Jeff. [ci skip]
1 parent beab3b6 commit 04e56db

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

base/generator.jl

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,9 @@
55
66
Given a function `f` and an iterator `iter`, construct an iterator that yields
77
the values of `f` applied to the elements of `iter`.
8-
The syntax `f(x) for x in iter` is syntax for constructing an instance of this
9-
type.
8+
The syntax `f(x) [if cond(x)::Bool] for x in iter` is syntax for constructing an instance of this
9+
type. The `[if cond(x)::Bool]` expression is optional and acts as a "guard", effectively
10+
filtering out values where the condition is false.
1011
"""
1112
immutable Generator{I,F}
1213
f::F

test/misc.jl

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -387,3 +387,34 @@ end
387387
optstring = sprint(show, Base.JLOptions())
388388
@test startswith(optstring, "JLOptions(")
389389
@test endswith(optstring, ")")
390+
391+
# generators and guards
392+
393+
let gen = (x for x in 1:10)
394+
@test typeof(gen) <: Generator
395+
@test gen.iter == 1:10
396+
@test gen.f(first(1:10)) == next(gen, start(gen))[1]
397+
for (a,b) in zip(1:10,gen)
398+
@test a == b
399+
end
400+
end
401+
402+
let gen = (x * y for x in 1:10, y in 1:10)
403+
@test gen == collect(1:10) .* collect(1:10)'
404+
@test first(gen) == 1
405+
@test collect(gen)[1:10] == collect(1:10)
406+
end
407+
408+
let gen = Base.Generator(+, 1:10, 1:10, 1:10)
409+
@test first(gen) == 3
410+
@test collect(gen) == collect(3:3:30)
411+
end
412+
413+
let gen = (x if x % 2 == 0 for x in 1:10), gen2 = Filter(x->x % 2 == 0, x for x in 1:10)
414+
@test collect(gen) == collect(gen2)
415+
@test collect(gen) == collect(2:2:10)
416+
end
417+
418+
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)
419+
@test collect(gen) == collect(gen2)
420+
end

0 commit comments

Comments
 (0)