Skip to content
rux-langPublic

About

Examples written in the Rux programming language

Topics

Resources

Stars

4 stars

Watchers

1 watching

Forks

Latest commit

 

History

711 Commits

Folders and files

Repository files navigation

Rux Examples

Example projects and programming tutorials for the Rux language.

The Course

The course is read in order: each lesson is one package that teaches one idea, and assumes only the lessons before it. Each lesson has a page at https://rux-lang.dev/docs/learn/<lesson>. Parts 1–17 build the language step by step; Parts 18–26 tour the standard packages and can be read in any order once their prerequisites are done; Part 27 holds complete small programs.

1. Basics

First programs: printing, values and their types.

  • 1.1 Hello: print "Hello, World!", the minimal Rux application
  • 1.2 Comment: explain code with // and /* */ comments, which can nest
  • 1.3 Variable: name a value with let, and let the compiler infer its type
  • 1.4 Mutable: declare a binding with var so it can be reassigned
  • 1.5 Integer: whole numbers: signed and unsigned widths, int and uint
  • 1.6 Float: fractional numbers: float32, float64, and why 0.1 + 0.2 is not 0.3
  • 1.7 Boolean: true, false and the bool type
  • 1.8 Character: single characters, character literals and the char type
  • 1.9 Literal: write numbers in other bases, with separators and suffixes
  • 1.10 Console: write to the console with Print and PrintLine, and fill {} placeholders
  • 1.11 Const: name a value the compiler folds in, and see where it differs from let
  • 1.12 Convert: convert between numeric types with as, and see what a value that does not fit becomes

2. Operators

Combining values into new ones.

  • 2.1 Arithmetic: add, subtract, multiply, divide and take the remainder
  • 2.2 Comparison: compare two values with ==, !=, <, <=, > and >=
  • 2.3 Logical: combine conditions with &&, || and !
  • 2.4 Assignment: update a variable in place with +=, -=, ++ and friends
  • 2.5 Precedence: which operator binds first, and how parentheses change it

3. Control flow

Choosing and repeating.

  • 3.1 If: run code only when a condition holds, with if and else
  • 3.2 ElseIf: choose one of several branches with an else if chain
  • 3.3 Ternary: pick one of two values inside an expression with an if value, since Rux has no ? :
  • 3.4 While: repeat while a condition holds, possibly zero times
  • 3.5 DoWhile: run the body first and test afterwards, so it runs at least once
  • 3.6 Loop: repeat forever with loop until a break leaves
  • 3.7 Break: leave a loop early when the answer is found
  • 3.8 Continue: skip the rest of one iteration and carry on with the next
  • 3.9 Range: describe a run of numbers with .. and ..=
  • 3.10 For: walk a range with for
  • 3.11 Label: name a loop, so break can leave an outer one
  • 3.12 Match: select a branch by value with match, and catch the rest with _
  • 3.13 MatchExpression: use match as a value, not only as a statement
  • 3.14 Block: use a plain block { ... } as a scope of its own and as a value that yields its last expression, and parenthesize one in a condition

4. Functions

Naming a piece of work and reusing it.

  • 4.1 Function: declare functions with parameters and a return value, and call them
  • 4.2 Return: return early, and write functions that return nothing
  • 4.3 Recursion: a function that calls itself, and the base case that stops it
  • 4.4 Overload: give several functions one name, and let the arguments choose between them
  • 4.5 DefaultArgument: give a parameter a default value so callers may leave it out, and name an argument to skip the defaults before it
  • 4.6 Generic: write one function that works for many types
  • 4.7 Callback: pass a function to another function as an ordinary value

5. Sequences

Many values of one type, and groups of values of different types.

  • 5.1 Array: an inline array holding a fixed number of values of one type
  • 5.2 Greetings: an array of strings in twelve languages, walked with for: Unicode text works out of the box
  • 5.3 ArrayRepeat: fill an array with one repeated value: [0; 16]
  • 5.4 ArrayNested: arrays of arrays: a grid with rows and columns
  • 5.5 Slice: view part of an array without copying it, and pass it to a function
  • 5.6 WritableSlice: change an array through a var T[..] view
  • 5.7 Variadic: accept any number of arguments, the way PrintLine does
  • 5.8 Tuple: group a few values without declaring a type, and return more than one result
  • 5.9 Destructure: unpack a tuple into separate names with let (x, y) = ...

