Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Changelog.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
# Next

* Add `findInRange()` and `findInRangeBinarySearch()` to `Int` and `Nat` (#381).

## 1.0.0

* Add `sliceToVarArray()` to `Array` and `VarArray` (#377).
Expand Down
58 changes: 58 additions & 0 deletions src/Int.mo
Original file line number Diff line number Diff line change
Expand Up @@ -577,4 +577,62 @@ module {
}
};

/// Returns the first value in the range of `Int` values [fromInclusive, toExclusive) for which `predicate` returns true.
/// If no element satisfies the predicate (or the range is empty), returns null.
///
/// ```motoko include=import
///
/// assert Int.findInRange(3, 9, func(x) { x > 7 }) == ?8;
/// assert Int.findInRange(3, 8, func(x) { x > 7 }) == null;
/// assert Int.findInRange(3, 8, func(x) { x < 7 }) == ?3;
/// ```
///
/// Runtime: O(toExclusive - fromInclusive)
///
/// Space: O(1)
///
/// *Runtime and space assumes that `predicate` runs in O(1) time and space.
public func findInRange(fromInclusive : Int, toExclusive : Int, predicate : Int -> Bool) : ?Int {
for (element in range(fromInclusive, toExclusive)) {
if (predicate element) {
return ?element
}
};
null
};

/// Same as `findInRange()`, but requires that `predicate` is non-decreasing on [fromInclusive, toExclusive).
/// Returns the first value in the range of `Int` values [fromInclusive, toExclusive) for which `predicate` returns true.
/// If no element satisfies the predicate (or the range is empty), returns null.
/// If `predicate` is not non-decreasing on the interval, the result is undefined.
///
/// ```motoko include=import
///
/// assert Int.findInRangeBinarySearch(3, 9, func(x) { x > 7 }) == ?8;
/// assert Int.findInRangeBinarySearch(3, 8, func(x) { x > 7 }) == null;
/// Int.findInRangeBinarySearch(3, 8, func(x) { x < 7 }); // Undefined result: `predicate` is not non-decreasing.
/// ```
///
/// Runtime: O(log(toExclusive - fromInclusive))
///
/// Space: O(1)
///
/// *Runtime and space assumes that `predicate` runs in O(1) time and space.
public func findInRangeBinarySearch(fromInclusive : Int, toExclusive : Int, predicate : Int -> Bool) : ?Int {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Implementation LGTM. I wonder if it might be difficult for developers / LLMs to understand when/how to correctly use this function. Maybe renaming to findInRangeSorted() could help clarify?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I do have similar feelings on the naming here (somehow, no matter how you call it, it won't be completely compelling). Find in range sorted would make sense when calling it on some array/list etc., but would seem a bit off when using it to binary search on an abstract predicate like when computing a square root with binary search (ranges are already sorted, so the sorted here would refer to the predicate being "sorted"). Perhaps the most theoretical name would be findInRangeMonotonePredicate or findInRangeMonotone. The latter actually doesn't sound that bad (it's basically your suggestion but abstracting away the sortedness into monotonicity, which is what the method ultimately needs). Wdyt?

Leaving the naming aside, I think it's actually a good idea to make the docstring more "useful" (i.e., with standard use-cases like binary searching on an array and binary searching for the square root). Would that perhaps also help? This could still have a downside: if we later merge a PR like yours introducing collection-specific binary-search methods (which would be nice to have because of inlining and removing some bloat from the interface for those specific use-cases), users might be tempted to use the method in the enhanced docstring rather than looking up the collection-specific method.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we could merge #375 first, since we would include those functions either way. I like the idea of showing more real-world-like examples in the doc comments.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That works from my side. I am wondering whether we then want to also make the functions there do "find first" (C++-like) instead of "return position where it would be inserted" (Rust-like). It's true though that you will be able to do "find first" with these Int/Nat functions anyway, so maybe the diversity/inconsistency is actually good.

var l = fromInclusive;
var r = toExclusive;
while (l < r) {
let mid = l + (r - l) / 2;
if (predicate mid) {
r := mid
} else {
l := mid + 1
}
};
if (r < toExclusive) {
?r
} else {
null
}
}
}
58 changes: 58 additions & 0 deletions src/Nat.mo
Original file line number Diff line number Diff line change
Expand Up @@ -569,4 +569,62 @@ module {
}
};

/// Returns the first value in the range of `Nat` values [fromInclusive, toExclusive) for which `predicate` returns true.
/// If no element satisfies the predicate (or the range is empty), returns null.
///
/// ```motoko include=import
///
/// assert Nat.findInRange(3, 9, func(x) { x > 7 }) == ?8;
/// assert Nat.findInRange(3, 8, func(x) { x > 7 }) == null;
/// assert Nat.findInRange(3, 8, func(x) { x < 7 }) == ?3;
/// ```
///
/// Runtime: O(toExclusive - fromInclusive)
///
/// Space: O(1)
///
/// *Runtime and space assumes that `predicate` runs in O(1) time and space.
public func findInRange(fromInclusive : Nat, toExclusive : Nat, predicate : Nat -> Bool) : ?Nat {
for (element in range(fromInclusive, toExclusive)) {
if (predicate element) {
return ?element
}
};
null
};

/// Same as `findInRange()`, but requires that `predicate` is non-decreasing on [fromInclusive, toExclusive).
/// Returns the first value in the range of `Nat` values [fromInclusive, toExclusive) for which `predicate` returns true.
/// If no element satisfies the predicate (or the range is empty), returns null.
/// If `predicate` is not non-decreasing on the interval, the result is undefined.
///
/// ```motoko include=import
///
/// assert Nat.findInRangeBinarySearch(3, 9, func(x) { x > 7 }) == ?8;
/// assert Nat.findInRangeBinarySearch(3, 8, func(x) { x > 7 }) == null;
/// Nat.findInRangeBinarySearch(3, 8, func(x) { x < 7 }); // Undefined result: `predicate` is not non-decreasing.
/// ```
///
/// Runtime: O(log(toExclusive - fromInclusive))
///
/// Space: O(1)
///
/// *Runtime and space assumes that `predicate` runs in O(1) time and space.
public func findInRangeBinarySearch(fromInclusive : Nat, toExclusive : Nat, predicate : Nat -> Bool) : ?Nat {
var l = fromInclusive;
var r = toExclusive;
while (l < r) {
let mid = (l + r) / 2;
if (predicate mid) {
r := mid
} else {
l := mid + 1
}
};
if (r < toExclusive) {
?r
} else {
null
}
}
}
33 changes: 33 additions & 0 deletions test/Int.test.mo
Original file line number Diff line number Diff line change
Expand Up @@ -951,6 +951,8 @@ run(
)
);

