✦ som
Learn
Introduction A tour of som
Guides
Errors Compile-time code dyn Shaders The web
Elsewhere
GitHub Examples

A tour of som

Som from the start, one feature at a time. Each section is a whole program, and each one compiles and runs: put it in a folder as main.som and run som run folder.

Contents

  • A tour of som
    • Contents
    • 1. Hello
    • 2. Values and numbers
    • 3. Text
    • 4. Functions
    • 5. Control flow
    • 6. Arrays, slices, lists and maps
    • 7. Structs and methods
    • 8. Enums and match
    • 9. Optionals
    • 10. Errors
    • 11. Ownership and references
    • 12. Shared values
    • 13. Generics
    • 14. Traits
    • 15. Closures and function values
    • 16. dyn
    • 17. Aliases and distinct types
    • 18. Modules
    • 19. Contracts
    • 20. Typestate
    • 21. Compile-time code
    • 22. Tests
    • 23. C libraries
    • 24. Shaders
    • 25. All together: guess a number

1. Hello

A program is a folder with a main.som. som run hello compiles it and runs it. println comes from som::io.

use som::io;

println("Hello, world!");

2. Values and numbers

Variables are immutable unless they're declared with mut. A number written out takes whatever type it's used as, and is an i32 (or an f64) where nothing else says. Number types never convert by themselves: as does it.

use som::io;

let answer = 42;            // an `i32`: a whole number, where nothing says otherwise
let mut count = 0;          // `mut` to change it later
count += 1;
count = count * 10;

let small: u8 = 200;        // the type written out
let ratio = 0.5;            // an `f64`
let precise: f32 = 640;     // a whole number can be a float, where it's exact
let yes = true;

// `as` converts between number types.
let total = small as i32 + answer;
let half = answer as f64 * ratio;

println("{count} {total} {half} {precise} {yes}");   // 10 242 21 640 true

3. Text

string is text. Writing {…} inside text puts a value there; that works for anything that implements Display.

use som::io;

let name = "som";
let version = 1;

// `{…}` in text puts a value there: anything `Display`.
let greeting = "Hello from {name} {version}, {name.len} letters long";
println(greeting);

// Text joins with `+`, and compares with `==`.
let shout = name + "!";
if shout == "som!" { println(shout); }

// Pieces of it, and its bytes.
let world = "hello, world".slice(7, 12) else "";
let mut ls = 0;
for b in "hello".bytes if b == 'l' as u8 { ls += 1; }
let trimmed = "  padded  ".trim();
println("{world} {ls} {trimmed}");   // world 2 padded

4. Functions

A block gives back its last expression, so short functions need no return. A function whose body is one expression writes it after =.

use som::io;

/// The last expression of a block is what it gives.
fn add(a: i32, b: i32) -> i32 {
    a + b
}

/// One expression: written after `=`.
fn square(x: i32) -> i32 = x * x;

/// Nothing to give: no `->`.
fn greet(name: string) {
    println("Hi, {name}");
}

/// Functions can share a name, told apart by what they take.
fn describe(x: i32) -> string = "a number";
fn describe(x: bool) -> string = "a yes or no";

/// A `mut` parameter is a copy to change.
fn countdown(mut n: i32) -> i32 {
    while n > 0 { n -= 1; }
    n
}

greet("som");
println("{add(2, 3)} {square(4)} {countdown(5)}");   // 5 16 0
println(describe(1));
println(describe(true));

5. Control flow

if is an expression. for goes over ranges and anything iterable, and can take a condition after what it goes over.

use som::io;

let n = 7;

// `if` gives a value, as a block or on one line.
let size = if n > 5 { "big" } else { "small" };
let parity = "even" if n % 2 == 0 else "odd";
println("{size} and {parity}");

// `for` over a range: 0, 1, 2, 3, 4.
let mut sum = 0;
for i in 0..5 { sum += i; }

