How would I implement a fixed size List in Scala?
For example suppose I want a list that contains 0 up to a max of 1000 elements. Above this, the oldest insertions should be dropped first. Do collections support this f开发者_高级运维unctionality natively? If not how would I go about the implementation? I understand that certain operations are very slow on Lists so maybe I need a different data type?
Looking at an element should not affect the list. I would like insert and size operations only.
It sounds like you want a size-bounded queue. Here's a similar question: Maximum Length for scala queue
There are three solutions presented in that question. You can,
- Write a queue from scratch (paradigmatic gave code for this),
- Extend Scala's Queue implementation by subclassing, or
- Use the typeclass extension pattern (aka, "pimp my library") to extend Scala's
Queue
.
Here is my first pass implementation in case someone else find it useful
import scala.collection._
import mutable.ListBuffer
class FixedList[A](max: Int) extends Traversable[A] {
val list: ListBuffer[A] = ListBuffer()
def append(elem: A) {
if (list.size == max) {
list.trimStart(1)
}
list.append(elem)
}
def foreach[U](f: A => U) = list.foreach(f)
}
A circular array is the fastest implementation. It's basically an array with a read and write index which are wrapped when reaching the end of the array. Size is defined as:
def size = writeIndex - readIndex + (if (readIndex > writeIndex) array.size else 0)
While not an answer to the question's details (but does somewhat answer the question's title), List.fill(1000){0}
would create a List
of length 1000 with initial value of 0
, which is from
Scala - creating a type parametrized array of specified length
精彩评论