6. Types

Declaring types of your own.

  • 6.1 Struct: group related values into a struct with named fields
  • 6.2 Reference: borrow a value with &T instead of copying it, and see when the call writes the loan as &x
  • 6.3 MutableReference: let a function change the caller's value through &var T
  • 6.4 Method: give a struct behaviour with extend and a &self receiver
  • 6.5 MutatingMethod: a method that changes its receiver through &var self
  • 6.6 Constructor: build a valid value in one place with a named constructor such as Time::New
  • 6.7 Extension: add methods to a type you did not write
  • 6.8 Enum: name a fixed set of cases
  • 6.9 EnumValue: give an enum an explicit underlying type and convert to and from it
  • 6.10 Variant: attach data to each case
  • 6.11 VariantMatch: take a variant apart in a match arm
  • 6.12 TypeAlias: give an existing type a second name to make a signature read clearly
  • 6.13 FunctionField: store a function in a struct field and call it later

7. Patterns

Everything a match arm can say.

  • 7.1 Guard: add an if condition to a match arm
  • 7.2 RangePattern: match a whole range of numbers in one arm
  • 7.3 TuplePattern: match several values at once as a tuple
  • 7.4 StructPattern: take a struct-shaped variant case apart by field name
  • 7.5 CharacterPattern: match single characters
  • 7.6 Exhaustive: why a match must cover every value: name every case of a variant, and end an integer match with _

8. Optionals

A value that may be absent: T?.

  • 8.1 Optional: a value that may be missing: int? and none
  • 8.2 Presence: match an optional with value? and none arms, or ask only whether it is there with == none and != none
  • 8.3 IfLet: bind a present value in a condition with if let value? = optional, add conditions with &&, loop with while let, and see that is only tests
  • 8.4 Coalesce: supply a fallback for a missing value with ??
  • 8.5 CoalesceExit: leave with ?? return, ?? continue or ?? break when a value is missing
  • 8.6 OptionalPropagate: pass absence to the caller with ?
  • 8.7 NestedOptional: int??: telling "nothing found" from "found nothing"

9. Errors

Operations that can fail: -> T ! E, throw, and the forms !, !! and catch.

  • 9.1 Fallible: return a value or fail with an error with -> T ! E, and take the outcome apart with a match on its sides
  • 9.2 Fail: leave a function with an error using throw
  • 9.3 UnitFallible: a function that returns nothing but can still fail: func F() -> !E
  • 9.4 Outcome: keep an outcome as the fallible itself, let kept = F();, and match it by side
  • 9.5 Discard: why a call that can fail must be handled, and how to drop its error on purpose with F() !!; or F() !! none
  • 9.6 Catch: handle each way an operation can fail with F() catch { arms }
  • 9.7 CatchFallback: turn any error into a default value with F() !! fallback
  • 9.8 Propagate: pass an error straight to the caller with a postfix ! instead of catching it
  • 9.9 ErrorVariant: describe the ways an operation can fail with a variant
  • 9.10 ErrorMapping: add context to an error as it passes through with F() catch { e => throw Mapped(e) }
  • 9.11 ErrorSum: fail with more than one kind of error with -> T ! A | B
  • 9.12 ExitStatus: keep Main as func Main() -> int, which cannot fail, and turn a helper's error into the exit status with Install() !! return 1; or return Run() !! 1;
  • 9.13 AbsenceToError: turn a missing value into an error with ?? throw
  • 9.14 NestedFallible: keep levels apart: -> T? ! E and -> (T ! E1) ! E2
  • 9.15 Panic: stop the program when something impossible happens
  • 9.16 Assert: check an assumption while the program runs

10. Sum types

A value that is one of several types: A | B.

  • 10.1 SumType: a value that can be an int32 or a bool: int32 | bool
  • 10.2 TypedPattern: match a sum by the type it holds
  • 10.3 SubsetPattern: match several members of a sum in one arm
  • 10.4 Is: ask which type a sum holds with is
  • 10.5 SumWidening: pass a smaller sum where a larger one is expected

