OxL Reference

V.2 Types, errors, iterators

A utility that counts words in a file.

oxl✓ checked in CI
use std.io { File }
use std.os { args }

const TOP_N = 10                      // a named constant instead of a "magic" number

@error data Usage { msg: str }        // @error: an error type, it cannot be ignored

// pure is a function without effects: no network, no files
fn countWords(text: str) -> Map<str, u64> pure {
  var counts: Map<str, u64> = {:}     // {:} is an empty map, {} is an empty block
  for w in text.splitWhitespace() where w.len() > 2 {   // where is a filter right in the loop
    counts[w.lower()] = (counts.get(w.lower()) ?? 0) + 1
  }
  counts                              // the last expression of the block is the function's result
}

// The result is either () or one of the errors: Usage or IoError
fn main() -> () | Usage | IoError  io {
  // no argument — fail immediately returns the error from main
  let path = args().get(1) ?? fail Usage{ msg: "usage: wc <file>" }
  let text = File.readText(path)?     // ? propagates IoError upwards
  // An in-memory query expression: a lazy iter<str>
  let top = from (w, n) in countWords(text) order by n desc take TOP_N select "{w}: {n}"
  for line in top { print(line) }
}

Source: docs/spec/oxl-standard.en.md