From 45f6de5928c2033cb309a62a6dcf5c0ebfe4d4af Mon Sep 17 00:00:00 2001 From: borovan <84897664+borovan@users.noreply.github.com> Date: Fri, 6 May 2022 12:54:14 +0200 Subject: [PATCH] change revRange to same argument types as range This allows it to iterate returning ?Nat instead of ?Int so it can be used in arrays. As range starts at Nat I figured that negative numbers weren't that important anyway. Maybe range should be (Nat, Nat) too? So then you've got the two functions that are easily used with arrays. Could always add rangeInt separately. This is my first pull request so if I've screwed anything up DONT HOLD BACK! Here are the tests I used // revRange do { let rev = LIter.revRange(0, 0); assert(rev.next() == ?0); assert(rev.next() == null); }; do { let rev = LIter.revRange(3, 1); assert(rev.next() == ?3); assert(rev.next() == ?2); assert(rev.next() == ?1); assert(rev.next() == null); }; --- src/Iter.mo | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/src/Iter.mo b/src/Iter.mo index 9f36887e..6706225a 100644 --- a/src/Iter.mo +++ b/src/Iter.mo @@ -36,11 +36,25 @@ module { public func next() : ?Nat { if (i > y) { null } else {let j = i; i += 1; ?j} }; }; - /// Like `range` but produces the values in the opposite - /// order. - public class revRange(x : Int, y : Int) { - var i = x; - public func next() : ?Int { if (i < y) { null } else {let j = i; i -= 1; ?j} }; + /// Like `range` but produces the values in the opposite order. + /// ```motoko + /// let iter = Iter.revRange(2, 0); + /// assert(?2 == iter.next()); + /// assert(?1 == iter.next()); + /// assert(?0 == iter.next()); + /// assert(null == iter.next()); + /// ``` + public class revRange(x : Nat, y : Int) { + var i : Int = x; + public func next() : ?Nat { + if (i + 1 == y or i < 0) { + null; + } else { + let j = Int.abs(i); + i -= 1; + ?j; + }; + }; }; /// Calls a function `f` on every value produced by an iterator and discards