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 functionality 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.
Syntax for defining a Scala List. val variable_name: List[type] = List(item1, item2, item3) or val variable_name = List(item1, item2, item3) A list in Scala is mostly like a Scala array. However, the Scala List is immutable and represents a linked list data structure.
In "Programming in scala" it is stated that lists are immutable and arrays are mutable. But I can't change the array length -- neither can I with list, so in this way they are both immutable. I can change array's element value -- just setting a new one, and I can modify a list's element value with, say, map method.
This is the first method we use to append Scala List using the operator “:+”. The syntax we use in this method is; first to declare the list name and then use the ':+' method rather than the new element that will be appended in the list. The syntax looks like “List name:+ new elements”.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With