// A condition after the range only runs the body when it holds.
for i in 0..10 if i % 3 == 0 { println("{i} divides by 3"); }

// `while`, and `loop` until a `break`.
let mut x = 1;
while x < 100 { x = x * 2; }
let mut tries = 0;
loop {
    tries += 1;
    if tries == 3 { break; }
}
println("{sum} {x} {tries}");   // 10 128 3

6. Arrays, slices, lists and maps

Indexing with [i] compiles only where the index is proven to be in range. Otherwise, use get, which gives an optional (chapter 9).

use som::io;

/// A slice, `&[i32]`, is a view of any number of them: an array's, a list's, or part of one.
fn sum(numbers: &[i32]) -> i32 {
    let mut total = 0;
    for n in numbers { total += n; }
    total
}

// An array: a fixed number of values, `[i32; 5]`.
let mut numbers = [1, 2, 3, 4, 5];
numbers[0] = 10;                         // the index is known to be in range
let zeros = [0; 3];                      // three zeros

// An index that might not be in range is asked for: `get` gives `none` past the end.
let past = numbers.get(9) else -1;

// Part of it: `slice` gives `none` if the range doesn't fit.
let middle = numbers.slice(1..4) else [];

// A list grows: `List<T>`.
let mut list: List<i32> = List::empty();
for i in 0..5 { list.push(i * i); }
let last = list.pop() else 0;

// A map finds a value by its key.
let mut ages: Map<string, i32> = Map::empty();
ages.insert("Ada", 36);
ages.insert("Alan", 41);
let name = "Ada";
let age = ages.get(&name);               // `none` if the key isn't there
if age { println("{name} is {*age}"); }

// Each with its position.
for x in list.with_index() { println("{x.index}: {x.value}"); }

println("{sum(&numbers)} {sum(middle)} {past} {last} {list.len} {zeros.len}");

7. Structs and methods

Methods go in impl blocks. Inside a method, .w means self.w. A prop reads like a field but is worked out each time it's read.

use som::io;

struct Rect {
    w: f64,
    h: f64,
}

impl Rect {
    /// No `self`: called as `Rect::square(2.0)`.
    fn square(side: f64) -> Rect = Rect { w: side, h: side };

    /// `&self` reads it, and `.w` is `self.w`.
    fn area(&self) -> f64 = .w * .h;

    /// `&mut self` changes it.
    fn grow(&mut self, by: f64) {
        .w += by;
        .h += by;
    }

    /// A property: read like a field, worked out each time.
    prop is_square: bool = .w == .h;
}

let mut r = Rect { w: 3.0, h: 4.0 };
r.grow(1.0);
let s = Rect::square(2.0);
println("{r.area()} {r.is_square} {s.is_square}");   // 20 false true

// Fields given by a variable of the same name.
let w = 1.0;
let h = 2.0;
let thin = Rect { w, h };
println("{thin.area()}");

8. Enums and match

An enum is one of its variants, and each variant can hold its own values. A match must handle every variant, and gives a value.

use som::io;

/// Each variant can hold values of its own.
enum Shape {
    Circle(f64),
    Rect { w: f64, h: f64 },
    Empty,
}

/// `match` has to cover every variant, and gives a value.
fn area(shape: &Shape) -> f64 = match shape {
    Circle(r) => 3.14 * r * r,
    Rect { w, h } => w * h,
    Empty => 0.0,
};

enum Direction { North, East, South, West }

impl Direction {
    fn turned_right(self) -> Direction = match self {
        North => Direction::East,
        East => Direction::South,
        South => Direction::West,
        West => Direction::North,
    };
}

/// A field every variant has is read without a `match`.
enum Animal {
    Dog { name: string, good: bool },
    Cat { name: string, lives: i32 },
}

let shapes = [Shape::Circle(1.0), Shape::Rect { w: 2.0, h: 3.0 }, Shape::Empty];
for s in &shapes { println("{area(s)}"); }

// `_` stands for the rest.
let facing = Direction::West.turned_right();
let up = match facing {
    North => true,
    _ => false,
};

let pet = Animal::Cat { name: "Tom", lives: 9 };
println("{up} {pet.name}");

9. Optionals

There's no null. T? is a T or none, and has to be checked before use: after an if checks it, it's the value itself, and else gives a fallback.

use som::io;

/// `T?` is a `T`, or `none`.
fn find(numbers: &[i32], want: i32) -> usize? {
    for x in numbers.with_index() {
        if x.value == want { return x.index; }
    }
    none
}

struct User { name: string, nickname: string? }

let numbers = [4, 8, 15, 16];

// `else` gives a fallback in its place.
let at = find(&numbers, 15) else 99;

// Inside an `if` that checks it, it's the value itself.
let maybe = find(&numbers, 23);
if maybe {
    println("found at {maybe}");
} else {
    println("not there");
}

// `else` can also leave.
let user = User { name: "Ada", nickname: none };
let called = user.nickname else user.name;
println("{at} {called}");

10. Errors

T! is a T or a failure, and any Display value can be a failure. What each function can fail with is worked out from its body, so nothing has to be converted between libraries. A T! can't be ignored: dropping one is a compile error.

use som::io;

/// `T!` is a `T`, or why there isn't one. Anything `Display` is a why.
fn parse_age(text: string) -> u32! {
    let age = u32::parse(text) else fail "`{text}` is no number";
    if age > 150 { fail "{age} is too old"; }
    age
}

/// `else fail "…"` passes a failure on, saying what was being done.
fn ages(texts: &[string]) -> u32! {
    let mut total = 0;
    for t in texts {
        total += parse_age(*t) else fail "reading the ages";
    }
    total
}

/// A failure of a type of its own, to tell apart in a `match`.
struct TooYoung { age: u32 }

impl Display for TooYoung {
    prop display_len: usize = "too young".len;
    fn display(&self, to: *u8) { "too young".display(to); }
}

fn check(age: u32) -> u32! {
    if age < 18 { fail TooYoung { age }; }
    age
}

// The program can fail too: `?` here prints why, and exits with 1.
let age = parse_age("42")?;
println("{age}");

// `else` gives a fallback, `else e =>` names the failure.
let bad = parse_age("old") else e => {
    println("error: {e}");
    0
};

match check(12) {
    age => println("ok, {age}"),
    fail TooYoung { age } => println("{age} is too young"),
    fail e => println("{e}"),
}

let total = ages(&["30", "x"]) else e => { println("{e}"); 0 };

11. Ownership and references

Each value has one owner. Passing it by value moves it; & and &mut lend it. The compiler checks that nothing is used after it's moved and that nothing borrowed outlives what it borrows. Cleanup goes in Drop, so there's no defer to forget.

use som::io;

struct Point { x: i32, y: i32 }

/// `&` lends it to read, `&mut` lends it to change. Nothing is copied.
fn length(numbers: &List<i32>) -> usize = numbers.len;
fn add_one(numbers: &mut List<i32>) { numbers.push(1); }

/// Taking it as it is takes it over: the caller can't use it after.
fn consume(numbers: List<i32>) -> usize = numbers.len;

/// Filled in by the function: `out p` makes the variable.
fn origin(p: &mut Point) { *p = Point { x: 0, y: 0 }; }

/// Cleanup belongs to the type: `drop` runs when a value goes away, last made first.
struct Say { text: string }

impl Drop for Say {
    fn drop(&mut self) { println("bye {.text}"); }
}

let mut numbers: List<i32> = List::empty();
add_one(&mut numbers);
add_one(&mut numbers);
println("{length(&numbers)}");      // 2
let n = consume(numbers);           // `numbers` is moved: using it now is an error

origin(out p);
println("{n} {p.x}");

let a = Say { text: "a" };
let b = Say { text: "b" };
// prints `bye b`, then `bye a`

12. Shared values

When a value really needs several owners, #T (Rc<T>) counts its copies and drops the value with the last one.

use som::io;
use som::mem;

/// `#T` is a value shared by its copies, and dropped with the last one.
struct Node { value: i32, next: #Node? }

fn total(node: #Node) -> i32 {
    let rest = node.get().next;
    node.get().value + (total(rest) if rest else 0)
}

let last: #Node = Rc::new(Node { value: 4, next: none });
let first = Rc::new(Node { value: 3, next: last });
let also = Rc::new(Node { value: 1, next: last });   // `last` is shared, not moved
println("{total(first)} {total(also)}");            // 7 5

13. Generics

Type parameters, and value parameters such as N: usize. Both are worked out from use where possible. Generic code is compiled separately for each type it's used with.

use som::io;

/// A type parameter: `Stack<i32>`, `Stack<string>`, …
struct Stack<T> { items: List<T> }

impl<T> Stack<T> {
    fn new() -> Stack<T> = Stack { items: List::empty() };
    fn push(&mut self, item: T) { .items.push(item); }
    fn pop(&mut self) -> T? = .items.pop();
}

/// A value parameter: the size is part of the type.
struct Buffer<N: usize> { bytes: [u8; N], len: usize }

impl<N: usize> Buffer<N> {
    fn new() -> Buffer<N> = Buffer { bytes: [0; N], len: 0 };
    fn capacity(&self) -> usize = N;
}

/// Worked out from what it's given: `N` from the array.
fn sum<N: usize>(numbers: [i32; N]) -> i32 {
    let mut total = 0;
    for n in numbers { total += n; }
    total
}

fn largest<T: Compare + Copy>(a: T, b: T) -> T = a if a > b else b;

let mut stack: Stack<string> = Stack::new();
stack.push("a");
stack.push("b");
let top = stack.pop() else "";

let small: Buffer<16> = Buffer::new();
println("{top} {small.capacity()} {sum([1, 2, 3])} {largest(2.5, 1.0)}");   // b 16 6 2.5

14. Traits

A trait says what a type can do, and generic code asks for it with a bound (S: Shape). Operators, comparison and writing into text are all traits.

use som::io;

/// What a type can do: implemented for each type on its own.
trait Shape {
    pub fn area(&self) -> f64;
    /// A default, which an implementation can replace.
    pub fn describe(&self) -> string = "a shape of {self.area()}";
}

struct Square { side: f64 }
struct Circle { r: f64 }

impl Shape for Square {
    fn area(&self) -> f64 = .side * .side;
}

impl Shape for Circle {
    fn area(&self) -> f64 = 3.14 * .r * .r;
    fn describe(&self) -> string = "a circle";
}

/// Any `S` that's a `Shape`: compiled once for each type it's used with.
fn total<S: Shape>(shapes: &[S]) -> f64 {
    let mut sum = 0.0;
    for s in shapes { sum += s.area(); }
    sum
}

/// Operators are traits too: `+` is `Add`, `==` is `Eq`, `<` is `Compare`.
struct Vec2 { x: f64, y: f64 }

impl Add for Vec2 {
    fn add(&self, other: &Vec2) -> Vec2 = Vec2 { x: .x + other.x, y: .y + other.y };
}

/// And `Display` says how it's written into text.
impl Display for Vec2 {
    prop display_len: usize = "({.x}, {.y})".len;
    fn display(&self, to: *u8) { "({.x}, {.y})".display(to); }
}

let squares = [Square { side: 1.0 }, Square { side: 2.0 }];
println("{total(&squares)}");                         // 5
println(Circle { r: 1.0 }.describe());
println(Square { side: 3.0 }.describe());

let v = Vec2 { x: 1.0, y: 2.0 } + Vec2 { x: 3.0, y: 4.0 };
println("{v}");                                       // (4, 6)

15. Closures and function values

A plain function is a value of type fn(…) -> …. A closure that captures variables is taken by a type parameter bounded by fn(…) instead.

use som::io;

/// A function is a value: `fn(i32) -> i32`.
fn double(x: i32) -> i32 = x * 2;

fn twice(f: fn(i32) -> i32, x: i32) -> i32 = f(f(x));

/// A closure can capture what's around it, so it's taken as anything callable that way.
fn apply<F: fn(i32) -> i32>(f: F, x: i32) -> i32 = f(x);

struct Button { clicks: i32, on_click: fn(i32) -> i32 }

println("{twice(double, 3)}");                       // 12

let step = 5;
let add_step = (x: i32) => x + step;
println("{apply(add_step, 1)}");                     // 6

// Iterators take closures too: `n => …` for short.
let numbers = [1, 2, 3, 4, 5, 6];
let evens = numbers.count(n => n % 2 == 0);
let doubled: i32 = numbers.where(n => n > 3).map(n => n * 2).sum();
println("{evens} {doubled}");                        // 3 30

// A field can hold a function, and be called like a method.
let button = Button { clicks: 0, on_click: double };
println("{button.on_click(21)}");                    // 42

16. dyn

Generics pick the type while compiling. A dyn Trait picks it as the program runs, so one list can hold several types. It owns its value, on the heap.

use som::io;

trait Speak {
    pub fn speak(&self) -> string;
}

struct Dog {}
struct Robot { id: i32 }

impl Speak for Dog { fn speak(&self) -> string = "Woof"; }
impl Speak for Robot { fn speak(&self) -> string = "Beep {.id}"; }

/// A `dyn Speak` is any value implementing `Speak`: which one is known only as it runs.
fn pick(friendly: bool) -> dyn Speak {
    if friendly { return Dog {}; }
    Robot { id: 7 }
}

let mut voices: List<dyn Speak> = List::empty();
voices.push(Dog {});
voices.push(Robot { id: 1 });
voices.push(pick(false));
for v in &voices { println(v.speak()); }

17. Aliases and distinct types

type A = B is just another name. type A = distinct B is a new type made like B: it keeps B's operators, but the two can't be mixed without as.

use som::io;

/// An alias: another name for the same type.
type Grid = [[u8; 3]; 3];

/// A distinct type: made like an `f64`, but a type of its own. Meters and seconds don't mix.
type Meters = distinct f64;
type Seconds = distinct f64;

fn speed(d: Meters, t: Seconds) -> f64 = (d as f64) / (t as f64);

let grid: Grid = [[0; 3]; 3];
let d = 100.0 as Meters;
let t = 9.58 as Seconds;
let further = d + d;               // its operators give a `Meters` back
println("{speed(further, t)} {grid.len}");
// `speed(t, d)` doesn't compile.

18. Modules

A folder next to main.som is a module, and use loads it. Names are private to their module unless they're pub.

main.som:

use som::io;
use shapes;

let r = shapes::Rect::new(2.0, 3.0);
println("{r.area()}");

shapes/rect.som:

/// Every `.som` file in a folder is part of the module named after it: `shapes`.
pub struct Rect { w: f64, h: f64 }

impl Rect {
    /// `pub`: seen from outside the module. Without it, only inside.
    pub fn new(w: f64, h: f64) -> Rect = Rect { w, h };
    pub fn area(&self) -> f64 = .w * .h;
}

19. Contracts

Contracts are proven while compiling, not checked as the program runs. @require is what a function needs from its callers. @fact is what a function gives back, or what always holds for a struct. The same prover checks every [i].

use som::io;

/// Indexing is proven in range while compiling: here, `i < numbers.len` holds in the loop.
fn sum(numbers: &[i32]) -> i32 {
    let mut total = 0;
    for i in 0..numbers.len { total += numbers[i]; }
    total
}

/// `@require`: what a function needs, proven where it's called.
@require numbers.len > 0, "there's a last one"
fn last(numbers: &[i32]) -> i32 = numbers[numbers.len - 1];

/// `@fact` above a function: what's so of what it gives, `result`.
@require size > 0, "room for one"
@fact result < size
fn slot(hash: usize, size: usize) -> usize = hash % size;

/// `@fact` above a struct: what's so of every one, kept by each method.
@fact .count <= .limit
struct Counter { count: i32, limit: i32 }

impl Counter {
    @require limit >= 0
    fn new(limit: i32) -> Counter = Counter { count: 0, limit };

    fn add(&mut self) {
        if .count < .limit { .count += 1; }
    }
}

let numbers = [3, 1, 4, 1, 5];
let table = [0, 0, 0, 0];
let at = slot(13, table.len);
let mut c = Counter::new(1);
c.add();
c.add();
println("{sum(&numbers)} {last(&numbers)} {table[at]} {c.count}");   // 14 5 0 1
// `last` of an empty array doesn't compile: "`(&empty).len > 0` is false here".

20. Typestate

An enum value can be a type parameter, so a state can be part of a type. Each state has its own methods, and changing state consumes the old value, so a stale state can't be used.

use som::io;

/// The state is part of the type: a `Door<Closed>` has no `walk_through`.
enum DoorState { Open, Closed }

struct Door<S: DoorState> { name: string }

impl Door<Closed> {
    fn new(name: string) -> Door<Closed> = Door { name };
    fn open(self) -> Door<Open> = Door { name: self.name };
}

impl Door<Open> {
    fn walk_through(&self) { println("through the {.name} door"); }
    fn close(self) -> Door<Closed> = Door { name: self.name };
}

let door = Door::new("front");
let open = door.open();
open.walk_through();
let closed = open.close();
// `closed.walk_through()` doesn't compile, and neither does using `open` again.

21. Compile-time code

Som has no macros. Ordinary functions can run while compiling. @ marks what the compiler settles: @const, @assert, calls like @fib(20), and @for and @if, which decide what code exists. The spec is in compile-time-code.md.

use som::io;

/// An ordinary function.
fn fib(n: i64) -> i64 = n if n <= 1 else fib(n - 1) + fib(n - 2);

/// `@const` runs it while compiling: only the number ends up in the program.
@const FIB_19 = fib(19);

/// A table worked out while compiling.
fn squares() -> [i32; 10] {
    let mut table = [0; 10];
    for i in 0..10 { table[i] = (i * i) as i32; }
    table
}
@const SQUARES = squares();

/// A check while compiling: if it doesn't hold, the program won't compile.
@assert(FIB_19 == 4181, "fib(19) is 4181");

/// `@for` writes its body out once for each value, while compiling. Over a struct's fields,
/// `f` is each field: `value.f` the field, `@name(f)` its name. This works for any struct.
fn describe<T>(value: &T) -> string {
    let mut text = "";
    @for f in T { text = text + "{@name(f)}={value.f} "; }
    text
}

/// And over an enum's variants.
enum Color { Red, Green, Blue }

fn color_names() -> List<string> {
    let mut names: List<string> = List::empty();
    @for v in Color { names.push(@name(v)); }
    names
}

/// `@if` keeps only the branch it picks: here, per array size.
fn kind<N: usize>(values: &[i32; N]) -> string {
    @if N == 0 { return "empty"; }
    "{N} values"
}

struct Point { x: i32, y: i32 }

println("{FIB_19} {SQUARES[9]} {@fib(20)}");          // `@fib(…)` runs it here, while compiling
let p = Point { x: 1, y: 2 };
println(describe(&p));                               // x=1 y=2
for name in &color_names() { println(name); }
println(kind(&[1, 2, 3]));

22. Tests

som test folder runs each @test and reports ok or what failed. assert is an ordinary std function: called with @, as @assert, it checks while compiling instead.

/// `som test` runs each `@test` function, each in a process of its own; `som run` leaves
/// them out.
fn double(n: i32) -> i32 = n * 2;

@test
fn doubles() {
    assert(double(2) == 4);
    assert(double(-1) == -2, "negative numbers too");
}

23. C libraries

A C library can be used straight from its header. use extern "raylib"; reads raylib.h, writes its declarations out as som, and links the library. extern "c"; does the same for the C standard library, as c::… (used in the next chapter).

/// `use extern "raylib";` reads raylib's C header, `raylib.h`, into som: its functions,
/// structs, enums and constants, checked like any other code, and linked with the library.
use extern "raylib";

init_window(800, 450, "bouncing");
set_target_fps(60);

let mut x: f32 = 400.0;
let mut y: f32 = 225.0;
let mut dx: f32 = 4.0;
let mut dy: f32 = 3.0;

while !window_should_close() {
    x += dx;
    y += dy;
    if x < 20.0 || x > 780.0 { dx = -dx; }
    if y < 20.0 || y > 430.0 { dy = -dy; }
    if is_key_pressed(KeyboardKey::Space as i32) { dx = dx * 1.5; }

    begin_drawing();
    clear_background(Color::RAYWHITE);       // `#define`d colours are constants on `Color`
    draw_circle(x as i32, y as i32, 20.0, Color::MAROON);
    draw_text("space to speed up", 10, 10, 20, Color::DARKGRAY);
    end_drawing();
}
close_window();

24. Shaders

Shaders are written in som. A @fragment function, or a closure given where a shader is expected, is compiled to WGSL while compiling, along with everything it calls, and runs through WebGPU with the wgpu library that comes with som. som build --emit wgsl writes the WGSL out. @vertex shaders, meshes and compute kernels are in shaders.md.

use som::gpu;
use wgpu;

/// Uniforms: what the program hands a shader each frame.
struct Waves { pub time: f32 }

/// Runs on the GPU for each pixel. It's compiled to WGSL while compiling, and it's still an
/// ordinary som function: callable, and testable, on the CPU.
@fragment
fn stripes(frag: Fragment, u: &Waves) -> Vec4 {
    let k = 0.5 + 0.5 * ((frag.uv.x + frag.uv.y) * 10.0 + u.time).sin();
    vec4(k, k * 0.5, 1.0 - k, 1.0)
}

let mut gpu = wgpu::Gpu::open("shaders", 800, 450);
let mut striped: wgpu::Shader<Waves> = wgpu::Shader::fragment(stripes);
let mut overlay = wgpu::Shader::empty();

while gpu.frame() {
    let time = gpu.time();
    striped.fullscreen(&mut gpu, Waves { time });

    // A closure is a shader too: what it captures, `time`, becomes its uniforms.
    overlay.draw(&mut gpu, 100.0, 100.0, 200.0, 200.0, (frag) => vec4(1.0, 1.0, 1.0, 0.5 * frag.uv.y * time.sin().abs()));
    gpu.present();
}

25. All together: guess a number

A complete program: random numbers seeded with the time from C (extern "c";, which makes the C library available as c::…), reading input, optionals and a loop.

use som::io;
extern "c";

/// A seed that's different each run: the time, from C.
fn seed() -> u32 {
    let mut now: i64 = 0;
    c::time(&mut now);
    now as u32
}

let mut random = Random::new(seed());
let secret = random.below(20) + 1;
let mut tries = 6;
println("Guess a number between 1 and 20.");
loop {
    let line = read_line() else return 1;
    let guess = u32::parse(line.trim()) else {
        println("That wasn't a valid number, try again.");
        continue;
    };
    if guess == secret {
        println("You Win!");
        break;
    }
    println("Too Small" if guess < secret else "Too Large");
    tries = tries - 1;
    if tries == 0 {
        println("Game Over - the number was {secret}");
        break;
    }
}
println("Thank you for playing!");

Edit this page on GitHub