Skip to content

Commit

Permalink
Fix Iter.take to handle infinite iterator
Browse files Browse the repository at this point in the history
Previously, the `take` method on an infinite stream, such as `Rand`,
would cause infinite recursion.
  • Loading branch information
Theodus committed Sep 3, 2017
1 parent 257ffdb commit 858fa16
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
9 changes: 9 additions & 0 deletions packages/itertools/_test.pony
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,15 @@ class iso _TestIterTake is UnitTest

h.assert_array_eq[String](expected, actual)

let infinite =
Iter[U64](
object ref
fun ref has_next(): Bool => true
fun ref next(): U64 => 0
end)

h.assert_eq[USize](3, infinite.take(3).collect(Array[U64]).size())

class iso _TestIterTakeWhile is UnitTest
fun name(): String => "itertools/Iter.take_while"

Expand Down
11 changes: 7 additions & 4 deletions packages/itertools/iter.pony
Original file line number Diff line number Diff line change
Expand Up @@ -678,16 +678,19 @@ class Iter[A] is Iterator[A]
```
`1 2 3`
"""
filter_stateful(
Iter[A](
object
var _countdown: USize = n

fun ref apply(a: A!): Bool =>
fun ref has_next(): Bool =>
_countdown > 0

fun ref next(): A ? =>
if _countdown > 0 then
_countdown = _countdown - 1
true
_iter.next()?
else
false
error
end
end)

Expand Down

0 comments on commit 858fa16

Please sign in to comment.