SultanC
  1. Home
  2. Examples
  3. Collections

Counting words with a text-keyed hash map

collections/word_count.sn
// Counting words with a text-keyed hash map.
import std.io.println;
import std.text.number;
import std.text.transform;
import std.collections.text_index_map;

def main(): int {
    let sentence: string = "the cat saw the dog and the bird";
    let separator: string = " ";
    let words: vector string = split(&sentence, &separator);
    let counts: mutable text_index_map = new_text_index_map();
    let i: mutable uint = 0;
    while (i < (length(words) as uint)) {
        let seen: mutable uint = 0;
        match text_index_map_get(&counts, &words[i]) with
        | option.some(so_far) -> { seen := so_far; }
        | option.none -> { };
        match text_index_map_insert(&mutable counts, clone(&words[i]), seen + 1) with
        | result.ok(_) -> { }
        | result.err(_) -> { return 1; };
        i := i + 1;
    }
    let the_word: string = "the";
    match text_index_map_get(&counts, &the_word) with
    | option.some(so_far) -> { println(uint_to_text(so_far)); }
    | option.none -> { println("0"); };
    println(uint_to_text(text_index_map_length(&counts)));
    return 0;
}

Run it

With the interpreter, without compiling:

./build/sultanc run examples/en/collections/word_count.sn

Or compile it to an executable:

./build/sultanc examples/en/collections/word_count.sn -o build/example && ./build/example

Source on GitHub   All examples