Almac snippets

ortfero

Small pieces of almac for everyday tasks, grouped by topic and ordered from the simplest. Each one is a complete fragment of a module body: its imports come first, and the functions go below the module's ... line. The language itself is described in the almac language report [1].

[1] Almac language report

1. Basics

Say hello.

import 'core/devices/tty

hello fn () {
  tty.say "hello, aldan";
}

Return a value. The last expression is the result.

square fn (x int) -> int {
  x * x;
}

Name a constant. A name and a value make one; no keyword.

import 'core/devices/tty

limit = 100
greeting = "hi"

show fn () {
  tty.say greeting, " ", limit;
}

Use locals. They follow the signature and start at zero.

average fn (a int, b int) -> int
  var sum int {
  sum = a + b;
  sum / 2;
}

Branch with if.

sign fn (x int) -> int {
  if x > 0 {
    return 1;
  } else if x < 0 {
    return -1;
  }
  0;
}

Choose a value with an if expression.

larger fn (a int, b int) -> int
  var r int {
  r = if a > b { a; } else { b; };
  r;
}

Count with a for loop.

import 'core/devices/tty

count fn (n int)
  var i int {
  for i < n; i += 1 {
    tty.say i;
  }
}

Loop until a condition, with break.

first_power fn (limit int) -> int
  var p int {
  p = 1;
  for {
    if p >= limit { break; }
    p = p * 2;
  }
  p;
}

Combine conditions with and, or, not.

is_digit fn (c byte) -> bool {
  and (c >= '0'), (c <= '9');
}

is_blank fn (c byte) -> bool {
  or (c == ' '), (c == 9), (c == 10);
}

Convert between number types with as.

ratio fn (part int, whole int) -> double {
  (part as double) / (whole as double);
}

Return two results through var parameters.

divide fn (a int, b int, var q int, var r int) {
  q = a / b;
  r = a mod b;
}

use fn ()
  var q int, r int {
  divide 17, 5, var q, var r;
}

2. Text

Print mixed values on one line.

import 'core/devices/tty

report fn (name string, score int, ok bool) {
  tty.say name, ": ", score, " ok=", ok;
}

Print without a line break.

import 'core/devices/tty

progress fn (done int, total int) {
  tty.sayin done, "/", total, " ";
}

Format values into a buffer.

import 'core/base/text, 'core/base/bytes

label fn (var buffer [32]byte, n int) -> string
  ! bytes.fault {
  text.format var buffer, "item #", n;
}

Parse a number.

import 'core/base/signed, 'core/base/boolean, 'core/base/bytes

number fn (s string) -> int
  ! boolean.fault | bytes.fault {
  signed.parse s;
}

Parse with a fallback instead of a failure.

import 'core/base/signed, 'core/base/boolean, 'core/base/bytes

number_or fn (s string, fallback int) -> int {
  return signed.parse s;
on boolean.fault | bytes.fault:
  return fallback;
}

Compare strings.

import 'core/base/bytes

is_yes fn (answer string) -> bool {
  bytes.equal answer, "yes";
}

Find a byte in a string.

import 'core/base/bytes

has_dot fn (name string) -> bool {
  (bytes.find name, '.') >= 0;
}

Walk the bytes of a string.

count_spaces fn (s string) -> int
  var i int, n int {
  for i < (length s); i += 1 {
    if s[i] == ' ' { n += 1; }
  }
  n;
}

Take a part of a string.

first_word fn (s string) -> const string
  var i int {
  for and (i < (length s)), (s[i] != ' ') {
    i += 1;
  }
  s[0:i];
}

Upper-case a string in place.

shout fn (var s string)
  var i int {
  for i < (length s); i += 1 {
    if and (s[i] >= 'a'), (s[i] <= 'z') {
      s[i] = s[i] - 32;
    }
  }
}

Read a line from the operator.

import 'core/devices/tty

greet fn ()
  var buffer [64]byte, name string {
  name = tty.ask "name? ", var buffer;
  tty.say "hello, ", name;
}

3. Numbers

Clamp a value.

import 'core/base/signed

clamp fn (x int, lo int, hi int) -> int {
  signed.max lo, (signed.min x, hi);
}

Compute a distance.

import 'core/base/float

distance fn (x double, y double) -> double {
  float.sqrt ((x * x) + (y * y));
}

Round a real to an integer.

import 'core/base/signed

percent fn (part double) -> int {
  signed.round (part * 100.0);
}

Format a real.

import 'core/base/float, 'core/base/bytes

