Skip to content

Commit c554c2a

Browse files
committed
closes #3837
1 parent a622291 commit c554c2a

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

tests/iter/tchainediterators2.nim

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
discard """
2+
output: '''start
3+
false
4+
0
5+
1
6+
2
7+
end
8+
@[2, 4, 6, 8, 10]
9+
@[4, 8, 12, 16, 20]'''
10+
"""
11+
12+
# bug #3837
13+
14+
proc iter1(): (iterator: int) =
15+
let coll = [0,1,2]
16+
result = iterator: int {.closure.} =
17+
for i in coll:
18+
yield i
19+
20+
proc iter2(it: (iterator: int)): (iterator: int) =
21+
result = iterator: int {.closure.} =
22+
echo finished(it)
23+
for i in it():
24+
yield i
25+
26+
echo "start"
27+
let myiter1 = iter1()
28+
let myiter2 = iter2(myiter1)
29+
for i in myiter2():
30+
echo i
31+
echo "end"
32+
# start
33+
# false
34+
# end
35+
36+
37+
from sequtils import toSeq
38+
39+
type Iterable*[T] = (iterator: T) | Slice[T]
40+
## Everything that can be iterated over, iterators and slices so far.
41+
42+
proc toIter*[T](s: Slice[T]): iterator: T =
43+
## Iterate over a slice.
44+
iterator it: T {.closure.} =
45+
for x in s.a..s.b:
46+
yield x
47+
return it
48+
49+
proc toIter*[T](i: iterator: T): iterator: T =
50+
## Nop
51+
i
52+
53+
iterator map*[T,S](i: Iterable[T], f: proc(x: T): S): S =
54+
let i = toIter(i)
55+
for x in i():
56+
yield f(x)
57+
58+
proc filter*[T](i: Iterable[T], f: proc(x: T): bool): iterator: T =
59+
## Iterates through an iterator and yields every item that fulfills the
60+
## predicate `f`.
61+
##
62+
## .. code-block:: nim
63+
## for x in filter(1..11, proc(x): bool = x mod 2 == 0):
64+
## echo x
65+
let i = toIter(i)
66+
iterator it: T {.closure.} =
67+
for x in i():
68+
if f(x):
69+
yield x
70+
result = it
71+
72+
iterator filter*[T](i: Iterable[T], f: proc(x: T): bool): T =
73+
let i = toIter(i)
74+
for x in i():
75+
if f(x):
76+
yield x
77+
78+
var it = toSeq(filter(2..10, proc(x: int): bool = x mod 2 == 0))
79+
echo it # @[2, 4, 6, 8, 10]
80+
it = toSeq(map(filter(2..10, proc(x: int): bool = x mod 2 == 0), proc(x: int): int = x * 2))
81+
echo it # Expected output: @[4, 8, 12, 16, 20], Actual output: @[]

0 commit comments

Comments
 (0)