From 9338c0e9e18b4b28e0f5db0fb1129f833be29c02 Mon Sep 17 00:00:00 2001 From: Dimi Racordon Date: Mon, 5 Aug 2024 11:50:33 +0200 Subject: [PATCH] Implement 'Collection.first_position(where:)' --- StandardLibrary/Sources/Core/Collection.hylo | 13 +++++++++++++ Tests/LibraryTests/TestCases/CollectionTests.hylo | 6 ++++++ 2 files changed, 19 insertions(+) diff --git a/StandardLibrary/Sources/Core/Collection.hylo b/StandardLibrary/Sources/Core/Collection.hylo index 8597b30e6..11c6a243b 100644 --- a/StandardLibrary/Sources/Core/Collection.hylo +++ b/StandardLibrary/Sources/Core/Collection.hylo @@ -37,6 +37,19 @@ public extension Collection { return r } + /// Returns the position of the first element of `self` satisfying `predicate`, or + /// `end_position()` if no such element exists. + /// + /// - Complexity: O(n), where n is the number of elements in `self`. + public fun first_position(where predicate: [E](Element) -> Bool) -> Position { + var i = start_position() + let j = end_position() + while (i != j) && !predicate(self[i]) { + &i = self.position(after: i) + } + return i + } + /// Returns the result of applying `combine` on an accumulator, initialized with `initial_value`, /// and each element of `self`, in order. /// diff --git a/Tests/LibraryTests/TestCases/CollectionTests.hylo b/Tests/LibraryTests/TestCases/CollectionTests.hylo index 57267c21f..4c8b97f3c 100644 --- a/Tests/LibraryTests/TestCases/CollectionTests.hylo +++ b/Tests/LibraryTests/TestCases/CollectionTests.hylo @@ -18,6 +18,11 @@ fun test_count() { precondition(a.count() == 64) } +fun test_first_position() { + let a = 4 + precondition(a.first_position(where: fun (_ x) { x.copy() }) == 2) +} + fun test_reduce() { var a = Array() &a.append(1) @@ -50,6 +55,7 @@ fun test_all_satisfy() { public fun main() { test_count() + test_first_position() test_reduce() test_contains_where() test_all_satisfy()