/// A sequence of integers that can be read by position.
/// Returns the number of elements.
/// Returns the element at position `i`, which is less than `count()`.
fun element(at i: Int) -> Int
/// Returns the sum of the elements, and whether it was computed by this
/// default implementation.
/// Every sequence gets this implementation, which reads each element in turn,
/// unless it provides its own.
fun sum() -> {Int, Bool} {
&total += self.element(at: i)
/// `value`, `times` times over.
struct Repetition is Sequence & Deinitializable {
fun count() -> Int { self.times.copy() }
fun element(at i: Int) -> Int { self.value.copy() }
/// The integers from `start` up to, but not including, `end`.
struct Range is Sequence & Deinitializable {
fun count() -> Int { self.end - self.start }
fun element(at i: Int) -> Int { self.start + i }
// The sum of a range has a closed form: no need to read every element.
fun sum() -> {Int, Bool} { ((self.start + self.end - 1) * self.count() / 2, false) }
/// Returns the average of the elements of `s`, which is not empty.
fun average<T is Sequence>(s: T) -> Int {
/// Returns whether the sum of `s` is computed by the default implementation.
fun sums_by_default<T is Sequence>(s: T) -> Bool {
let r = Repetition(value: 7, times: 3)
precondition(r.sum().0 == 21)
let n = Range(start: 1, end: 101)
precondition(n.sum().0 == 5050)
// Generic code calls the implementation of each type: `Range`'s own `sum`.
precondition(average(Range(start: 1, end: 11)) == 5)
precondition(sums_by_default(r))
precondition(!sums_by_default(n))