Skip to content

Commit

Permalink
Implement RFC 66: Iter maybe (#3603)
Browse files Browse the repository at this point in the history
Closes #3593
  • Loading branch information
Theodus authored Jul 28, 2020
1 parent 0d51854 commit 37fa288
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
17 changes: 17 additions & 0 deletions packages/itertools/_test.pony
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ actor Main is TestList
test(_TestIterFold)
test(_TestIterLast)
test(_TestIterMap)
test(_TestIterNextOr)
test(_TestIterNth)
test(_TestIterRun)
test(_TestIterSkip)
Expand Down Expand Up @@ -345,6 +346,22 @@ class iso _TestIterMap is UnitTest

h.assert_array_eq[String](actual, expected)

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

fun apply(h: TestHelper) =>
let input: (U64 | None) = 42
var iter = Iter[U64].maybe(input)
h.assert_true(iter.has_next())
h.assert_eq[U64](42, iter.next_or(0))
h.assert_false(iter.has_next())
h.assert_eq[U64](0, iter.next_or(0))
h.assert_error({()? => Iter[U64].maybe(None).next()? })

iter = Iter[U64].maybe(None)
h.assert_false(iter.has_next())
h.assert_eq[U64](1, iter.next_or(1))

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

Expand Down
28 changes: 28 additions & 0 deletions packages/itertools/iter.pony
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,16 @@ class Iter[A] is Iterator[A]
fun ref next(): A ? =>
_iter.next()?

new maybe(value: (A | None)) =>
_iter =
object is Iterator[A]
var _value: (A | None) = consume value

fun has_next(): Bool => _value isnt None

fun ref next(): A ? => (_value = None) as A
end

new chain(outer_iterator: Iterator[Iterator[A]]) =>
"""
Take an iterator of iterators and return an Iter containing the
Expand Down Expand Up @@ -89,6 +99,24 @@ class Iter[A] is Iterator[A]
fun ref next(): A => _v
end

fun ref next_or(default: A): A =>
"""
Return the next value, or the given default.
## Example
```pony
let x: (U64 | None) = 42
Iter[U64].maybe(x).next_or(0)
```
`42`
"""
if has_next() then
try next()? else default end
else
default
end

fun ref map_stateful[B](f: {ref(A!): B^ ?}): Iter[B]^ =>
"""
Allows stateful transformation of each element from the iterator, similar
Expand Down

0 comments on commit 37fa288

Please sign in to comment.