Tin

Examples · 12 of 339

12-words

Strings and maps: count the words in a text.

examples/12-words.tintin run examples/12-words.tin
// Strings and maps: count the words in a text.

let TEXT = "the cat sat on the mat and the dog sat on the log"

type Count = { word: string, n: int }

fn main() {
  var counts: Map<string, int> = newMap()
  for word in TEXT.split(" ") {
    counts.set(word, counts.get(word).or(0) + 1)
  }

  var rows: Count[] = []
  for word, n in counts {
    rows.push(Count { word: word, n: n })
  }
  let ranked = rows.sortBy((a, b) => a.n > b.n || (a.n == b.n && a.word < b.word))

  for row in ranked.slice(0, 5) {
    print("{row.word.padRight(5, " ")} {"#".repeat(row.n)} {row.n}")
  }

  print("longest word: {TEXT.split(" ").reduce("", (best, w) => if w.len > best.len { w } else { best })}")
  print("title: {TEXT.slice(0, 11).upper()}")
  print("mentions a dog? {TEXT.contains("dog")}")
}
the   #### 4
on    ## 2
sat   ## 2
and   # 1
cat   # 1
longest word: the
title: THE CAT SAT
mentions a dog? true