/* --------------------------------------- */

do {
Debug.print("range()");

Expand Down Expand Up @@ -1012,6 +1014,37 @@ do {
assert Array.fromIter(Int.rangeByInclusive(1, 2, -1)) == []
};

do {
Debug.print("findInRange()");
assert Int.findInRange(-3, -3, func(x) { x > 7 }) == null;
assert Int.findInRange(-3, 9, func(x) { x > 7 }) == ?8;
assert Int.findInRange(-3, 8, func(x) { x > 7 }) == null;
assert Int.findInRange(3, 8, func(x) { x < 7 }) == ?3;
assert Int.findInRange(-5, -3, func(x) { x > -5 }) == ?-4;
let v : [Int] = [7, 3, 10, 3, 17, 10, 3];
assert Int.findInRange(0, v.size(), func(x) { v[Int.toNat(x)] == 7 }) == ?0;
assert Int.findInRange(0, v.size(), func(x) { v[Int.toNat(x)] == 3 }) == ?1;
assert Int.findInRange(0, v.size(), func(x) { v[Int.toNat(x)] == 10 }) == ?2;
assert Int.findInRange(0, v.size(), func(x) { v[Int.toNat(x)] == 17 }) == ?4
};

do {
Debug.print("findInRangeBinarySearch()");
assert Int.findInRangeBinarySearch(-3, -3, func(x) { x > 7 }) == null;
assert Int.findInRangeBinarySearch(-3, 9, func(x) { x > 7 }) == ?8;
assert Int.findInRangeBinarySearch(-3, 8, func(x) { x > 7 }) == null;
assert Int.findInRangeBinarySearch(3, 8, func(x) { x < 7 }) == ?3;
assert Int.findInRangeBinarySearch(-5, -3, func(x) { x > -5 }) == ?-4;
// Stress-test binary search against linear search.
for (i in Int.range(-10, 10)) {
for (j in Int.range(-10, 10)) {
for (val in Int.range(-11, 11)) {
assert Int.findInRangeBinarySearch(i, j, func(x) { x >= val }) == Int.findInRange(i, j, func(x) { x >= val })
}
}
}
};

/* --------------------------------------- */

run(
Expand Down
33 changes: 33 additions & 0 deletions test/Nat.test.mo
Original file line number Diff line number Diff line change
Expand Up @@ -96,4 +96,37 @@ test(
assert Array.fromIter(Nat.rangeByInclusive(3, 0, 0)) == [];
assert Array.fromIter(Nat.rangeByInclusive(3, 3, 0)) == [3]
}
);

test(
"findInRange",
func() {
assert Nat.findInRange(0, 0, func(x) { x > 7 }) == null;
assert Nat.findInRange(3, 9, func(x) { x > 7 }) == ?8;
assert Nat.findInRange(3, 8, func(x) { x > 7 }) == null;
assert Nat.findInRange(3, 8, func(x) { x < 7 }) == ?3;
let v = [7, 3, 10, 3, 17, 10, 3];
assert Nat.findInRange(0, v.size(), func(x) { v[x] == 7 }) == ?0;
assert Nat.findInRange(0, v.size(), func(x) { v[x] == 3 }) == ?1;
assert Nat.findInRange(0, v.size(), func(x) { v[x] == 10 }) == ?2;
assert Nat.findInRange(0, v.size(), func(x) { v[x] == 17 }) == ?4
}
);

test(
"findInRangeBinarySearch",
func() {
assert Nat.findInRangeBinarySearch(0, 0, func(x) { x > 7 }) == null;
assert Nat.findInRangeBinarySearch(3, 9, func(x) { x > 7 }) == ?8;
assert Nat.findInRangeBinarySearch(3, 8, func(x) { x > 7 }) == null;
assert Nat.findInRangeBinarySearch(3, 8, func(x) { x < 7 }) == ?3;
// Stress-test binary search against linear search.
for (i in Nat.range(0, 10)) {
for (j in Nat.range(0, 10)) {
for (val in Nat.range(0, 11)) {
assert Nat.findInRangeBinarySearch(i, j, func(x) { x >= val }) == Nat.findInRange(i, j, func(x) { x >= val })
}
}
}
}
)
4 changes: 4 additions & 0 deletions validation/api/api.lock.json
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,8 @@
"public func compare(x : Int, y : Int) : Order.Order",
"public func div(x : Int, y : Int) : Int",
"public func equal(x : Int, y : Int) : Bool",
"public func findInRange(fromInclusive : Int, toExclusive : Int, predicate : Int -> Bool) : ?Int",
"public func findInRangeBinarySearch(fromInclusive : Int, toExclusive : Int, predicate : Int -> Bool) : ?Int",
"public func fromNat(nat : Nat) : Int",
"public func fromText(text : Text) : ?Int",
"public func greater(x : Int, y : Int) : Bool",
Expand Down Expand Up @@ -618,6 +620,8 @@
"public func compare(x : Nat, y : Nat) : Order.Order",
"public func div(x : Nat, y : Nat) : Nat",
"public func equal(x : Nat, y : Nat) : Bool",
"public func findInRange(fromInclusive : Nat, toExclusive : Nat, predicate : Nat -> Bool) : ?Nat",
"public func findInRangeBinarySearch(fromInclusive : Nat, toExclusive : Nat, predicate : Nat -> Bool) : ?Nat",
"public func fromInt(int : Int) : Nat",
"public func fromText(text : Text) : ?Nat",
"public func greater(x : Nat, y : Nat) : Bool",
Expand Down
Loading