show fn (var buffer [32]byte, x double) -> string
  ! bytes.fault {
  float.format var buffer, x;
}

Roll a die.

import 'core/base/random, 'core/system/clock, 'core/base/boolean

roll fn () -> int
  ! boolean.fault
  var r random.state {
  random.seed var r, ((clock.now) as int);
  random.range var r, 1, 6;
}

4. Arrays and slices

Sum an array.

sum fn (xs []int) -> int
  var i int, total int {
  for i < (length xs); i += 1 {
    total += xs[i];
  }
  total;
}

Fill a local array, then pass it as a slice.

sum fn (xs []int) -> int ...

squares fn () -> int
  var a [10]int, i int {
  for i < 10; i += 1 {
    a[i] = i * i;
  }
  sum a;
}

sum fn (xs []int) -> int
  var i int, total int {
  for i < (length xs); i += 1 {
    total += xs[i];
  }
  total;
}

Look up a constant table. The first element gives the element type; a prefix such as []byte writes another one.

days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31,
  30, 31]
names = ["jan", "feb", "mar"]
widths = []byte [3, 5, 8]

days_in fn (month int) -> int {
  days[month - 1];
}

Find the largest element.

largest fn (xs []int) -> int
  var i int, best int {
  best = xs[0];
  i = 1;
  for i < (length xs); i += 1 {
    if xs[i] > best { best = xs[i]; }
  }
  best;
}

Reverse an array in place.

reverse fn (var xs []int)
  var i int, j int, t int {
  j = (length xs) - 1;
  for i < j; i += 1 {
    t = xs[i];
    xs[i] = xs[j];
    xs[j] = t;
    j -= 1;
  }
}

Copy and clear bytes.

import 'core/base/bytes

backup fn (src string, var dst [64]byte) {
  bytes.clear var dst;
  bytes.copy src, var dst;
}

Take any number of arguments.

total fn (xs ...int) -> int
  var i int, t int {
  for i < (length xs); i += 1 {
    t += xs[i];
  }
  t;
}

use fn () -> int {
  total 1, 2, 3, 4;
}

5. Records, enums and unions

Declare and use a record. A name and its structure make a type; no keyword.

point record { x int, y int }

manhattan fn (a point, b point) -> int
  var dx int, dy int {
  dx = a.x - b.x;
  dy = a.y - b.y;
  if dx < 0 { dx = -dx; }
  if dy < 0 { dy = -dy; }
  dx + dy;
}

Change a record through a var parameter.

point record { x int, y int }

move_by fn (var p point, dx int, dy int) {
  p.x += dx;
  p.y += dy;
}

Build a record into an into parameter.

point record { x int, y int }

origin fn (into p point) {
  p.x = 0;
  p.y = 0;
}

Keep a constant record. Its type comes first, as a prefix.

point record { x int, y int }

corner = point {x: 79, y: 24}

Dispatch on an enum.

light enum red | amber | green

next fn (l light) -> light
  var r light {
  when l {
  * light.red: r = light.green;
  * light.green: r = light.amber;
  * light.amber: r = light.red;
  }
  r;
}

Dispatch on a union.

shape union circle { r double }
  | rect { w double, h double }

area fn (s shape) -> double {
  when s {
  * shape.circle: return 3.14159 * s.r * s.r;
  * shape.rect: return s.w * s.h;
  }
  0.0;
}

Build a union value through its subtype.

shape union circle { r double }
  | rect { w double, h double }

area fn (s shape) -> double {
  guard s shape.rect | return 0.0;
  s.w * s.h;
}

unit_square fn () -> double
  var r shape.rect {
  r.w = 1.0;
  r.h = 1.0;
  area r;
}

Give a number its own type.

meters from int
meters.mile = 1609

walk fn (steps int) -> meters {
  (steps * 3 / 4) as meters;
}

6. Failures

Declare a failure and raise one of its kinds.

fault failure { empty, too_long }

check fn (s string)
  ! fault {
  if (length s) == 0 { raise fault.empty; }
  if (length s) > 64 { raise fault.too_long; }
}

Handle a kind, let the rest propagate.

fault failure { empty, too_long }

check fn (s string)
  ! fault ...

size_of fn (s string) -> int
  ! fault {
  check s;
  return length s;
on fault.empty:
  return 0;
}

check fn (s string)
  ! fault {
  if (length s) == 0 { raise fault.empty; }
  if (length s) > 64 { raise fault.too_long; }
}

Catch anything with the unnamed handler.

import 'core/devices/tty

