ref: aa906e108823e155dd2c5e9b1b4ef6967f55473b
parent: 4855e100dd14214ffe838fd836e4dcb726dea1d2
author: Ori Bernstein <ori@eigenstate.org>
date: Sun Sep 4 16:50:27 EDT 2016
Add byreverse iterator.
--- a/lib/std/iterutil.myr
+++ b/lib/std/iterutil.myr
@@ -7,6 +7,11 @@
s2 : @b[:]
;;
+ type reverseiter(@a) = struct
+ sl : @a[:]
+ idx : size
+ ;;
+
type enumiter(@a) = struct
idx : size
s : @a[:]
@@ -14,9 +19,11 @@
impl iterable zipiter(@a, @b) -> (@a, @b)
impl iterable enumiter(@a) -> (size, @a)
+ impl iterable reverseiter(@a) -> (size, @a)
generic byzip : (a : @a[:], b : @b[:] -> zipiter(@a, @b))
generic byenum : (a : @a[:] -> enumiter(@a))
+ generic byreverse : (sl : @a[:] -> reverseiter(@a))
;;
generic byzip = {a, b
@@ -39,7 +46,25 @@
}
;;
+generic byreverse = {sl
+ -> [.sl = sl, .idx = sl.len]
+}
+impl iterable reverseiter(@a) -> @a =
+ __iternext__ = {itp, valp
+ if itp.idx > 0
+ valp# = itp.sl[itp.idx - 1]
+ itp.idx--
+ -> true
+ else
+ -> false
+ ;;
+ }
+
+ __iterfin__ = {itp, valp
+ }
+;;
+
generic byenum = {a
-> [.s = a, .idx = 0]
}
@@ -47,7 +72,6 @@
impl iterable enumiter(@a) -> (size, @b) =
__iternext__ = {itp, valp
if itp.idx < itp.s.len
- std.put("itp.idx: {}, itp.s[{}]: {}\n", itp.idx, itp.idx, itp.s[itp.idx])
valp# = (itp.idx, itp.s[itp.idx])
itp.idx++
-> true
--- a/lib/std/test/iterutil.myr
+++ b/lib/std/test/iterutil.myr
@@ -16,4 +16,11 @@
std.assert(b == n*2 + 2, "invalid val from b: {}", b)
n++
;;
+
+ n = 0
+ for x in std.byreverse([3, 2, 1, 0][:])
+ std.assert(x == n, "invalid reversed value {}, expected {}", x, n)
+ n++
+ ;;
+
}