11. Ownership

Who owns a value, and when it is cleaned up.

  • 11.1 Exclusivity: write a loan where it starts with &x or &var x, and hold one writer at a time
  • 11.2 Copy: assignment copies a value, and the copies are independent
  • 11.3 GiveAway: give a value away by writing it bare in a binding, an argument, a return or a field, and lend it with & to keep it
  • 11.4 Destructor: run cleanup when a value goes out of scope with destructor { ... }
  • 11.5 Destroy: end a value early with destroy, or with a ~self method that replaces its destructor and can return a field or fail
  • 11.6 NoCopy: mark plain data #NoCopy so it is given away instead of copied
  • 11.7 CustomCopy: copy a move-only type on purpose with a Clone method
  • 11.8 ReplaceSwap: why one field cannot be given away by itself, taking it with Replace or Swap, and taking a whole struct apart with a pattern
  • 11.9 Defer: schedule cleanup at the point you start the work, so it cannot be forgotten
  • 11.10 DeferReturn: what a deferred action sees when the function returns a value, and how defers and destructors run as one sequence
  • 11.11 Initialization: var x: T; is empty storage that every path must assign before it is read

12. Interfaces

Describing behaviour that many types share.

  • 12.1 Interface: declare an interface and implement it for your own types
  • 12.2 InterfaceValue: borrow values of different types as one interface
  • 12.3 InterfaceParameter: write a function that accepts any type implementing an interface
  • 12.4 Display: make your own type printable with {}
  • 12.5 Equatable: define what it means for two of your values to be equal
  • 12.6 Comparable: define an order for your own type
  • 12.7 StructuralEquality: compare whole structs and tuples with ==
  • 12.8 OperatorOverload: define ==, + and the other operators for your own type
  • 12.9 DerivedOperator: define one operator and get its partners for free
  • 12.10 Indexer: let your own type be indexed with []
  • 12.11 Iterator: implement Next so a type of your own can be used with for
  • 12.12 Iterable: let a container hand out an iterator for for

13. Generics

Types and functions that work for many types.

  • 13.1 GenericType: a struct with a type parameter: Pair<T>
  • 13.2 GenericMethod: methods on a generic type, and methods with type parameters of their own
  • 13.3 GenericBound: require a type parameter to implement an interface
  • 13.4 NumericBound: do arithmetic on a type parameter bounded by Integer, SignedInteger or Float, and see a wrong type argument refused at the call
  • 13.5 MultipleBounds: require several interfaces at once with A + B
  • 13.6 GenericOutcome: write helpers that work for any optional T? or fallible T ! E
  • 13.7 GenericSum: generic sums, and what happens when both members are the same type

14. Text

Strings, characters, formatting, parsing and input.

  • 14.1 StringLiteral: what a string literal is: read-only char8 code units
  • 14.2 Encoding: c8, c16 and c32 literals, and code units versus characters
  • 14.3 StringView: borrow text without copying it
  • 14.4 String: own text that lives as long as you need it
  • 14.5 StringBuilder: build text a piece at a time
  • 14.6 Utf8: check and decode UTF-8 bytes
  • 14.7 Unicode: bytes, code points and grapheme clusters, and why their counts differ
  • 14.8 UnicodeCase: change case beyond ASCII, where one letter can become two
  • 14.9 Format: control width and alignment when formatting values
  • 14.10 FormatNumber: control precision and number base when formatting numbers
  • 14.11 Render: format values into a String instead of the console
  • 14.12 Parse: turn text into a number, and handle text that is not one
  • 14.13 Input: read a line typed by the user, and notice when input ends
  • 14.14 JoinLines: split text into lines and join pieces back together, and change its case
  • 14.15 Regex: test and find matches of a regular expression
  • 14.16 RegexCapture: capture groups, every match, splitting and replacing

15. Memory

