TWiki . Doc . HashBeginnerExample

/* Please try the NoviceExamples before the BeginnerExamples
To compile:
   nicec --sourcepath=.. -a hash.jar hash
To run:
   java -jar hash.jar 150

void main(String[] args){
   var n = toSingleInt(args);
   let nKeys = 10000;

   HashMap<String,Cell> table1 = new HashMap(nKeys);
   HashMap<String,Cell> table2 = new HashMap();
   for (int i = 0; i <= nKeys; i++) 
      table1["foo_" + i] = new Cell(value: i);

   String key;
   int v1;        
   ?Cell c2;      // c2 = table2[key] can be null 

   while (n-- > 0) 
     for (each : table1.entrySet()) {
         key = each.getKey;
         v1 = each.getValue.value;                       
         if ( (c2 = table2[key]) != null)
            c2.value += v1;   
            table2[key] = new Cell(value: v1);
   print("" + table1["foo_1"]);
   print(" " + table1["foo_9999"]);
   print(" " + table2["foo_1"]);
   println(" " + table2["foo_9999"]);

class Cell { int value; }

toString(Cell c) = c.value.toString();

int toSingleInt(String[] s){
   try { return Integer.parseInt(s[0]); }
   catch (Exception e){ return 1; } }

/* Notes - language
Compare with Java at the "Win32 Language Shootout"

   var n = toSingleInt(args);
Declare variable n, the compiler will infer the variable type
from the return type of the package function toSingleInt(String[] s)

   let nKeys = 10000;
Declare constant nKeys, the compiler will infer the constant type
from the literal value.

   HashMap<String,Cell> table1 = new HashMap(nKeys);
Declare and initialize table1 with type parameter <String,Cell>
HashMap<String,Cell> keys are type String and values are type Cell

   for (Map.Entry<String, Cell> entry : table1.entrySet()) {
Using the enhanced for loop to iterate over the map entries.

This is equivalent to table2.get(key)

   class Cell { int value; }
Define a new class Cell, with a single field. Using a Cell
in the HashMap allows entries to be updated without using

   String key;
Declare variable key with type String (that excludes null values)

   ?Cell c2;
Declare variable c2 as an Option Type with type Cell or null.

   toString(Cell c) = c.value.toString()
Implement the toString method for the class Cell using the short return syntax.
Note that the method is implemted outside the class.

   int toSingleInt(String[] s){
Define a package function


-- IsaacGouy? - 26 Aug 2003

----- Revision r1.6 - 10 Jan 2004 - 19:03 GMT - IsaacGouy
Copyright © 1999-2003 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback.