Skip to content

Commit

Permalink
Implement 'Collection.first_position(where:)'
Browse files Browse the repository at this point in the history
  • Loading branch information
kyouko-taiga committed Aug 5, 2024
1 parent 5eedd68 commit 9338c0e
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
13 changes: 13 additions & 0 deletions StandardLibrary/Sources/Core/Collection.hylo
Original file line number Diff line number Diff line change
Expand Up @@ -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<E>(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.
///
Expand Down
6 changes: 6 additions & 0 deletions Tests/LibraryTests/TestCases/CollectionTests.hylo
Original file line number Diff line number Diff line change
Expand Up @@ -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<Int>()
&a.append(1)
Expand Down Expand Up @@ -50,6 +55,7 @@ fun test_all_satisfy() {

public fun main() {
test_count()
test_first_position()
test_reduce()
test_contains_where()
test_all_satisfy()
Expand Down

0 comments on commit 9338c0e

Please sign in to comment.