1% This example illustrates the use of associative arrays.
2% The function 'analyse_file' counts the number of occurrences of each word
3% in a specified file.  Once the file has been read in, it writes out
4% the list of words and number of occurrences to the file counts.log
5
6define analyse_file (file)
7{
8   variable fp = fopen (file, "r");
9   if (fp == NULL)
10     throw OpenError, "Unable to open $file"$;
11
12   % Create an Integer_Type assoc array with default value of 0.
13   variable a = Assoc_Type[Integer_Type, 0];
14
15   variable line, word;
16   while (-1 != fgets (&line, fp))
17     {
18	foreach word (strtok (strlow(line), "^\\w"))
19	  a[word] = a[word] + 1;    %  default value of 0 assumed!!
20     }
21   () = fclose (fp);
22
23   variable keys = assoc_get_keys (a);
24   variable values = assoc_get_values (a);
25
26   % The default array_sort for Int_Type is an ascending sort.  We want the
27   % opposite.
28   variable i = array_sort (values; dir=-1);
29
30   fp = fopen ("count.log", "w");
31   () = array_map (Int_Type, &fprintf, fp, "%s:\t%d\n", keys[i], values[i]);
32   () = fclose (fp);
33}
34