Pointers, raw memory and allocators.

  • 15.1 Pointer: the difference between *T and *var T, and taking an address with @
  • 15.2 OutParameter: return an answer through a &var T out-parameter, and why an optional T? is usually better
  • 15.3 RawMemory: allocate, use and free memory by hand (Alloc, Zero, Free)
  • 15.4 PointerArithmetic: step a pointer through memory one element at a time
  • 15.5 PointerSlice: turn a pointer and a length into a slice
  • 15.6 OptionalPointer: *T? and (*T)?: a pointer to an optional, or an optional pointer
  • 15.7 Layout: how big a type is and how it is aligned: sizeof and alignof
  • 15.8 Union: overlay one piece of storage with several types, and why that needs care
  • 15.9 Allocator: allocate through the Allocator interface instead of straight from the system
  • 15.10 Box: own one value allocated on the heap
  • 15.11 Arena: allocate many values and free them all at once
  • 15.12 FixedBuffer: allocate from a buffer you provide
  • 15.13 Pool: reuse fixed-size blocks instead of allocating new ones
  • 15.14 Zeroize: clear sensitive memory explicitly
  • 15.15 Rc: share one value between several owners with reference counting

16. Numbers

Numbers in depth.

  • 16.1 WideInteger: 128-, 256- and 512-bit integers
  • 16.2 NumberLimit: the smallest and largest value each number type can hold
  • 16.3 FloatSpecial: infinity and NaN, and how they compare
  • 16.4 Bitwise: &, |, ^ and ~: set, clear, flip and test bits with masks
  • 16.5 Shift: move bits left and right with <<, >> and >>>
  • 16.6 CheckedArithmetic: detect overflow instead of getting a wrong answer
  • 16.7 WrappingArithmetic: arithmetic that wraps around or saturates on purpose
  • 16.8 CheckedConvert: convert between number types and detect values that do not fit
  • 16.9 BitOperation: count, find and rotate bits
  • 16.10 Endian: write a number's bytes in a chosen byte order
  • 16.11 Math: roots, powers, logarithms, trigonometry, and rounding
  • 16.12 Complex: complex numbers: arithmetic, magnitude and polar form

17. Collections

Containers from the Collections package.

  • 17.1 Vector: a growable array that manages its own memory and capacity
  • 17.2 DynamicArray: Collections::Array, and how it differs from an inline array
  • 17.3 Deque: add and remove at both ends, and see where that beats a vector
  • 17.4 HashMap: look values up by key
  • 17.5 HashSet: test membership with a hash set
  • 17.6 TreeMap: keep keys in order, and walk them in order
  • 17.7 TreeSet: keep a set of values in order
  • 17.8 PriorityQueue: always take the most urgent item next
  • 17.9 BitSet: a set of small integers kept as bits
  • 17.10 SmallVector: a vector that keeps its first few items without allocating
  • 17.11 LruCache: a bounded cache that forgets the least recently used entry

18. Algorithms

Algorithms over slices from the Algorithms package.

  • 18.1 Sort: sort a slice in place
  • 18.2 Search: find a value in a slice, and handle not finding it
  • 18.3 BinarySearch: find a value in sorted data quickly
  • 18.4 MinMax: the smallest and largest values, and the empty case
  • 18.5 Fold: combine all elements into one value with a function
  • 18.6 IteratorAdaptor: chain lazy steps such as map, filter and take over an iterator
  • 18.7 Scan: running sums and scans, counting sequences and safe midpoints

19. Files

Paths, files and directories.

  • 19.1 Path: split a path into its parts, and see why a path is not a string
  • 19.2 PathJoin: build a path from parts
  • 19.3 PathNormalize: tidy a path by removing . and ..
  • 19.4 File: write text to a file and read it back, handling failure at every step
  • 19.5 Directory: create, list, and remove directories
  • 19.6 Metadata: ask a file for its size and kind
  • 19.7 Binary: read and write fixed-width values and raw bytes
  • 19.8 BufferedIo: buffer writes and flush them
  • 19.9 AtomicFile: replace a file's contents all at once or not at all
  • 19.10 TemporaryFile: a scratch file that cleans up after itself
  • 19.11 MemoryStream: read and write bytes in memory through the same reader and writer interfaces as a file

20. Utilities

Time, randomness, hashing and identifiers.

  • 20.1 Duration: lengths of time, and arithmetic on them
  • 20.2 Stopwatch: measure how long something takes
  • 20.3 Date: calendar dates, parsing them, and leap years
  • 20.4 DateTime: a date with a time and an offset, in RFC 3339
  • 20.5 Random: a reproducible random number generator
  • 20.6 Distribution: draw from a range, shuffle, and sample a normal distribution
  • 20.7 Entropy: unpredictable bytes from the operating system
  • 20.8 Hash: fast non-cryptographic hashes and checksums
  • 20.9 Uuid: create, print and parse UUIDs
  • 20.10 NanoId: short, URL-safe random identifiers
  • 20.11 TimeZone: turn a moment into local time in a time zone, and back

21. Data formats

Reading and writing JSON and TOML.

  • 21.1 Json: parse JSON into a value and walk it
  • 21.2 JsonWrite: write a value out as JSON
  • 21.3 JsonStream: read JSON as a stream of events
  • 21.4 Toml: parse a TOML document and read its values
  • 21.5 TomlWrite: write a TOML document
  • 21.6 BaseEncoding: bytes as hexadecimal, Base64, Base32 and Base58 text
  • 21.7 Url: parse, resolve and build URLs and their queries
  • 21.8 Compress: compress and decompress data in the Deflate, zlib and gzip formats

22. Packages

Modules, packages, libraries and tools.

  • 22.1 Module: split a package across source files and modules
  • 22.2 Visibility: choose what a package shows to others with pub
  • 22.3 Package: what a manifest says about a package
  • 22.4 Dependency: depend on another package
  • 22.5 Workspace: build several packages together
  • 22.6 SourceLibrary: write a library and use it from an executable
  • 22.7 StaticLibrary: build a static library
  • 22.8 SharedLibrary: build a shared library
  • 22.9 Documentation: document your code with /// comments
  • 22.10 Tooling: format, lint, test and document with the rux tool
  • 22.11 UnitTest: write #Test functions declared -> !TestFailure that pass each failed Expect check on with !, and run them with rux test
  • 22.12 Benchmark: measure how long code takes with the Test package's benchmarks

23. Compile time

Code that runs or is chosen while compiling.

  • 23.1 When: select code at compile time with when
  • 23.2 Target: the operating system and architecture being compiled for
  • 23.3 BuildMode: tell debug builds from release builds
  • 23.4 SourceLocation: the file and line of an expression
  • 23.5 CompileError: stop the build with #Error, or warn with #Warn
  • 23.6 Define: values passed to the build from the manifest or the command line
  • 23.7 Intrinsic: declarations the compiler implements itself, provided by the one package a build binds with Intrinsics

24. Platform

Talking to the operating system and the machine.

  • 24.1 Extern: call a platform API directly through an extern declaration and #Link
  • 24.2 CInterop: C-compatible types, pointers and handles
  • 24.3 Abi: choose a calling convention with #Abi
  • 24.4 Asm: write a function body in assembly
  • 24.5 AsmArm: the same function in AArch64 assembly, chosen with when

25. Concurrency

Threads, and the tools that let them share work safely.

  • 25.1 Thread: start a thread, wait for its result, and ask how many can run at once
  • 25.2 Atomic: count across threads without a lock
  • 25.3 Mutex: guard shared data with a lock that only one thread holds at a time
  • 25.4 Arc: share ownership of one value between threads
  • 25.5 Channel: send values from one thread to another
  • 25.6 WaitGroup: wait until a group of threads has finished
  • 25.7 Once: run initialization exactly once, whichever thread gets there first
  • 25.8 RwLock: many readers at once, or one writer alone

26. Systems

Processes, command lines, logs and networks.

  • 26.1 Environment: the program's arguments, environment variables and exit status
  • 26.2 ChildProcess: run another program and capture its output
  • 26.3 CommandLine: declare options and arguments, and get the help text for free
  • 26.4 Log: structured log records with levels and typed fields
  • 26.5 IpAddress: IPv4 and IPv6 addresses, and socket addresses with a port
  • 26.6 Tcp: a TCP server and client talking over the loopback interface
  • 26.7 Udp: datagrams between two UDP sockets

27. Projects

