Skip to content

Commit

Permalink
Implement 'Collection.count'
Browse files Browse the repository at this point in the history
  • Loading branch information
kyouko-taiga committed Aug 5, 2024
1 parent f46bc7d commit 5eedd68
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
9 changes: 9 additions & 0 deletions StandardLibrary/Sources/Core/Collection.hylo
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,15 @@ public trait Collection {

public extension Collection {

/// Returns the number of elements in `self`.
///
/// - Complexity: O(n), where n is the number of elements in `self`.
public fun count() -> Int {
var r = 0
for let _ in self { &r += 1 }
return r
}

/// Returns the result of applying `combine` on an accumulator, initialized with `initial_value`,
/// and each element of `self`, in order.
///
Expand Down
19 changes: 19 additions & 0 deletions Tests/LibraryTests/TestCases/CollectionTests.hylo
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
//- compileAndRun expecting: .success

conformance Int: Collection {

public typealias Element = Bool
public typealias Position = Int

public fun start_position() -> Int { 0 }
public fun end_position() -> Int { Int.bit_width() }
public fun position(after p: Int) -> Int { p + 1 }

public subscript(_ p: Int): Bool { (self & (1 << p)) != 0 }

}

fun test_count() {
let a = 0
precondition(a.count() == 64)
}

fun test_reduce() {
var a = Array<Int>()
&a.append(1)
Expand Down Expand Up @@ -31,6 +49,7 @@ fun test_all_satisfy() {
}

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

0 comments on commit 5eedd68

Please sign in to comment.