safely fn (work fn () ! ...) {
  work;
on ...:
  tty.say "work failed";
}

Name the failure that was caught.

import 'core/devices/tty

explain fn (work fn () ! ...) {
  work;
on ... with f:
  tty.say "failed: ", (mirror.fault_name_of f), ".",
    (mirror.fault_kind_of f);
}

Clean up on every exit with defer.

import 'core/devices/tty

framed fn (work fn () ! ...)
  ! ... {
  tty.say "begin";
  defer tty.say "end";
  work;
}

Narrow an optional pointer with guard.

node record { next ^node|none, value int }

first_value fn (head ^node|none) -> int {
  guard head | return -1;
  head^.value;
}

7. Bits

Test and set single bits.

toggle_low fn (flags dword)
  var f dword {
  f = flags;
  f[0] = not f[0];
  f;
}

Read and write a bit field.

high_nibble fn (b byte) -> byte {
  b[4:8];
}

with_high_nibble fn (b byte, v byte) -> byte
  var r byte {
  r = b;
  r[4:8] = v;
  r;
}

Mask with and, combine with or.

low_byte fn (v dword) -> dword {
  and v, (0xff as dword);
}

merge fn (a dword, b dword) -> dword {
  or a, b;
}

Shift, xor and count bits.

import 'core/base/bit

parity fn (v dword) -> bool {
  ((bit.ones v) mod 2) == 1;
}

mix fn (a dword, b dword) -> dword {
  bit.xor (bit.shil a, 7), (bit.shir b, 3);
}

8. Memory

Claim and release a heap block.

import 'core/system/heap

grid [64]int

scratch fn ()
  ! heap.fault
  var g ^grid {
  g = heap.claim grid;
  defer heap.release from g;
  g^[0] = 1;
}

Push onto a linked list.

import 'core/system/heap

node record { next ^node|none, value int }

push fn (from head ^node|none, v int) -> ^node
  ! heap.fault
  var n ^node {
  n = heap.claim node;
  n^.next = head;
  n^.value = v;
  n;
}

Walk a linked list without taking it.

node record { next ^node|none, value int }

sum fn (head ^node|none) -> int
  var total int {
  for with n = head; n.next {
    total += n.value;
  }
  total;
}

Alias a deep place once with with.

cell record { hits int, misses int }

record_hit fn (var cells [16]cell, i int) {
  with c = cells[i];
  c.hits += 1;
}

Read memory through a raw address.

import 'core/base/octet

first_byte fn (at int) -> byte {
  octet.peek (at as address);
}

9. Collections

Grow an array of numbers.

import 'core/collections/array, 'core/system/heap

evens fn (var a array.ty)
  ! heap.fault
  var i int, cell [1]int {
  array.create var a, 64;
  for i < 10; i += 1 {
    cell[0] = i * 2;
    array.append var a, (cell as []byte);
  }
}

at fn (a array.ty, i int) -> int
  var xs const []int {
  xs = (array.view a) as []int;
  xs[i];
}

Map keys to values with a hash table.

import 'core/collections/table, 'core/system/heap,
  'core/base/boolean

key record { id int }
value record { score int }

score fn (t table.ty, id int) -> int
  var k key, found string {
  k.id = id;
  found = table.get t, (k as []byte);
  if (length found) == 0 { return 0; }
  found as int;
}

remember fn (var t table.ty, id int, score int)
  ! heap.fault | boolean.fault
  var k key, v value {
  k.id = id;
  v.score = score;
  table.put var t, (k as []byte), (v as []byte);
}

Mark seen items in a bitset.

import 'core/collections/bitset, 'core/system/heap

dedup fn (xs []int) -> int
  ! heap.fault
  var seen bitset.ty, i int, n int {
  bitset.create into seen, 1024;
  defer bitset.dispose from seen;
  for i < (length xs); i += 1 {
    if not (bitset.test seen, xs[i]) {
      bitset.set var seen, xs[i];
      n += 1;
    }
  }
  n;
}

10. Files and directories

Check that a file exists.

import 'core/storage/file

has_config fn () -> bool {
  file.is_exist "config.dano";
}

Print a file.

import 'core/storage/file, 'core/devices/tty

cat fn (path string)
  ! file.fault
  var buffer [512]byte, view []byte, final f file.id {
  f = file.open path;
  defer file.close from f;
  view = file.read f, var buffer;
  for (length view) > 0; view = file.read f,
    var buffer {
    tty.sayin view;
  }
}

Write a new file.

import 'core/storage/file

