#1392 persistent collections pod released

ilya Mon 17 Jan 2011

Overview

Collections pod provides a set of general-purpose persistent collections. The key feature of these collections is that all of them are const clasess which return a copy on modification. The main trick is the fact, that no full copy is produced, still the old link continues to reference the old version of the collection, i.e. a partial copy takes place to boost the speed of operations.

The basic idea is taken from Clojure

Collection classes can be compiled to Javascript

This pod uses constArray pod with the simple native array class for the performance needs.

The base item is a const mixin ConstColl, it provides a lot of iterable list-like methods like each, findAll, exclude and so on.

Other collection mixins are ConstColl descendants.

  • ConstSeq is a mixin for a constant sequence of objects.
  • ConstList mixin provides constant list routings.
  • ConstMap is a mixin for constant maps. It has two implementations provided: ConstHashSet and ConstTreeSet.
  • And there is a constant set mixin ConstSet, it is based on ConstMap, and therefore has two implementations as well: ConstHashSet and ConstTreeSet

Repositories:

Examples

ConstList

n := 10000
cList := ConstList.empty
n.times { cList = cList.add(it) }
verifyEq(cList.size, n)
verifyEq(cList.reduce(0) |Int r, Int v -> Int | { r+=v }, (n-1) * n / 2)
verifyEq(list[0..0].toList, Obj?[0])
verifyEq(list[0..-1].size, n)
list = list.removeAt(n / 2)
verifyEq(list.size, n - 1)

ConstMap

map := ConstHashMap.empty // or ConstTreeMap.empty
map = map[1] = 1
map = map[2] = 2
map = map[3] = 3
fMap := map.toMap
verifyEq(fMap, Obj:Obj?[1:1,2:2,3:3])

map = ConstHashMap.empty // or ConstTreeMap.empty
count := 100
count.times
{
  map = map[count - it] = it.toStr
  verifyEq(map.size, it+1)
}
count.times
{
  verifyEq(map[count - it], it.toStr)
}
verifyEq(map.keys.toList.sort, Obj?[,].addAll((1..count).toList))
verifyEq(map.findAll |x| { x->key != 1 }.toList.size, count - 1)

ConstSet

emptySet := ConstHashSet.empty // or ConstTreeSet.empty
set := emptySet.add(1) 
verifyEq(Obj?[1], set.toList)
set = set.addAll([2,3])
verifyEq(Obj?[1,2,3], set.toList)

set = emptySet.addAll([1,2,2,2,3,3])
Obj? val := null
set = set.remove(2) {val = it}
verifyEq(Obj?[1,3], set.toList)
verifyEq(val, 2)

verifyEq(emptySet.addAll([,]), emptySet)
verifyNotEq(emptySet, null)

verifyEq(emptySet.addAll([1]), emptySet.addAll([1]))
verifyEq(emptySet.addAll([1,2,3]), emptySet.addAll([1,3,2]))
verifyEq(emptySet.addAll([1,2,2]), emptySet.addAll([2,2,1]))
verifyEq(emptySet.addAll([1,3,3,4]), emptySet.addAll([4,1,3]))

Login or Signup to reply.