Examples
Count the words in a file
 previous   up   next 

This example counts the words from the standard input file and writes a list with words and the corresponding count

$ include "seed7_05.s7i";       # Standard Seed7 library
  include "scanfile.s7i";       # Import the getSimpleSymbol function

const type: wordHash is hash [string] integer;

const proc: main is func
  local
    var wordHash: numberOfWords is wordHash.EMPTY_HASH;
    var string: symbol is "";
  begin
    while not eof(IN) do
      symbol := getSimpleSymbol(IN);
      if symbol in numberOfWords then
        incr(numberOfWords[symbol]);
      else
        numberOfWords @:= [symbol] 1;
      end if;
    end while;
    for symbol range sort(keys(numberOfWords)) do
      writeln(symbol rpad 20 <& " " <& numberOfWords[symbol]);
    end for;
  end func;

The type 'hash [string] integer' describes a hash table. Hash tables contain a collection of values which can be accessed by an index. In contrast to an array a hash allows a wider range of possible key types. In case of 'hash [string] integer' the key type is string and the element type is integer.

The hash 'numberOfWords' is used to count the words (=symbols). Symbols are read from the standard input 'IN' with the scanner function getSimpleSymbol(IN). Every 'symbol' is checked with the in operator for presence in 'numberOfWords'. The @:= statement inserts a value into a hash table at the place specified with a key. With 'numberOfWords @:= [symbol] 1;' the integer value 1 is inserted to 'numberOfWords' at the place specified with 'symbol'. With 'numberOfWords[symbol]' the hash table element with the key 'symbol' is obtained. The procedure incr increments the the given variable (in this case 'numberOfWords[symbol]'). The keys function delivers an unordered array of keys from 'numberOfWords'. The resulting array string is sorted with the 'sort' function.


 previous   up   next