Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I implement a fixed size List in Scala?

Tags:

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 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.

like image 228
deltanovember Avatar asked Aug 15 '11 03:08

deltanovember


People also ask

How do I create a list in Scala?

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.

Are lists immutable in Scala?

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.

How do you add elements to a list in Scala?

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”.


1 Answers

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)

}
like image 120
deltanovember Avatar answered Sep 22 '22 05:09

deltanovember