Complete small programs. Each one needs only the parts before its checkpoint.

  • 27.1 Thanks: draw RUX as an ASCII banner and thank everyone who helps build it (after Control flow)
  • 27.2 FizzBuzz: the classic counting game (after Control flow)
  • 27.3 Temperature: a table of Celsius and Fahrenheit temperatures (after Functions)
  • 27.4 Prime: every prime below 100, found with the sieve of Eratosthenes (after Sequences)
  • 27.5 Calculator: evaluate expressions and report every way they can go wrong (after Errors)
  • 27.6 Circle: read a radius, check it, and print the circle's measurements (after Numbers)
  • 27.7 Quadratic: solve a quadratic equation, including linear and degenerate cases (after Numbers)
  • 27.8 WordCount: count how often each word appears (after Collections)
  • 27.9 Inventory: keep a stock list of items, with updates that can fail (after Collections)
  • 27.10 Statistics: count, extremes, mean, variance and median, including empty and single-value input (after Algorithms)
  • 27.11 Guess: a number guessing game with seven valid guesses from 1 to 100 (after Utilities)
  • 27.12 Age: an age in completed years, months and days, with month-end clamping (after Utilities)
  • 27.13 Password: a 16-character password drawn from system entropy with rejection sampling (after Utilities)
  • 27.14 Launch: a mission checklist, a bounded countdown and a launch (after Utilities)
  • 27.15 Notes: keep notes in a JSON file (after Data formats)
  • 27.16 Melody: play a tune through the Windows console speaker (Windows only) (after Platform)
  • 27.17 SystemInfo: show the Windows version, build, processor and memory in a window (Windows only) (after Platform)
  • 27.18 Grep: search files for lines that match a regular expression, with command-line options (after Systems)

Running an Example

Each example is a standalone Rux package with its own Rux.toml, and requires Rux 0.4.0 or newer.

cd Basics/Hello
rux run

If necessary, install the dependencies first with rux install. To type-check an example without running it, use rux check.

Use the repository runners to check or test the examples. Running without arguments shows help:

./Run.ps1
./Run.ps1 check
./Run.ps1 test -Filter Errors
./Run.ps1 test -RuxExecutable ../Rux/Bin/rux.exe
./Run.ps1 clean

On Linux, macOS, or FreeBSD, use the equivalent POSIX shell runner:

sh Run.sh
sh Run.sh check
sh Run.sh test --filter Errors
sh Run.sh test --rux-executable ../Rux/Bin/rux
sh Run.sh clean

check type-checks the selected packages. test also runs eligible executables and builds static/shared libraries; source libraries are only checked. Tests verify exit codes, not printed output. Interactive, audible and windowed examples are checked but not run, and lessons that require another OS or architecture are reported as platform skips. Each run ends with checked, executed, built, skipped, and failed counts, returning a nonzero exit code if any check fails.

clean removes the Bin and Temp folders that the compiler leaves beside every package manifest, including companion packages and workspace members, and the repository Temp folder. It needs no compiler, takes the same filter (a filtered clean keeps the repository Temp), and removes only a symbolic link, never its target. Run it after switching compilers so no build record from an older Rux is reused.

Both runners use rux on PATH unless an executable is supplied. Dependencies must already be installed. The filter is a case-insensitive literal substring of a repository-relative package path; matching a workspace selects its members. An unmatched filter is an error. You can invoke a runner from another directory: package paths remain relative to the repository, while an explicit relative compiler path is resolved from your current directory.

Exceptions are maintained in Scripts/RunnerExceptions.tsv. The runners execute sequentially and do not build the compiler, install dependencies, or update the package cache. The runner regression tests use temporary fixtures and a fake compiler: pwsh -File Scripts/TestRunners.ps1 (use -ShellExecutable PATH if a POSIX shell is not on PATH).

Output follows the compiler runner's style: a ==> heading, green Passed or red Failed statuses with the package and stage, and elapsed times. Skips are yellow. Redirected output stays plain text; set NO_COLOR to disable terminal colors. Shell timings fall back to whole seconds where a fractional clock is unavailable.

License

Licensed under the MIT License.

About

Examples written in the Rux programming language

Topics

Resources

Stars

4 stars

Watchers

1 watching

Forks

Contributors

Languages