Skip to content

Commit

Permalink
Merge pull request #1551 from hylo-lang/collection-algorithms
Browse files Browse the repository at this point in the history
Implement some algorithms on `Collection`
  • Loading branch information
kyouko-taiga authored Aug 31, 2024
2 parents e2af44c + d4eacda commit 816c569
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
34 changes: 34 additions & 0 deletions StandardLibrary/Sources/Core/Collection.hylo
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,28 @@ 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 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 Expand Up @@ -63,3 +85,15 @@ public extension Collection {
}

}

public extension Collection where Element: Equatable {

/// Returns the position of the first element of `self` that is equal to `needle`, or
/// `end_position()` if no such element exists.
///
/// - Complexity: O(n), where n is the number of elements in `self`.
public fun first_position(of needle: Element) -> Position {
first_position(where: fun (_ e) { e == needle })
}

}
26 changes: 26 additions & 0 deletions Tests/LibraryTests/TestCases/CollectionTests.hylo
Original file line number Diff line number Diff line change
@@ -1,5 +1,29 @@
//- 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_first_position() {
let a = 4
precondition(a.first_position(where: fun (_ x) { x.copy() }) == 2)
precondition(a.first_position(of: true) == 2)
}

fun test_reduce() {
var a = Array<Int>()
&a.append(1)
Expand Down Expand Up @@ -31,6 +55,8 @@ 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 816c569

Please sign in to comment.