Implement a custom collection in Scala that supports advanced operations.

Instruction: Provide an implementation of a custom collection in Scala, including support for advanced operations like map, filter, and custom aggregations.

Context: Tests the implementation of a custom collection API, transformation and aggregation semantics, and the distinction between composition and full collection-framework integration.

Updated

For a small domain API, compose an immutable collection and expose the operations actually required. This wrapper supports transformations and a sequential custom aggregation without pretending that aggregation runs in parallel.

final class Batch[+A] private (private val elements: Vector[A]) {
  def toVector: Vector[A] = elements
  def map[B](f: A => B): Batch[B] = Batch.from(elements.map(f))
  def filter(p: A => Boolean): Batch[A] = Batch.from(elements.filter(p))
  def foldLeft[B](initial: B)(step: (B, A) => B): B =
    elements.foldLeft(initial)(step)
}
object Batch {
  def from[A](values: IterableOnce[A]): Batch[A] =
    new Batch(values.iterator.toVector)
}
@main def batchExample(): Unit = {
  val input = scala.collection.mutable.ArrayBuffer(1, 2, 3)
  val original = Batch.from(input)
  input += 4
  val labels: Batch[String] = original.filter(_ % 2 == 1).map(_.toString)
  assert(original.toVector == Vector(1, 2, 3))
  assert(labels.toVector == Vector("1", "3"))
  assert(original.foldLeft(BigInt(0))((sum, n) => sum + n) == 6)
  assert(Batch.from(Vector.empty[Int]).foldLeft(7)(_ + _) == 7)
}

from snapshots collection structure, map can change the element type, and filter preserves order. Mutable element objects would still be shared. The input must be finite and must not change concurrently during construction. User-supplied functions can have effects or throw; the wrapper does not make them pure.

foldLeft processes elements in order and can use a non-associative step. A parallel aggregate would need a separate partition-combining operation and appropriate identity/associativity laws; floating-point rounding and effects can make regrouping observable.

This is a custom collection API built by composition, not a full subclass of Scala's collection framework. If inherited collection operations must preserve the custom result type, implement the appropriate IterableOps or SeqOps and factory/builder methods for the supported library version, and test transformed element types and empty results. Simply inheriting an iterable does not establish that contract. Custom collections and result types

Related Questions