Tin

Examples · 28 of 339

28-chars

char: one Unicode character.

examples/28-chars.tintin run examples/28-chars.tin
// char: one Unicode character. 'a' is a char, "a" is a string.
//
// s.chars() decodes a string into chars; positions in a string still count bytes.

/// Is this a valid robot name: a letter, then letters, digits or '-'?
fn validName(s: string): bool {
  let cs = s.chars()
  if cs.len == 0 || !cs[0].isLetter() { return false }
  for c in cs {
    if !(c.isLetter() || c.isDigit() || c == '-') { return false }
  }
  true
}

/// A Caesar shift on ASCII letters; everything else stays.
fn shift(s: string, by: int): string {
  var out: char[] = []
  for c in s.chars() {
    let base = if c.isLower() { int('a') } else if c.isUpper() { int('A') } else { -1 }
    out.push(if base < 0 { c } else { char(base + (int(c) - base + by) % 26) })
  }
  fromChars(out)
}

fn kind(c: char): string => match c {
  v if ['a', 'e', 'i', 'o', 'u'].contains(v) => "vowel",
  ' ' => "space",
  _ => if c.isDigit() { "digit" } else { "other" },
}

fn main() {
  for name in ["arm-2", "2arm", "señor", "bad name"] {
    print("{name}: {validName(name)}")
  }
  print(shift("Hello, Tin!", 3))
  print(shift(shift("Hello, Tin!", 3), 23))
  print("ñ€😀".chars().map((c) => int(c)))
  print(kind('e'))
  print(kind('7'))
  let counts = setOf("mississippi".chars())
  print(counts)
  print(sort("tin".chars()))
}
arm-2: true
2arm: false
señor: true
bad name: false
Khoor, Wlq!
Hello, Tin!
[241, 8364, 128512]
vowel
digit
{'m', 'i', 's', 'p'}
['i', 'n', 't']