compiler: rename compilation dir as `nit_compile`
[nit.git] / lib / counter.nit
index 3d1555b..befce9c 100644 (file)
@@ -35,7 +35,7 @@ import poset
 # assert c.max    == "b" # because "b" has the most count (3)
 # assert c.avg    == 2.0 # because it is the mean of the counts
 # ~~~~
-class Counter[E: Object]
+class Counter[E]
        super Map[E, Int]
 
        # Total number of counted occurrences
@@ -53,14 +53,14 @@ class Counter[E: Object]
        redef fun iterator do return map.iterator
 
        # The number of counted occurrences of `e`
-       redef fun [](e: E): Int
+       redef fun [](e)
        do
                var map = self.map
                if map.has_key(e) then return map[e]
                return 0
        end
 
-       redef fun []=(e: E, value: Int)
+       redef fun []=(e, value)
        do
                sum -= self[e]
                self.map[e] = value
@@ -93,6 +93,22 @@ class Counter[E: Object]
                for e in es do inc(e)
        end
 
+       # Decrement the value of `e` by 1
+       fun dec(e: E) do
+               if not has_key(e) then
+                       self.map[e] = 0
+               else
+                       self.map[e] = self[e] - 1
+                       sum += - 1
+               end
+       end
+
+       # Decrement the value for each element of `es`
+       fun dec_all(es: Collection[E])
+       do
+               for e in es do dec(e)
+       end
+
        # A new Counter initialized with `inc_all`.
        init from(es: Collection[E])
        do
@@ -181,7 +197,8 @@ class Counter[E: Object]
        fun max: nullable E do
                var max: nullable Int = null
                var elem: nullable E = null
-               for e, v in map do
+               for e in map.keys do
+                       var v = map[e]
                        if max == null or v > max then
                                max = v
                                elem = e
@@ -201,7 +218,8 @@ class Counter[E: Object]
        fun min: nullable E do
                var min: nullable Int = null
                var elem: nullable E = null
-               for e, v in map do
+               for e in map.keys do
+                       var v = map[e]
                        if min == null or v < min then
                                min = v
                                elem = e
@@ -238,7 +256,7 @@ class Counter[E: Object]
        end
 end
 
-private class CounterComparator[E: Object]
+private class CounterComparator[E]
        super Comparator
        redef type COMPARED: E
        var counter: Counter[E]