save fn (path string, data string) ! file.fault
  var f file.id {
  f = file.create path;
  defer file.close from f;
  file.write f, data;
}

Append a line to a log.

import 'core/storage/file

log fn (line string)
  ! file.fault
  var newline [1]byte
  final f file.id {
  f = if file.is_exist 'log.txt {
    file.append 'log.txt;
  } else {
    file.create 'log.txt;
  };
  defer file.close from f;
  newline[0] = 10;
  file.write f, line;
  file.write f, newline;
}

List a directory.

import 'core/storage/directory, 'core/storage/file, 'core/devices/tty

ls fn (path string) ! file.fault
  var e directory.entry, more bool
  final h directory.id {
  h = directory.open path;
  defer directory.close from h;
  more = directory.next h, var e;
  for more; more = directory.next h, var e {
    tty.say e.name[0:e.length];
  }
}

Build a path.

import 'core/storage/path, 'core/devices/tty

show_join fn (dir string, name string)
  var buffer [256]byte, n int {
  n = path.join var buffer, dir, name;
  tty.say buffer[0:n];
}

11. Time

Measure elapsed time.

import 'core/system/clock, 'core/devices/tty

timed fn (work fn ())
  var t clock.tick {
  t = clock.now;
  work;
  tty.say (clock.elapsed_ms t), " ms";
}

Print the date and time.

import 'core/system/time, 'core/devices/tty, 'core/base/bytes

now fn ()
  ! bytes.fault
  var buffer [64]byte {
  tty.say (time.format var buffer, time.now);
}

Read the calendar fields.

import 'core/system/time

year fn () -> int
  var cal time.calendar {
  time.decompose time.now, var cal;
  cal.year;
}

Pause and let other tasks run.

import 'core/system/task

wait_a_second fn () {
  task.sleep 1000;
}

12. Screen and keys

Draw a box and wait for esc.

import 'core/devices/screen, 'core/system/event, 'core/system/heap,
  'core/base/boolean

show fn ()
  ! heap.fault | boolean.fault
  var pump event.pump, k screen.key,
  final sf ^screen.surface {
  sf = heap.claim screen.surface;
  defer heap.release from sf;
  screen.snapshot;
  defer screen.restore;
  screen.clear var sf^;
  screen.frame var sf^, 10, 5, 30, 8;
  screen.print var sf^, 12, 7, "press esc";
  screen.blit sf^, screen.normal;
  event.keys var pump;
  for {
    if (event.next var pump, var k) == event.kind.key {
      if k.code == screen.key_esc { break; }
    }
  }
}

Dispatch on key chords.

import 'core/devices/screen

quit = screen.ctrl_q
save = screen.ctrl_s

act fn (k screen.key) -> int
  var r int {
  when k.chord {
  * quit: r = 1;
  * save: r = 2;
  * else: r = 0;
  }
  r;
}

13. Network

Send a datagram.

import 'core/net/socket, 'core/net/ipv4, 'core/base/bytes

ping fn (port int)
  ! socket.fault | bytes.fault
  var host int
  final s socket.id {
  host = ipv4.parse '10.0.2.2;
  s = socket.open 0;
  defer socket.close from s;
  socket.send s, (socket.endpoint host, port), 'ping;
}

Receive a datagram.

import 'core/net/socket, 'core/devices/tty

listen fn (port int)
  ! socket.fault
  var buffer [512]byte, n int, from_ep int,
  final s socket.id {
  s = socket.open port;
  defer socket.close from s;
  n = socket.receive s, var buffer, var from_ep;
  tty.say "got ", n, " bytes from port ",
    (socket.port_of from_ep);
}

14. Hashing and crypto

Hash bytes.

import 'core/crypto/rapidhash

fingerprint fn (data string) -> dword {
  rapidhash.of data;
}

Take a cryptographic digest.

import 'core/crypto/ascon, 'core/base/boolean

digest fn (data string, var out [32]byte)
  ! boolean.fault {
  ascon.hash data, var out;
}

15. Services and tests

Run a periodic background service.

import 'core/system/service, 'core/system/heap, 'core/devices/tty

beat fn () {
  tty.say "tick";
}

halt fn () {}

start fn ()
  ! service.fault | heap.fault {
  service.periodic "beat", fn beat, 1000, fn halt;
}

Write a spec for a module.

import 'core/tools/spec

verify fn ()
  ! spec.fault

...

square fn (x int) -> int {
  x * x;
}

verify fn ()
  ! spec.fault {
  spec.expect ((square 3) == 9);
  spec.expect ((square -2) == 4);
}