Start in the browser, make a prediction, then edit and run your first line of Blyx.
Start with a running file
A program is a set of instructions written as text. The editor below contains a complete file. Select Run program and read the Output pane. If Run on edit is selected, changes run automatically. You can reset the example at any time.
Read the greeting
The two lines beginning with // are notes for the reader. Execution begins at fn main(). The braces enclose the work that main performs. Inside them, println! writes the text between the double quotes and finishes the line. The semicolon ends that instruction.
Change one thing
Replace World inside the quoted greeting with your name. Leave the quotes, parentheses, exclamation mark and semicolon where they are. Run again and compare the two greetings. Changing the text changes what your reader sees.
Let the computer calculate
Add println!(6 * 7); on a new line inside the braces. Blyx evaluates the multiplication before printing 42. Put double quotes around 6 * 7 and you will see the characters instead. The difference between a value and text describing a value will recur throughout the course.
Worked program
// Blyx Example 1: Hello World
// Official Domain: https://blyx-lang.space
fn main() {
println!("Hello, World from Blyx!");
}
Expected output
Hello, World from Blyx!
Practice
Make the program print Hello, Blyx! on its first line and 42 on its second.
Hint
Keep both print calls inside main. Use quotes for the greeting and leave the multiplication unquoted.
Solution
Each println! adds one line. The arithmetic expression evaluates before the second call.
Find
println!("Hello, World from Blyx!");
Replace with
println!("Hello, Blyx!");
println!(6 * 7);
Output after the change
Hello, Blyx!
42
First steps
Numbers and expressions
Use a packing problem to learn whole numbers, decimals, operator order and integer division.
Turn a question into an expression
How many rows of five can you fill with 23 items? Give the two counts names with let. Since both values are integers, items / row yields the number of whole rows. The remainder operator, %, gives the three items still on the table.
Choose whole or fractional units
The literal 23 has type i64, a signed 64-bit integer. The literal 23.0 has type f64, a 64-bit floating-point number. The expression 23.0 / 5.0 yields 4.6. Use integer counts for indivisible objects and decimal operands on both sides when a fraction matters.
Group an expression
Multiplication and division bind more tightly than addition and subtraction. Read 2 + 3 * 4 as 2 + (3 * 4), which gives 14. In the editor, parentheses make (2 + 3) happen first, giving 20.
Choose useful test cases
A full row, one fewer than a full row, and zero items each tell you something different about the result. With a nonzero row size, full_rows * row + leftover reconstructs the input. Integer division by zero and integer overflow produce execution errors.
Pack 24 items in rows of five. Predict both integer results before running.
Hint
The division and remainder use items. The separate decimal example uses literal values.
Solution
Four complete rows hold 20 items. Four items remain. The decimal expression and the grouped expression still use their original literals.
Find
let items = 23;
Replace with
let items = 24;
Output after the change
4
4
4.6
20
First steps
Text, comments and output
Build a receipt one value at a time and learn how strings differ from variable names.
Name the pieces
A string literal encloses text in double quotes. Inside "Total: " the final space separates the label from the price. Outside quotes, label refers to the value introduced by let. Writing "label" would print those five letters.
Assemble a line
print!(label) writes the label and leaves the cursor on that line. println!(cost) writes the integer and ends the line. The last call starts a new line with Paid. To display several values together, use consecutive calls. These macros take zero or one expression.
Write a useful comment
A // comment continues to the end of its line. A comment such as // price is in whole credits records the unit that the number alone cannot express. Put the calculation in a binding if you want to print it twice.
Read output precisely
An extra space, a missing line break or putting the numeric expression inside quotes can change a report. First compare the lines and then compare characters within each line. This is the same approach you can use when testing a longer program.
Worked program
fn main() {
let label = "Total: ";
let cost = 3 * 7;
print!(label);
println!(cost);
println!("Paid");
}
Expected output
Total: 21
Paid
Practice
Change the quantity from three to five and replace the final receipt line with Thanks.
Hint
Edit the expression that defines cost, then edit the last quoted string.
Solution
Five units at seven credits cost 35. print! keeps the label and total on the same line.
Find
3 * 7
Replace with
5 * 7
Find
"Paid"
Replace with
"Thanks"
Output after the change
Total: 35
Thanks
Language essentials
Bindings, mutation and scope
Trace a name through nested blocks and choose when a value should change.
Bind a name
let level = 3; evaluates the right-hand expression and gives its result a name. An immutable binding is a useful default for a quantity that should keep the same value. Declare let mut when later statements need to update that particular binding.
Follow a name into a block
At the opening brace the program enters a new scope. The inner let level = 8; creates a second binding. A read of level starts in the current scope, so the first print sees 8. Leaving the block removes the inner binding and the outer 3 is visible again.
Change an existing binding
An assignment starts with the name, as in level = 8;. The interpreter finds the nearest binding with that name. Assignment requires a mutable binding and a compatible value kind. If there is an inner declaration, updating it only changes the inner value.
Accumulate a result
For a mutable integer counter, count += 1 adds one to the current value. The same updates work for subtraction, multiplication, division and remainder through -=, *=, /= and %=. Start a sum at zero and a product at one so the initial value preserves the first term.
Worked program
fn main() {
let level = 3;
{
let level = 8;
println!(level);
}
println!(level);
}
Expected output
8
3
Practice
Make both print calls show 8 by updating the outer level inside the block.
Hint
Use mut for the outer declaration and remove let from the inner statement.
Solution
There is now one mutable binding. The assignment reaches it and the new value is still visible after the block.
Find
let level = 3;
Replace with
let mut level = 3;
Find
let level = 8;
Replace with
level = 8;
Output after the change
8
8
Language essentials
Booleans and decisions
Classify temperatures, then test exactly what happens at the boundaries.
Ask a yes-or-no question
A comparison such as t < 0.0 produces true or false. An if condition requires a boolean. The band function first checks for a value below zero. Its early return immediately sends the string frozen back to the caller.
Partition the remaining inputs
After the first check, every remaining input in this example is zero or warmer. The final if expression chooses mild below 30 and hot otherwise. Because this expression supplies the function’s result, there is no semicolon after its closing brace.
Read the comparison signs
Use == to compare for equality and != to test inequality. Use < or > for strict limits and <= or >= to include the limit itself. To combine rules, && requires both sides, || requires at least one, and ! reverses a boolean. Short-circuit evaluation skips the right side once the answer is known.
Test the boundary
Two implementations can agree on -2 and 10 and still disagree at zero. A boundary test deliberately uses the threshold itself. Here 0.0 skips the frozen branch and 30.0 skips the mild branch.
Worked program
fn band(t: f64) -> str {
if t < 0.0 { return "frozen"; }
if t < 30.0 { "mild" } else { "hot" }
}
fn main() {
println!(band(-2.0));
println!(band(0.0));
println!(band(30.0));
}
Expected output
frozen
mild
hot
Practice
Change the rule so exactly 30 is mild. Keep the boundary at zero as it is.
Hint
Look for the comparison in the final if expression.
Solution
Including equality sends 30.0 through the mild branch. The negative and zero cases take their original branches.
Find
t < 30.0
Replace with
t <= 30.0
Output after the change
frozen
mild
mild
Language essentials
Functions, parameters and results
Give a calculation a name, call it more than once, and use its return value in another expression.
Define the interface
Read fn total(price: i64, quantity: i64) -> i64 as a function named total taking two signed integers and returning one signed integer. A parameter names a value inside the function. An argument is the value supplied by a call.
Trace a call
In total(7, 3), price receives 7 and quantity receives 3. The function multiplies them, finishes, and the caller receives 21. The binding first keeps that result in main. The second call uses new arguments and its result is added to first.
Return from a block
A final expression without a semicolon supplies the result. You can also write return price * quantity; to exit explicitly. A semicolon discards a final expression’s value. Keep an explicit return type on functions that return values when compiling a native executable.
Keep calculation separate from output
total can serve a receipt, a test or a larger calculation because it returns its answer. main decides what to print. Parameters belong to each call. Declare a local mutable accumulator when you need a value to change inside the function.
Make the second order four units at four credits. Print the combined total for both orders.
Hint
Only the second call in main needs different arguments.
Solution
The first order is 21 and the second is 16. Their sum is 37.
Find
total(4, 2)
Replace with
total(4, 4)
Output after the change
21
37
Language essentials
While loops and the Euclidean algorithm
Trace changing state and explain why a loop finishes.
Name the repeated work
The greatest common divisor is the largest positive integer that divides both inputs exactly. For nonnegative inputs with at least one positive, dividing x by y leaves a remainder. A number divides both x and y exactly if and only if it divides y and that remainder.
Trace the state
A while loop checks its condition before executing the body. Each pass replaces (x, y) with (y, x % y). Save the remainder first because overwriting x earlier would lose one of the inputs.
Before the pass
Remainder
After the pass
48, 18
12
18, 12
18, 12
6
12, 6
12, 6
0
6, 0
Explain termination
When y is positive, the new remainder is at least zero and strictly smaller than y. Eventually y reaches zero. The guard prevents taking a remainder with a zero divisor and the final x supplies the answer.
Start with a small test
If the second argument already equals zero, no iteration runs. Swapping positive inputs can add a first iteration, but the same common divisors survive. Tracing two small examples by hand is a quick way to find a mistaken update order.
Worked program
fn gcd(a: i64, b: i64) -> i64 {
let mut x = a;
let mut y = b;
while y != 0 {
let remainder = x % y;
x = y;
y = remainder;
}
x
}
fn main() {
println!(gcd(48, 18));
}
Expected output
6
Practice
Use 35 and 15 as inputs. Predict each remainder and the final result.
Hint
Start with 35 % 15, then divide 15 by that remainder.
Solution
The remainders are 5 and 0, so the last positive divisor is 5.
Find
gcd(48, 18)
Replace with
gcd(35, 15)
Output after the change
5
Language essentials
Break, continue and loop values
Find the first matching integer and carry it out of a loop.
Choose a stopping rule
while is convenient when the decision to repeat belongs at the top. Here the program must construct a candidate before it can decide whether to stop. A loop expression lets the test live beside the value that will become the answer.
Follow one iteration
The counter starts at 9. The first pass increments it to 10. Its remainder on division by four is nonzero, so continue jumps back to the beginning. The update occurs before continue so the candidate moves forward on every pass.
Return a value from a loop
At 12 the condition for continue is false. break n exits the nearest loop and supplies 12 to the binding found. The semicolon after the loop expression completes the enclosing let declaration. An ordinary break also exits a while loop, without carrying a value.
Distinguish the destinations
continue returns to the next iteration, break leaves the current loop, and return leaves the current function. If your program stops with a step-budget error, trace the path through continue and check that the variable in the condition actually changes.
Worked program
fn main() {
let mut n = 9;
let found = loop {
n += 1;
if n % 4 != 0 { continue; }
break n;
};
println!(found);
}
Expected output
12
Practice
Find the first multiple of five strictly greater than nine.
Hint
Keep the starting number and change the divisor.
Solution
The first candidate is 10. Its remainder on division by five is zero, so it becomes the loop result.
Find
n % 4
Replace with
n % 5
Output after the change
10
Language essentials
Recursion and the cost of a call
Trace Fibonacci by hand, identify the base case, and decide when iteration is cheaper.
Specify a base case
In this example Fibonacci is defined on nonnegative integers with F(0) = 0 and F(1) = 1. Each call first checks whether its argument is smaller than two. A base case gives a direct answer and prevents another call.
Expand one call
For n = 4 the two subproblems are F(3) and F(2). F(3) needs F(2) and F(1), while each F(2) needs F(1) and F(0). Work back up the tree to get 2 + 1 = 3. Each invocation has its own parameter value.
Count work as well as depth
F(2) is evaluated twice in that small tree. Repeated subproblems make this recursive implementation expensive as n grows. An iterative version can carry the two most recent values in mutable bindings and advance one position per pass.
Choose a safe input
The interpreter has both a step budget and a maximum of 64 simultaneous calls. Keep practice inputs small. A native build also uses finite machine resources. Large Fibonacci numbers eventually exceed the checked i64 range regardless of the algorithm.
Print Fibonacci at position seven, with a matching label.
Hint
The function name also occurs in the label. Edit the label and the call.
Solution
Building the sequence from zero gives 0, 1, 1, 2, 3, 5, 8, 13. Position seven is 13.
Find
"Fibonacci(10):"
Replace with
"Fibonacci(7):"
Find
fibonacci(10)
Replace with
fibonacci(7)
Output after the change
Fibonacci(7):
13
Numerical programming
Vectors and reductions
Represent several readings in one value and combine them into a weighted mean.
Choose a representation
A vector literal such as [5.0, 7.0, 9.0] holds numeric elements in order. Element storage is f64, including when the literal contains whole numbers. A vector can be empty. Bind it to a name or pass it to a function whose parameter type is vector.
Read by position
Indices begin at zero. For these three readings, len(readings) is 3 and at(readings, 2) is 9. Use an integer index and keep it below the length. The release supports reading vector elements. Build an accumulator when you need to calculate a derived result.
Give one reading extra weight
A dot product multiplies pairs at matching positions and adds them. With weights [1.0, 1.0, 2.0], the weighted total is 5 + 7 + 18 = 30. The total weight is 4. Dividing produces 7.5, which is closer to the final reading than the ordinary mean.
State the input contract
dot requires equal vector lengths. For a weighted average with nonnegative weights, require a positive total weight. An empty pair can have a valid dot product of zero while its mean has a zero denominator. Decide how your program should handle that case before you divide.
Worked program
fn main() {
let readings = [5.0, 7.0, 9.0];
let weights = [1.0, 1.0, 2.0];
println!(dot(readings, weights) / sum(weights));
}
Expected output
7.5
Practice
Give the first reading double weight and give each of the others weight one.
Hint
Keep the number of weights equal to the number of readings.
Solution
The weighted total becomes 10 + 7 + 9 = 26. Divide by four to get 6.5.
Find
[1.0, 1.0, 2.0]
Replace with
[2.0, 1.0, 1.0]
Output after the change
6.5
Numerical programming
Scan a vector for its maximum
Design a loop that finds the largest value even when every reading is negative.
Define the input
Finding a maximum requires at least one reading. This example supplies a nonempty literal. A reusable function should check len(readings) before indexing, or document and enforce the nonempty requirement at its call site.
Choose a starting value
Initialize peak from the first reading and begin the loop at index 1. Starting at zero as a candidate maximum would report a nonexistent zero for an all-negative input. The first real reading is a candidate you know belongs to the data.
Maintain a fact after every pass
Before reading index i, peak is the largest of the first i elements. Compare the next reading with peak, keep the larger value and increment i. The same fact now covers one more element. When i equals len(readings), the fact covers the whole input.
Estimate the cost
For n nonempty readings this scan performs n − 1 comparisons and stores a fixed number of local values beyond the input. A one-element vector skips the loop and returns its only element. Equal maxima do not change the reported value.
Worked program
fn main() {
let readings = [-8.0, -1.0, -3.0];
let mut peak = at(readings, 0);
let mut i = 1;
while i < len(readings) {
let reading = at(readings, i);
if reading > peak { peak = reading; }
i += 1;
}
println!(peak);
}
Expected output
-1
Practice
Try a vector containing just -12.0. Decide whether the loop body will run.
Hint
After initialization the index and the vector length both equal one.
Solution
The condition is false before the first pass. The initial reading is already the maximum.
Find
[-8.0, -1.0, -3.0]
Replace with
[-12.0]
Output after the change
-12
Numerical programming
Smooth a sequence with one running value
Turn a noisy signal into a sequence of estimates and trace how much history each estimate retains.
Set the initial state
The first reading is the first estimate. Print it before the loop and begin processing at index one. This convention gives one output per input, including for a single reading. The example assumes a nonempty signal because it reads index zero.
Blend old and new
Each later estimate is half the new reading plus half the previous estimate. For readings 10, 14, 18, the second estimate is 0.5 × 14 + 0.5 × 10 = 12. The third uses 12 as its old state and becomes 15.
Understand the tradeoff
More weight on the new reading makes the output respond faster to changes. Less weight preserves more history. Choose complementary weights that sum to one so a constant signal stays constant. A weight of one on the new reading reproduces the input.
Check a boundary case
Feed the algorithm three copies of 6. Its estimate should remain 6 after every pass. This checks both the initial value and the blend. Then change one input at a time so the reason for any output change is visible.
Worked program
fn main() {
let signal = [10.0, 14.0, 18.0];
let mut estimate = at(signal, 0);
println!(estimate);
let mut i = 1;
while i < len(signal) {
estimate = 0.5 * at(signal, i) + 0.5 * estimate;
println!(estimate);
i += 1;
}
}
Expected output
10
12
15
Practice
Give the new reading weight 0.75 and the previous estimate weight 0.25.
Hint
Both coefficients occur on the line that updates estimate.
Solution
The second estimate is 13. The last uses 13 as its old state, yielding 16.75.
Find
0.5 * at(signal, i) + 0.5 * estimate
Replace with
0.75 * at(signal, i) + 0.25 * estimate
Output after the change
10
13
16.75
Numerical programming
Fit a line and predict a value
Fit a one-parameter model, inspect its assumptions, and predict the response at an unseen input.
Choose a model
Suppose measurements are proportional to their input and a zero input should produce a zero response. Use y = slope × x. This choice fixes the intercept at zero. Pair each input with its observed target by position in two equal-length vectors.
Find the slope
The least-squares slope through the origin is dot(samples, targets) / dot(samples, samples). The numerator adds input × observed response across the pairs. The denominator adds the squared inputs. It is positive when at least one input is nonzero.
Work a fit by hand
With x = [1, 2, 3, 4] and y = [2, 4, 6, 8], the numerator is 60 and the denominator is 30. The slope is 2. A new input of 5 yields 10. The fit function only returns a coefficient. main chooses where to predict.
Interpret a changed observation
Increase the last target by 3. The numerator increases by 4 × 3 while the denominator stays 30. The new slope is 72 / 30 = 2.4. One observation can move every future prediction because the fitted slope is shared.
Worked program
// Fit y = slope * x by least squares through the origin.
fn fit(samples: vector, targets: vector) -> f64 {
dot(samples, targets) / dot(samples, samples)
}
fn main() {
let samples = [1.0, 2.0, 3.0, 4.0];
let targets = [2.0, 4.0, 6.0, 8.0];
let slope = fit(samples, targets);
println!(slope);
println!(slope * 5.0);
}
Expected output
2
10
Practice
Leave the training data unchanged and predict the response for x = 6.
Hint
Change the final multiplication in main. The fit still sees the original four pairs.
Solution
The fitted coefficient is still 2, and multiplying by 6 produces 12.
Find
slope * 5.0
Replace with
slope * 6.0
Output after the change
2
12
Numerical programming
Measure prediction error
Evaluate a set of predictions, trace the residuals and interpret their mean squared error.
Compare paired observations
Take one prediction and the matching observed target. Their difference is a residual. Its sign tells you whether the prediction is high or low. Averaging signed residuals alone could hide errors that cancel one another.
Accumulate the loss
With predictions [2, 3, 5] and targets [1, 4, 3], the residuals are 1, -1 and 2. Squaring gives 1, 1 and 4. Add the squares, then divide 6 by the number of observations, 3. The mean squared error is 2.
Match types and lengths
The loop index is an integer for at. The floating-point count supplies a same-type divisor for squares in both execution paths. For inputs supplied by a caller, check that the lengths match and that at least one pair exists before you compute the mean.
Use held-out data
Training chooses a slope or other parameters. Evaluation asks how those fixed parameters perform on examples that did not determine them. Keep a second vector of test targets when comparing two models. A low training loss alone says little about unseen observations.
Worked program
fn main() {
let predicted = [2.0, 3.0, 5.0];
let target = [1.0, 4.0, 3.0];
let mut squares = 0.0;
let mut count = 0.0;
let mut i = 0;
while i < len(target) {
let error = at(predicted, i) - at(target, i);
squares += error * error;
count += 1.0;
i += 1;
}
println!(squares / count);
}
Expected output
2
Practice
Replace the predictions with the three actual targets. What is the best possible value of this loss?
Hint
Each residual should be exactly zero for these inputs.
Solution
All squared residuals are zero, so the mean squared error is zero.
Find
[2.0, 3.0, 5.0]
Replace with
[1.0, 4.0, 3.0]
Output after the change
0
Numerical programming
Classify using a score and a threshold
Combine two features, choose a category, and decide how ties are classified.
Build the score
A feature is a numeric input such as a count or a measurement. A weight describes its contribution to a score. classify uses one weight per feature, computes dot(features, weights), then adds a scalar bias. The inputs and weights must have equal lengths.
Trace the prediction
The two contributions are 2 × 0.5 = 1 and 3 × -0.25 = -0.75. With a zero bias the score is 0.25. The condition score >= 0.0 chooses the string positive. A negative sign on a weight makes a larger feature lower the score.
Choose the tie rule
The comparison includes exactly zero on the positive side. A negative bias moves the cutoff without changing any individual weight. Test scores on both sides of zero and exactly at zero to check that the rule matches your intention.
Separate scoring from training
This is inference with coefficients supplied in the program. There is no learning step in this classifier. If you choose different coefficients, evaluate their predictions on labeled data before interpreting the change as an improvement.
Set the bias to -0.5 and predict the label before running.
Hint
The original weighted sum is 0.25.
Solution
The adjusted score is -0.25. This selects the negative branch.
Find
[0.5, -0.25], 0.0
Replace with
[0.5, -0.25], -0.5
Output after the change
negative
Practical projects
Test a program at its boundaries
Design a small repeatable test suite that catches an off-by-one classification rule.
Write the rule first
Raise an alarm only above 30.0. This sentence decides what happens at exactly 30.0. Implement the production rule in a function so the test calls precisely the same calculation that a larger program would use.
Choose three cases
Select a value below the limit, exactly at the limit, and above it. For each input, compare the returned boolean with the expected boolean. A correct run prints true three times. If one line prints false, its position identifies the case to inspect.
Prove a test can fail
Temporarily replace > with >= and run again. The below and above cases still pass. The equality case now prints false. Restore the strict comparison and repeat. This gives you evidence that at least one test can detect a real defect.
Compare execution paths
Run the same source with blyxc run, then build an executable and compare its output on the same inputs. Checking the process exit status detects execution failures. Checking actual output against expected output detects wrong answers from executions that finished successfully.
Change the rule to include exactly 30 and update the expected result for that input.
Hint
The implementation and the test expectation express two sides of the same contract.
Solution
Both changes are needed to keep all three tests passing under the new specification.
Find
t > 30.0
Replace with
t >= 30.0
Find
alarm(30.0) == false
Replace with
alarm(30.0) == true
Output after the change
true
true
true
Practical projects
Capstone project — build a sensor report
Build a complete report from a blank file, handle empty input, and verify a boundary condition.
Specify the report
Given a vector of readings and a limit, print their total and how many exceed the limit. For an empty batch, print no readings and stop. Before coding, write down the expected behavior for an empty batch, one reading equal to the limit, and a batch with readings on both sides.
Build the counting function
Start with fn hot_count(readings: vector, limit: f64) -> i64. Start hits and i at zero. While i is less than len(readings), inspect at(readings, i). Increment hits only for a reading strictly above the limit. Advance i on every pass and return hits after the loop.
Build the report function
Take the same two parameters. Check for an empty batch first. The early return lets the normal report follow at the same indentation. Use sum for the total, call hot_count for the count, and pair print! labels with println! values.
Trace and verify
The four readings total 123.5. Only 31.5 and 34.0 exceed the limit of 30.0. The empty batch exercises a separate branch without reading an element. Verify the complete program in both the browser and the CLI.
Input
Expected behavior
[]
One line: no readings
[30.0] with limit 30.0
Total 30 and count 0
[28.0, 31.5, 30.0, 34.0] with limit 30.0
Total 123.5 and count 2
Take it further
Change the function to count readings inside an inclusive range. Accept low and high parameters and combine two comparisons with &&. Test both endpoints, a value outside each end, and an empty vector. Decide how a caller should handle low greater than high.
Worked program
fn hot_count(readings: vector, limit: f64) -> i64 {
let mut hits = 0;
let mut i = 0;
while i < len(readings) {
if at(readings, i) > limit { hits += 1; }
i += 1;
}
hits
}
fn report(readings: vector, limit: f64) {
if len(readings) == 0 {
println!("no readings");
return;
}
print!("total: ");
println!(sum(readings));
print!("above limit: ");
println!(hot_count(readings, limit));
}
fn main() {
report([28.0, 31.5, 30.0, 34.0], 30.0);
report([], 30.0);
}
Expected output
total: 123.5
above limit: 2
no readings
Practice
Replace only the empty batch in main with a single reading equal to the limit. Predict the complete report.
Hint
This batch takes the nonempty branch but adds nothing to the above-limit count.
Solution
The first batch is unchanged. For the second, sum returns 30 and the strict comparison leaves hits at zero.
Compare the cost of two classifiers, check their probability forecasts, and score a ranked retrieval result. Run the comparison in CI or import the same Blyx functions into your application.
Start with a release decision
You have predictions from two versions of a classifier on the same held-out observations. The current model raises one false alarm. Its replacement misses one positive. Both get three out of four right. Decide what a false alarm and a miss cost before you look at which model wins.
Prepare a paired CSV
Save the four rows below as predictions.csv in UTF-8. Each row must refer to the same observation for both models. The label is 0 or 1. Each prediction is an unquoted number between 0 and 1. Keep the header and column order shown. Rows can use LF or CRLF line endings.
ModelGate 0.1.2 ships as a native executable. On Apple Silicon macOS or x86-64 Linux use the Homebrew command below. On x64 Windows, extract the release ZIP from the ecosystem catalog and run .\modelgate.exe predictions.csv --fn-cost 5 in PowerShell. A release archive also contains fixtures/improved.csv and fixtures/regression.csv.
At the default threshold of 0.5, a score equal to the threshold counts as positive. The baseline’s one false alarm costs 1. The candidate’s missed positive costs 5. Divide by four observations to get costs per row of 0.25 and 1.25. The JSON pass field is false. You can retain the report as a CI artifact using shell output redirection.
Exit code
Meaning
0
Candidate meets the cost and Brier criteria.
1
The candidate exceeds at least one permitted limit.
2
The CSV, a value or a command option is invalid. Check the diagnostic.
4
The native host could not complete an I/O operation.
Measure probability quality
Brier score averages the squared difference between each probability and its binary label. Two models with identical class decisions can have different Brier scores. ModelGate accepts --brier-tolerance for the largest allowed increase in this mean. The calibration library also provides cal_bin for counts, forecast totals and outcome totals, and cal_ece for a count-weighted summary of the gaps. Compare ECE on the same data using the same bin count.
Import a versioned library
Install Blyx 0.2.1, Rust 1.85 or later and a platform linker for a source build. In an empty project directory, run the clone command below. It puts the release beside the entry file. For a shared project, record the commit in version control, for example as a Git submodule.
Save this code as main.blyx beside vendor and run blyxc native-run main.blyx. It prints 6, the total cost of one false alarm and one miss. To keep the executable use blyxc build main.blyx -o evaluate, or -o evaluate.exe on Windows. The editable browser program below contains the same library in one file.
use vendor::classification::classification;
fn main() {
println!(class_cost(1.0, 1.0, 1.0, 5.0));
}
Evaluate a retriever
Use the retrieval package to score an ordered list of numeric document IDs for one judged query. With results [7, 7, 9], judgments [7, 9] and k of 3, unique hits occur at ranks 1 and 3. Precision is 2/3, recall is 1, reciprocal rank is 1, and average precision is (1 + 2/3) / 2. A repeated document still uses a rank. Record which queries have judgments and average the per-query metrics over that set.
Keep future data out of a time-series backtest
Blyx Backtest measures forecasts in chronological folds. For demand [10, 20, 30, 40, 50, 60, 70, 80], set initial history to 3, forecast horizon to 2, gap to 1 and training window to 2. The first fold trains on 20 and 30, skips 40 and scores against 50 and 60. The next trains on 40 and 50, skips 60 and scores against 70 and 80. Across those four observations the last-value baseline has mean absolute error of 25, the training-mean baseline 30, and custom forecasts [45, 55, 65, 75] score 5. Use the same fold bounds when fitting preprocessing and model parameters.
Use held-out paired data and keep the error costs, threshold and tolerance fixed when comparing runs. Inspect the individual errors and the number of observations. The four-row fixture illustrates the decision rule. Statistical uncertainty, subgroup performance and business impact require evidence from your own evaluation.
In the worked program, raise the cost of a missed positive from 5 to 10. Predict the three lines of output and then run it.
Hint
Only the total cost uses that argument. The confusion counts stay the same.
Solution
Precision and recall both remain 0.5. One false alarm costs 1 and one missed positive now costs 10, so the final line is 11.
Find
at(table, 3), 1.0, 5.0
Replace with
at(table, 3), 1.0, 10.0
Output after the change
0.5
0.5
11
Practical projects
Train, calibrate and monitor a regression model
Fit a regression, attach intervals using held-out errors, and catch persistent underprediction in a later stream. Run each stage in native Blyx or the browser.
Keep three sets of observations
Use training pairs to fit the model. Reserve a separate calibration set for choosing an interval radius. Keep a stable, chronological reference period and later labelled predictions for monitoring. Reusing training errors for calibration can make intervals too narrow. Choose data splits before fitting.
Fit the relationship
Save x,y pairs as a UTF-8 CSV. The second column is the response. The four rows below follow y = 2x + 1. The centered least-squares fit has feature mean 2.5, response mean 6 and slope 2. At x = 5 it predicts 11.
x,y
1,3
2,5
3,7
4,9
Run LinearFit
Extract the LinearFit archive for your platform and run the included fixture. On Windows, start the command with .\linearfit.exe in PowerShell. On Apple Silicon macOS and x86-64 Linux you can also install it from the Blyx Homebrew tap. Supplying --ridge 5 shrinks the slope to 1 and changes the prediction to 8.5.
./linearfit fixtures/line.csv --predict 5
Train by batch or by row
Use lf_fit on aligned vectors for a batch. For incoming observations start with lf_start, pass the state and next training pair to lf_update, and call lf_finish when you need a model. lf_merge combines disjoint training batches. The shared Moments library also exposes their means, centered sums and sample standard deviation.
Calibrate an interval
Suppose a separate model predicted 10 for each of four calibration cases whose true values were 10, 12, 7 and 11. The absolute errors are 0, 2, 3 and 1. At target coverage 3/5, take the third smallest error because ceil((4+1)×3/5) = 3. This yields a radius of 2 and the interval [18,22] around a new prediction of 20. At 90% coverage four cases give no finite result.
let cal = cf_calibrate([10, 12, 7, 11], [10, 10, 10, 10], 3, 5);
let interval = cf_interval(20.0, at(cal, 0));
Interpret coverage
Use cf_coverage on separate labelled predictions to measure the fraction inside the intervals. The usual split-conformal guarantee is marginal and assumes calibration and future examples are exchangeable. Inspect time periods or important subgroups separately when that assumption may fail.
Detect sustained underprediction
ResidualWatch calculates actual minus predicted. In its shift fixture the first three residuals are −1, 0 and 1, so the frozen center is 0 and the sample scale is 1. Two later residuals of 2 add 1.5 each to the positive CUSUM at allowance 0.5. The second reaches the inclusive limit of 3. The first alert is data row 5, and the CLI exits with status 1.
Keep the JSON report from each run. Exit code 0 means the monitor finished without an alert, 1 means a limit was reached, 2 signals invalid input and 4 signals an I/O failure. Choose an allowance, limit and scale floor using a representative stable period. Investigate drift alarms against labels and feature changes before deciding whether to retrain.
Add a package to a native project
With Blyx 0.2.1, Rust and a host linker installed, clone the tagged release next to your entry file. The training and monitoring packages include their pinned Blyx dependencies. Save the imported program as main.blyx and run blyxc native-run main.blyx. The package catalog has the exact import, function reference, runnable example and source for every package.
git clone --depth 1 --branch v0.1.1 https://github.com/Rahulchaube1/blyx-linearfit.git vendor/linearfit
# First line of main.blyx
use vendor::linearfit::linearfit;
Run all three stages in one project
The starter includes LinearFit, Conformal, ResidualWatch and their Blyx dependencies. With the native toolchain installed, extract the ZIP and run the command below in the project folder. The model predicts 21 with an interval from 19 to 23. The first incoming error gives a signal of 0. A second underprediction raises the signal to 1.
// https://github.com/Rahulchaube1/blyx-moments/blob/v0.1.0/moments.blyx
// A paired summary stores [count, mean_x, mean_y, Sxx, Sxy, Syy].
fn moments_finite(x: f64) -> bool { x - x == 0.0 }
pub fn mom_empty() -> vector { [0, 0, 0, 0, 0, 0] }
pub fn mom_valid(s: vector) -> bool {
if len(s) != 6 { return false; }
let n = at(s, 0);
if !(n >= 0.0 && n <= 9007199254740991.0) || n % 1.0 != 0.0 { return false; }
let mut i = 1;
while i < 6 {
if !moments_finite(at(s, i)) || (n == 0.0 && at(s, i) != 0.0) { return false; }
i += 1;
}
at(s, 3) >= 0.0 && at(s, 5) >= 0.0
}
pub fn mom_update(s: vector, x: f64, y: f64) -> vector {
if !mom_valid(s) || !moments_finite(x) || !moments_finite(y) { return []; }
if at(s, 0) == 0.0 { return [1, x, y, 0, 0, 0]; }
let n = at(s, 0) + 1.0;
let dx = x - at(s, 1);
let dy = y - at(s, 2);
let mx = at(s, 1) + dx / n;
let my = at(s, 2) + dy / n;
let next = [n, mx, my, at(s, 3) + dx * (x - mx),
at(s, 4) + dx * (y - my), at(s, 5) + dy * (y - my)];
if !mom_valid(next) { return []; }
next
}
pub fn mom_summary(x: vector, y: vector) -> vector {
if len(x) != len(y) { return []; }
let mut state = mom_empty();
let mut i = 0;
while i < len(x) {
state = mom_update(state, at(x, i), at(y, i));
if len(state) == 0 { return []; }
i += 1;
}
state
}
pub fn mom_merge(a: vector, b: vector) -> vector {
if !mom_valid(a) || !mom_valid(b) { return []; }
if at(a, 0) == 0.0 { return b; }
if at(b, 0) == 0.0 { return a; }
let n = at(a, 0) + at(b, 0);
let share = at(b, 0) / n;
let weight = at(a, 0) * share;
let dx = at(b, 1) - at(a, 1);
let dy = at(b, 2) - at(a, 2);
let next = [n, at(a, 1) + dx * share, at(a, 2) + dy * share,
(at(a, 3) + at(b, 3)) + (dx * weight) * dx,
(at(a, 4) + at(b, 4)) + (dx * weight) * dy,
(at(a, 5) + at(b, 5)) + (dy * weight) * dy];
if !mom_valid(next) { return []; }
next
}
// Reduce to [1,4) before Newton iteration, including for subnormal variance.
fn moments_positive_root(value: f64) -> f64 {
if value == 0.0 { return 0.0; }
let mut v = value;
let mut factor = 1.0;
while v >= 4.0 { v /= 4.0; factor *= 2.0; }
while v < 1.0 { v *= 4.0; factor /= 2.0; }
let mut root = 2.0;
let mut i = 0;
while i < 6 { root = 0.5 * (root + v / root); i += 1; }
root * factor
}
pub fn mom_sample_sd_y(s: vector) -> f64 {
if !mom_valid(s) || at(s, 0) < 2.0 { return -1.0; }
moments_positive_root(at(s, 5) / (at(s, 0) - 1.0))
}
// https://github.com/Rahulchaube1/blyx-linearfit/blob/v0.1.1/linearfit.blyx
fn linearfit_finite(x: f64) -> bool { x - x == 0.0 }
pub fn lf_start() -> vector { mom_empty() }
pub fn lf_update(s: vector, x: f64, y: f64) -> vector { mom_update(s, x, y) }
pub fn lf_merge(a: vector, b: vector) -> vector { mom_merge(a, b) }
// Model is centered at the sample means to preserve precision in prediction.
// penalty multiplies slope squared in the unnormalized sum-of-squares objective.
pub fn lf_finish(s: vector, penalty: f64) -> vector {
if !mom_valid(s) || at(s, 0) < 2.0 || !linearfit_finite(penalty) || penalty < 0.0 { return []; }
let denominator = at(s, 3) + penalty;
if denominator <= 0.0 || !linearfit_finite(denominator) { return []; }
let slope = at(s, 4) / denominator;
if !linearfit_finite(slope) { return []; }
[at(s, 1), at(s, 2), slope]
}
pub fn lf_fit(x: vector, y: vector, penalty: f64) -> vector {
lf_finish(mom_summary(x, y), penalty)
}
pub fn lf_predict(model: vector, x: f64) -> f64 {
if len(model) != 3 || !linearfit_finite(x) { return 0.0 / 0.0; }
let y = at(model, 1) + at(model, 2) * (x - at(model, 0));
if !linearfit_finite(y) { return 0.0 / 0.0; }
y
}
fn main() {
let training = lf_fit([1, 2, 3, 4], [3, 5, 7, 9], 0.0);
println!(at(training, 2));
println!(lf_predict(training, 5.0));
}
Expected output
2
11
Practice
In the worked program, change the training penalty from 0 to 5. What happens to the slope and the prediction at x = 5?
Hint
Sxx is 5 and Sxy is 10. The ridge slope divides Sxy by Sxx plus the penalty.
Solution
The slope becomes 1. The centered prediction is 6 + 1 × (5 − 2.5), or 8.5.
Find
[3, 5, 7, 9], 0.0);
Replace with
[3, 5, 7, 9], 5.0);
Output after the change
1
8.5
Practical projects
Train a neural network with BlyxTorch
Train an XOR classifier, inspect a real gradient, then compile a dense network for your own labels and deploy it as a standalone CPU executable.
Learn a nonlinear decision
XOR labels the input pair (0,1) or (1,0) as positive. A single straight-line decision boundary cannot separate both positive points from the two negative points. The default BlyxTorch model uses two inputs, four tanh hidden units and one output logit. Its 17 parameters include all weights and biases.
Start in VS Code or VSCodium
Install the BlyxTorch extension from your editor’s registry. It installs Blyx Language alongside the trainer. Create a file named sensor.blyx, type bt-sensor, accept the completion, and choose Blyx: Run File. Change the final sensor reading and run it again. An offline install uses the two VSIX files linked from the package page.
Download and extract the matching archive. From its folder, run the three commands below. Training takes 250 epochs with Adam, a learning rate of 0.03, batches of four and seed 7. The output is a two-line text checkpoint. The prebuilt trainer runs directly. On Windows PowerShell, start commands with .\blyxtorch.exe and save the checkpoint with | Out-File -Encoding ascii xor.bt.
The mean training loss is about 0.00630 on the four rows. The probabilities below are rounded. To evaluate performance on a real dataset, keep separate labelled observations out of training and run score on those rows. In the browser example, change the second input from [0, 1] to [0, 0]. Its predicted class changes from true to false.
The browser program uses a dual number with a value and a tangent. For a trainable weight use tangent 1; for a constant use tangent 0. At w = 1, the loss (2w − 5)² is 9. Its derivative is −12, so a gradient step with learning rate 0.125 moves the weight to 2.5 and the loss becomes zero.
Compile a different network
Widths include input and output. This example uses eight and four hidden units for a three-class classifier. Compile the emitted Blyx source with Blyx 0.2.1, Rust 1.85 or later and a host linker. The resulting executable can train and predict on a different machine of the same target platform. For Windows PowerShell, send the emitted source through Out-File -Encoding ascii classifier.blyx and compile to classifier.exe.
Use mse for continuous targets, binary for one probability, or softmax for a single class index per observation. The input is an unquoted numerical UTF-8 CSV. Training and gradient commands use labelled rows. Prediction takes the feature columns alone.
Task
Example header
Model output
Two regression targets
x0,x1,y0,y1
Two real numbers
Binary classification
x0,x1,y0
One probability
Three-class classification
x0,x1,class
Three probabilities summing to one
Inspect gradients and checkpoints
The gradient command returns a per-row loss followed by one derivative per trainable weight or bias. The compiled backward pass uses the chain rule to traverse the layers in reverse order. Within each layer the output-by-input weight matrix comes first in row-major order, then its bias vector. Loading checks the model's identity and parameter count. The optimizer uses the actual size of the final mini-batch.
./blyxtorch gradient xor.bt fixtures/xor.csv
Train and test on different jobs
Extract the starter and open BlyxTorch.code-workspace. Each row describes pages divided by 100 and waiting jobs divided by 10. Select Terminal → Run Task → BlyxTorch: Evaluate print queue. The model trains on 16 synthetic jobs and evaluates six separate labels. The task reports six rows and mean loss near 0.00234. Edit new-jobs.csv and choose Predict new print jobs to score your inputs. A saved checkpoint and the browser program also run inference without retraining.
blyxtorch train-score print-queue/train.csv print-queue/holdout.csv 180 0.03 4 adam 7
blyxtorch train-predict print-queue/train.csv print-queue/new-jobs.csv 180 0.03 4 adam 7
BlyxTorch 0.2.0 runs fixed-shape float64 networks on CPU. It supports up to eight affine layers and 1,024 parameters. The published comparison covers five small networks, CPU PyTorch, and a separate CSV-scoring benchmark. GPU execution, convolution, transformer training and arbitrary-rank tensors are outside this release.
// BlyxTorch 0.1.0, MIT OR Apache-2.0.
// https://github.com/Rahulchaube1/blyxtorch
fn main() {
let weight = bt_dual(1.0, 1.0);
let x = bt_dual(2.0, 0.0);
let target = bt_dual(5.0, 0.0);
let loss = bt_square(bt_sub(bt_mul(weight, x), target));
println!(at(loss, 0));
println!(at(loss, 1));
let updated = bt_dual(at(weight, 0) - 0.125 * at(loss, 1), 0.0);
println!(at(bt_square(bt_sub(bt_mul(updated, x), target)), 0));
}
// Portable f64 primitives and forward-mode automatic differentiation.
pub fn btx_finite(x: f64) -> bool { x - x == 0.0 }
pub fn btx_valid(v: vector, width: i64) -> bool {
if len(v) != width { return false; }
let mut i = 0;
while i < width {
if !btx_finite(at(v, i)) { return false; }
i += 1;
}
true
}
// exp(-x) for finite x >= 0. Range reduction bounds the Taylor remainder.
fn exp_decay(x: f64) -> f64 {
if x >= 746.0 { return 0.0; }
let mut r = -x;
let mut levels = 0;
while r < -0.35 { r *= 0.5; levels += 1; }
let mut term = 1.0;
let mut total = 1.0;
let mut k = 1.0;
while k <= 15.0 { term *= r / k; total += term; k += 1.0; }
while levels > 0 { total *= total; levels -= 1; }
total
}
pub fn btx_exp_shift(x: f64) -> f64 {
if x > 0.0 { return 0.0 / 0.0; }
exp_decay(-x)
}
// log(1+x), 0 <= x <= 1. The transformed series also retains very small x.
fn log1p_unit(x: f64) -> f64 {
let z = x / (2.0 + x);
let zz = z * z;
let mut term = z;
let mut accum = z;
let mut k = 3.0;
while k <= 35.0 { term *= zz; accum += term / k; k += 2.0; }
2.0 * accum
}
// The softmax denominator is always finite and at least one.
pub fn btx_log_sum(x: f64) -> f64 {
if x < 1.0 || !btx_finite(x) { return 0.0 / 0.0; }
let mut n = x;
let mut offset = 0.0;
while n >= 2.0 { n *= 0.5; offset += 0.6931471805599453; }
offset + log1p_unit(n - 1.0)
}
pub fn btx_sqrt(x: f64) -> f64 {
if x == 0.0 { return 0.0; }
if x < 0.0 || !btx_finite(x) { return 0.0 / 0.0; }
let mut z = x;
let mut scale = 1.0;
while z < 1.0 { z *= 4.0; scale *= 0.5; }
while z > 4.0 { z *= 0.25; scale *= 2.0; }
let mut r = 1.5;
let mut i = 0;
while i < 6 { r = 0.5 * (r + z / r); i += 1; }
r * scale
}
pub fn btx_logistic(x: f64) -> f64 {
if x >= 0.0 { return 1.0 / (1.0 + exp_decay(x)); }
let q = exp_decay(-x);
q / (1.0 + q)
}
pub fn btx_tanh_value(x: f64) -> f64 {
if x < 0.0 { return -btx_tanh_value(-x); }
if x < 0.00001 { return x * (1.0 - x*x/3.0); }
let q = exp_decay(2.0*x);
(1.0-q)/(1.0+q)
}
pub fn btx_relu_value(x: f64) -> f64 { if x > 0.0 { return x; } 0.0 }
pub fn btx_softplus_value(x: f64) -> f64 {
if x >= 0.0 { return x + log1p_unit(exp_decay(x)); }
log1p_unit(exp_decay(-x))
}
pub fn btx_bce_value(logit: f64, label: f64) -> f64 {
if logit >= 0.0 { return (1.0-label)*logit + log1p_unit(exp_decay(logit)); }
return -label*logit + log1p_unit(exp_decay(-logit));
}
pub fn btx_bce_slope(logit: f64, label: f64) -> f64 {
if logit >= 0.0 { return (1.0-label) - btx_logistic(-logit); }
btx_logistic(logit) - label
}
pub fn bt_dual(value: f64, tangent: f64) -> vector {
if !btx_finite(value) || !btx_finite(tangent) { return []; }
[value, tangent]
}
pub fn bt_add(a: vector, b: vector) -> vector {
if len(a) != 2 || len(b) != 2 { return []; }
bt_dual(at(a,0)+at(b,0), at(a,1)+at(b,1))
}
pub fn bt_sub(a: vector, b: vector) -> vector {
if len(a) != 2 || len(b) != 2 { return []; }
bt_dual(at(a,0)-at(b,0), at(a,1)-at(b,1))
}
pub fn bt_mul(a: vector, b: vector) -> vector {
if len(a) != 2 || len(b) != 2 { return []; }
bt_dual(at(a,0)*at(b,0), at(a,1)*at(b,0) + at(a,0)*at(b,1))
}
pub fn bt_div(a: vector, b: vector) -> vector {
if len(a) != 2 || len(b) != 2 || at(b,0) == 0.0 { return []; }
let v = at(a,0)/at(b,0);
bt_dual(v, (at(a,1)-v*at(b,1))/at(b,0))
}
pub fn bt_square(a: vector) -> vector { bt_mul(a, a) }
pub fn bt_relu(a: vector) -> vector {
if !btx_valid(a,2) { return []; }
if at(a,0) > 0.0 { return a; }
[0,0]
}
pub fn bt_tanh(a: vector) -> vector {
if !btx_valid(a,2) { return []; }
let v = btx_tanh_value(at(a,0));
bt_dual(v, (1.0-v)*(1.0+v)*at(a,1))
}
pub fn bt_sigmoid(a: vector) -> vector {
if !btx_valid(a,2) { return []; }
let x = at(a,0);
bt_dual(btx_logistic(x), btx_logistic(x)*btx_logistic(-x)*at(a,1))
}
pub fn bt_softplus(a: vector) -> vector {
if !btx_valid(a,2) { return []; }
bt_dual(btx_softplus_value(at(a,0)), btx_logistic(at(a,0))*at(a,1))
}
pub fn bt_bce_logits(a: vector, label: f64) -> vector {
if !btx_valid(a,2) || !btx_finite(label) || label < 0.0 || label > 1.0 { return []; }
bt_dual(btx_bce_value(at(a,0),label), btx_bce_slope(at(a,0),label)*at(a,1))
}
Expected output
9
-12
0
Practice
In the worked program, change the learning rate from 0.125 to 0.25. Where does the update put the weight, and what loss do you get?
Hint
The derivative before the update is −12. Compute 1 − 0.25 × (−12), then square the new prediction error.
Solution
The weight becomes 4. Its prediction is 8, so the new loss is (8 − 5)² = 9. The larger step crosses the minimum.
Find
0.125 * at(loss, 1)
Replace with
0.25 * at(loss, 1)
Output after the change
9
-12
9
Framework projects
Swiftlet · Route a book catalog request
Dispatch a method and request path against a table of literal and parameterized routes. Return a matched template and the methods a client can use.
The developer problem
A method error and a missing route mean different things to an HTTP client. If their responses share one fallback, clients lose the list of methods a resource accepts. RFC 9110 requires an Allow field on a 405 response.
Pass PATCH and /books/42?preview=yes to the dispatcher. It selects /books/:id and extracts 42. Try the same method on /books/new, an explicitly read-only resource. The CGI example also serves a health check through an existing web server. Install Blyx 0.2.1, Rust and a host linker, then run these commands.
Register a method and an absolute path template separated by one space. GET, HEAD, POST, PUT, PATCH, DELETE and OPTIONS use explicit registrations. Literal segments outrank parameters by their count. Equally specific templates use registration order. The matcher strips the query, preserves percent encoding and treats a trailing slash as significant. Hosting, URL decoding and authentication belong to the application.
Function
Behavior
sw_dispatch(routes, method, target)
Import router. Returns status text, matched template, and the Allow value in a three-element argument list.
sw_param(template, target, name)
Extract an encoded path parameter from a matching path. An absent capture returns an empty string.
// Blyx Swiftlet 0.1.0, MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-swiftlet/tree/v0.1.0
// A resource's method set is shared by the dispatcher and the Allow header.
pub fn sw_flag(method: str) -> i64 {
if method == "GET" { return 1; }
if method == "HEAD" { return 2; }
if method == "POST" { return 4; }
if method == "PUT" { return 8; }
if method == "PATCH" { return 16; }
if method == "DELETE" { return 32; }
if method == "OPTIONS" { return 64; }
0
}
pub fn sw_accepts(mask: i64, method: str) -> bool {
let bit = sw_flag(method);
if mask < 0 || mask > 127 || bit == 0 { return false; }
(mask / bit) % 2 == 1
}
pub fn sw_status(found: bool, mask: i64, method: str) -> i64 {
if !found { return 404; }
if sw_accepts(mask, method) { return 200; }
405
}
pub fn sw_enable(mask: i64, method: str) -> i64 {
if sw_accepts(mask, method) { return mask; }
mask + sw_flag(method)
}
fn main() {
let methods = sw_enable(sw_enable(0, "GET"), "POST");
println!(sw_status(true, methods, "GET"));
println!(sw_status(true, methods, "DELETE"));
println!(sw_status(false, methods, "GET"));
}
Expected output
200
405
404
Practice
Change DELETE to POST in the second request. Which status changes?
Hint
Change only the worked example’s input. The API table describes the output.
Solution
The route accepts POST, so the second status becomes 200.
Find
sw_status(true, methods, "DELETE")
Replace with
sw_status(true, methods, "POST")
Output after the change
200
200
404
Framework projects
Shrike · Merge two help-center searches
Combine lexical and semantic search results by rank, then walk the merged list in a deterministic order.
The developer problem
A keyword ranker and an embedding ranker return scores on different scales. Reciprocal rank fusion combines each document’s position in the lists. It gives a developer an inspectable baseline before tuning a score calibration or training a reranker.
A literal-word search and a paraphrase search return different article IDs. The example prints the first three fused results. Article 21 wins because both rankers put it near the top. Install Blyx 0.2.1, Rust and a host linker, then run these commands.
Supply two ranked vectors of nonnegative integer IDs up to 2^53−1 and an offset from 0 to 1,000,000. The first occurrence in each list contributes 1/(offset + one-based position). Missing IDs contribute zero. Equal scores use ascending ID. Start the cursor at −1. Each next-result call can take quadratic time in the combined shortlist length; use this version with small candidate sets.
Function
Behavior
sh_valid_inputs(left, right, offset)
Validate every ID and the smoothing offset.
sh_score(left, right, id, offset)
Get the fused score of one document. Zero means absent and −1 means invalid input.
sh_next(left, right, offset, previous)
Get the next ID after a cursor, or −1 for exhaustion or invalid input. Each ID is returned once.
Verify a change
Run the package checks from its release directory. Compare the browser example with its expected output, then change the input in the exercise below.
// Blyx Shrike 0.1.0, MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-shrike/tree/v0.1.0
// Document IDs fit exactly in a numeric vector. -1 is the iteration sentinel.
fn sh_id(id: f64) -> bool {
id >= 0.0 && id <= 9007199254740991.0 && id % 1.0 == 0.0
}
fn sh_valid(list: vector) -> bool {
let mut i = 0;
while i < len(list) {
if !sh_id(at(list, i)) { return false; }
i += 1;
}
true
}
fn sh_vote(list: vector, id: f64, offset: f64) -> f64 {
let mut i = 0;
while i < len(list) {
if at(list, i) == id { return 1.0 / (offset + at([i], 0) + 1.0); }
i += 1;
}
0.0
}
pub fn sh_valid_inputs(left: vector, right: vector, offset: f64) -> bool {
offset >= 0.0 && offset <= 1000000.0 && sh_valid(left) && sh_valid(right)
}
pub fn sh_score(left: vector, right: vector, id: f64, offset: f64) -> f64 {
if !sh_id(id) || !sh_valid_inputs(left, right, offset) { return -1.0; }
sh_vote(left, id, offset) + sh_vote(right, id, offset)
}
// Iterate by score descending and ID ascending. Return -1 at the end.
pub fn sh_next(left: vector, right: vector, offset: f64, previous: f64) -> f64 {
if !sh_valid_inputs(left, right, offset) { return -1.0; }
let prev_score = sh_vote(left, previous, offset) + sh_vote(right, previous, offset);
if previous != -1.0 && (!sh_id(previous) || prev_score == 0.0) { return -1.0; }
let mut best_id = -1.0;
let mut best_score = 0.0;
let mut i = 0;
while i < len(left) + len(right) {
let mut doc = 0.0;
if i < len(left) { doc = at(left, i); } else { doc = at(right, i - len(left)); }
let score = sh_vote(left, doc, offset) + sh_vote(right, doc, offset);
let eligible = previous == -1.0 || score < prev_score || (score == prev_score && doc > previous);
if eligible && (score > best_score || (score == best_score && doc < best_id)) {
best_id = doc;
best_score = score;
}
i += 1;
}
best_id
}
fn main() {
let lexical = [41, 17, 83];
let semantic = [17, 83, 99];
let first = sh_next(lexical, semantic, 60.0, -1.0);
let second = sh_next(lexical, semantic, 60.0, first);
println!(first);
println!(second);
}
Expected output
17
83
Practice
Move article 41 to first place in both lists. Which two articles lead?
Hint
Change only the worked example’s input. The API table describes the output.
Solution
41 wins both lists and 83 retains a contribution from each.
Find
let semantic = [17, 83, 99];
Replace with
let semantic = [41, 83, 99];
Output after the change
41
83
Framework projects
Bunting · Publish a support-queue report
Publish a distribution as a standalone HTML table with interval labels, counts and meters. Reuse the same bin definitions in reports and tests.
The developer problem
A colored chart alone can hide values from people navigating with assistive technology. W3C’s table guidance pairs data cells with headers. Bunting emits row and column headers and prints the count alongside every meter.
Group eight first-reply waits at 5, 10 and 20 minutes. The resulting HTML page opens offline and exposes intervals, counts and shares as a table. Every observation contributes to one row. Install Blyx 0.2.1, Rust and a host linker, then run these commands.
Supply finite strictly increasing boundaries. A value exactly on a boundary belongs to the bucket above it. Bucket −1 counts missing or non-finite values. An empty boundary vector represents all finite values. The table generator validates boundaries before writing any markup. The caller supplies the HTML document around the table.
Function
Behavior
bu_valid(edges), bu_bucket(edges, value)
Check boundaries and locate the value by binary search.
bu_count(data, edges, bucket)
Count observations in one bucket. An invalid request returns −1.
bu_table(data, edges)
Write a captioned HTML table with explicit counts and meter values. Returns false for invalid boundaries.
Verify a change
Run the package checks from its release directory. Compare the browser example with its expected output, then change the input in the exercise below.
// Blyx Bunting 0.1.0, MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-bunting/tree/v0.1.0
fn bu_finite(x: f64) -> bool { x - x == 0.0 }
pub fn bu_valid(edges: vector) -> bool {
let mut i = 0;
while i < len(edges) {
if !bu_finite(at(edges, i)) { return false; }
if i > 0 && at(edges, i) <= at(edges, i - 1) { return false; }
i += 1;
}
true
}
fn bu_find(edges: vector, x: f64) -> i64 {
let mut low = 0;
let mut high = len(edges);
while low < high {
let mid = low + (high - low) / 2;
if x < at(edges, mid) { high = mid; } else { low = mid + 1; }
}
low
}
pub fn bu_bucket(edges: vector, x: f64) -> i64 {
if !bu_valid(edges) || !bu_finite(x) { return -1; }
bu_find(edges, x)
}
// The missing bucket is -1. All other buckets include the lower boundary.
pub fn bu_count(data: vector, edges: vector, bucket: i64) -> i64 {
if !bu_valid(edges) || bucket < -1 || bucket > len(edges) { return -1; }
let mut count = 0;
let mut i = 0;
while i < len(data) {
let x = at(data, i);
if bu_finite(x) {
if bucket >= 0 && bu_find(edges, x) == bucket { count += 1; }
} else {
if bucket == -1 { count += 1; }
}
i += 1;
}
count
}
fn bu_label(edges: vector, i: i64) {
if i == -1 { print!("Missing or non-finite"); return; }
if len(edges) == 0 { print!("All finite values"); return; }
if i == 0 { print!("Below "); print!(at(edges, 0)); return; }
print!(at(edges, i - 1));
if i == len(edges) { print!(" and above"); return; }
print!(" to below "); print!(at(edges, i));
}
// Emit a semantic HTML fragment. Labels come from numeric edges.
pub fn bu_table(data: vector, edges: vector) -> bool {
if !bu_valid(edges) { return false; }
println!("<table><caption>Distribution of observations</caption>");
println!("<thead><tr><th scope=\"col\">Interval</th><th scope=\"col\">Count</th><th scope=\"col\">Share</th></tr></thead><tbody>");
let mut bucket = 0;
while bucket <= len(edges) + 1 {
let mut id = bucket;
if bucket == len(edges) + 1 { id = -1; }
let n = bu_count(data, edges, id);
let mut total = len(data);
if total == 0 { total = 1; }
print!("<tr><th scope=\"row\">"); bu_label(edges, id);
print!("</th><td>"); print!(n); print!("</td><td><meter aria-label=\"Share of all observations\" min=\"0\" max=\"");
print!(total); print!("\" value=\""); print!(n); print!("\"></meter> ");
print!(n); print!(" / "); print!(len(data)); println!("</td></tr>");
bucket += 1;
}
println!("</tbody></table>");
true
}
fn main() {
let waits = [0, 4, 5, 8, 10, 12];
let edges = [5, 10];
println!(bu_count(waits, edges, 0));
println!(bu_count(waits, edges, 1));
println!(bu_count(waits, edges, 2));
}
Expected output
2
2
2
Practice
Change the cut points to 4 and 12. Where do the exact boundary observations go?
Hint
Change only the worked example’s input. The API table describes the output.
Solution
Values 4 and 12 move into the buckets beginning at those cut points.
Find
let edges = [5, 10];
Replace with
let edges = [4, 12];
Output after the change
1
4
1
Framework projects
Wren · Test an invoice and packing calculation
Run named checks and skips, compare floating-point measurements, and report a TAP 13 stream and a process exit status for CI.
The developer problem
A test that only prints an error can leave a build green. TAP defines a machine-readable result for each check and a plan stating how many results to expect. Wren couples that output to the number of failures.
The suite checks a decimal invoice total and a whole-box count, then records an offline printer as a skip. Change the expected box count to see the process exit with status 1. Install Blyx 0.2.1, Rust and a host linker, then run these commands.
Start with wr_begin, pass the returned suite to each check or skip, then call process_exit(wr_end(suite)). The producer emits a trailing TAP plan. Names are truncated at a line break or # to keep the stream unambiguous. Relative tolerance ranges from zero to one. Inputs for measurements and tolerances must be finite.
Function
Behavior
wr_begin(), wr_check(suite, passed, label)
Import tap. Start a TAP stream and record numbered checks.
wr_skip(suite, label, detail), wr_end(suite)
Declare a skip and finish with a plan. wr_end returns 1 when a check failed.
wr_near(actual, expected, absolute, relative)
Compare using the larger of an absolute tolerance and a tolerance scaled by the larger input magnitude.
// Blyx Wren 0.1.0, MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-wren/tree/v0.1.0
// Compare finite measurements using the larger of an absolute and relative tolerance.
pub fn wr_near(actual: f64, expected: f64, absolute: f64, relative: f64) -> bool {
if actual - actual != 0.0 || expected - expected != 0.0 { return false; }
if absolute - absolute != 0.0 || relative - relative != 0.0 || absolute < 0.0 || relative < 0.0 || relative > 1.0 { return false; }
if actual == expected { return true; }
let mut a = actual;
let mut b = expected;
if a < 0.0 { a = -a; }
if b < 0.0 { b = -b; }
let mut scale = a;
if b > scale { scale = b; }
let mut diff = actual - expected;
if diff < 0.0 { diff = -diff; }
if diff <= absolute { return true; }
if relative == 0.0 { return false; }
// Scaling first is only necessary when subtraction overflows.
if diff - diff == 0.0 { return diff / scale <= relative; }
let mut norm = actual / scale - expected / scale;
if norm < 0.0 { norm = -norm; }
norm <= relative
}
pub fn wr_start() -> vector { [0, 0, 0] }
pub fn wr_record(state: vector, passed: bool, skipped: bool) -> vector {
if len(state) != 3 { return []; }
let total = at(state, 0) + 1.0;
let failed = at(state, 1);
let skip = at(state, 2);
if skipped { return [total, failed, skip + 1.0]; }
if passed { return [total, failed, skip]; }
[total, failed + 1.0, skip]
}
pub fn wr_exit(state: vector) -> i64 {
if len(state) != 3 || at(state, 1) != 0.0 { return 1; }
0
}
fn main() {
let first = wr_record(wr_start(), wr_near(0.1 + 0.2, 0.3, 0.000001, 0.0), false);
let second = wr_record(first, false, true);
let result = wr_record(second, 2 * 2 == 5, false);
println!(at(result, 0));
println!(at(result, 1));
println!(at(result, 2));
println!(wr_exit(result));
}
Expected output
3
1
1
1
Practice
Correct the failing arithmetic check and predict the exit code.
Hint
Change only the worked example’s input. The API table describes the output.
Solution
The suite still contains three cases and one skip, with zero failures and status zero.
Find
2 * 2 == 5
Replace with
2 * 2 == 4
Output after the change
3
0
1
0
Framework projects
Weaver · Render a file chooser as SVG
Lay out equal-width tiles on small or large viewports, distribute leftover pixels and map pointer coordinates back to an item.
The developer problem
A grid can draw a tile in one place and dispatch a click to its neighbor if painting and input code round dimensions differently. CSS Grid describes how tracks and gaps form a layout. Weaver uses one integer track calculation for both drawing and input.
The example draws five file tiles in three columns. The final row has two items. Use the same geometry for touch or mouse hit testing when embedding the layout in a UI host. Install Blyx 0.2.1, Rust and a host linker, then run these commands.
Use integer logical pixels. Width, inset, gap, minimum width and row height support values up to 1,000,000. The column limit is 1–10,000, and a grid can address 1,000,000 items. Invalid geometry produces an empty rectangle or a missed hit. Right and bottom edges are exclusive. A narrow positive content area uses one column.
Function
Behavior
we_columns(width, inset, gap, minimum, limit)
Choose a responsive column count; zero indicates an empty or invalid content area.
// Blyx Weaver 0.1.0, MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-weaver/tree/v0.1.0
// Integer logical pixels. Layout and hit testing use the same track formula.
fn we_dimension(v: i64) -> bool { v >= 0 && v <= 1000000 }
pub fn we_columns(width: i64, inset: i64, gap: i64, minimum: i64, limit: i64) -> i64 {
if !we_dimension(width) || !we_dimension(inset) || !we_dimension(gap) || !we_dimension(minimum) || minimum < 1 || limit < 1 || limit > 10000 { return 0; }
let space = width - 2 * inset;
if space < 1 { return 0; }
let fit = (space + gap) / (minimum + gap);
if fit < 1 { return 1; }
if fit > limit { return limit; }
fit
}
fn we_valid(width: i64, inset: i64, gap: i64, cols: i64, row_height: i64) -> bool {
we_dimension(width) && we_dimension(inset) && we_dimension(gap) && we_dimension(row_height) && row_height > 0 && cols >= 1 && cols <= 10000 && width - 2 * inset - (cols - 1) * gap >= cols
}
fn we_left(space: i64, cols: i64, gap: i64, inset: i64, col: i64) -> i64 {
let mut extra = col;
if extra > space % cols { extra = space % cols; }
inset + col * (space / cols + gap) + extra
}
pub fn we_rect(width: i64, inset: i64, gap: i64, cols: i64, row_height: i64, index: i64) -> vector {
if !we_valid(width, inset, gap, cols, row_height) || index < 0 || index >= 1000000 { return []; }
let col = index % cols;
let space = width - 2 * inset - (cols - 1) * gap;
let left = we_left(space, cols, gap, inset, col);
let mut cell = space / cols;
if col < space % cols { cell += 1; }
[left, inset + (index / cols) * (row_height + gap), cell, row_height]
}
pub fn we_hit(width: i64, inset: i64, gap: i64, cols: i64, row_height: i64, count: i64, x: i64, y: i64) -> i64 {
if !we_valid(width, inset, gap, cols, row_height) || count < 0 || count > 1000000 { return -1; }
if x < inset || x >= width - inset || y < inset { return -1; }
let row = (y - inset) / (row_height + gap);
if row >= count || (y - inset) % (row_height + gap) >= row_height { return -1; }
let space = width - 2 * inset - (cols - 1) * gap;
let mut low = 0;
let mut high = cols;
while low + 1 < high {
let mid = low + (high - low) / 2;
if we_left(space, cols, gap, inset, mid) <= x { low = mid; } else { high = mid; }
}
let id = row * cols + low;
if id >= count || x >= we_left(space, cols, gap, inset, low + 1) - gap { return -1; }
id
}
fn main() {
let columns = we_columns(320, 8, 8, 80, 6);
let second = we_rect(320, 8, 8, columns, 48, 1);
println!(columns);
println!(at(second, 0));
println!(we_hit(320, 8, 8, columns, 48, 5, 113, 19));
}
Expected output
3
112
1
Practice
Move the pointer four pixels left into the gutter. Which item receives it?
Hint
Change only the worked example’s input. The API table describes the output.
Solution
The coordinates fall between tracks, so the result is −1.
Find
5, 113, 19
Replace with
5, 109, 19
Output after the change
3
112
-1
Framework projects
Dipper · Import a two-column notes file
Parse quoted CSV records, preserve embedded line breaks, and validate a row width before consuming a file.
The developer problem
Splitting each line on commas changes both field contents and record counts when a field contains a quoted comma or newline. RFC 4180 describes the quoting and doubled-quote rules that the Dipper parser uses.
The importer preserves a literal quote in the first note and an embedded newline in the second. Give it a UTF-8 CSV file to check its width before reading the note column. Install Blyx 0.2.1, Rust and a host linker, then run these commands.
Parse a UTF-8 string in memory. Delimiters are commas. Records accept CRLF, LF or CR; embedded quoted newlines preserve their original bytes. Spaces are data. A malformed quote discards partial results. Empty input contains zero rows; a blank line holds one empty cell. di_bad_row applies a caller-supplied column count.
Function
Behavior
di_parse(input), di_ok(records)
Import csv. Parse into F-prefixed field events and R end-of-row events. A lone E-prefixed event describes a syntax error.
di_cell(records, row, column)
Return one string for a present cell, including an empty cell; an absent cell returns an empty list.
di_bad_row(records, width)
Return the first zero-based row of the wrong width, −1 for success or −2 for a parse or argument error.
di_transition(state, token), di_shape(tokens)
Walk the portable quote state machine. A valid stream yields [rows, fields].
Verify a change
Run the package checks from its release directory. Compare the browser example with its expected output, then change the input in the exercise below.
// Blyx Dipper 0.1.0, MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-dipper/tree/v0.1.0
// States: field start (0), bare (1), quoted (2), after closing quote (3).
// Tokens: nonempty text (0), comma (1), quote (2), record break (3).
pub fn di_transition(state: i64, token: i64) -> i64 {
if state < 0 || state > 3 || token < 0 || token > 3 { return -1; }
if state == 2 {
if token == 2 { return 3; }
return 2;
}
if token == 1 || token == 3 { return 0; }
if token == 2 {
if state == 0 || state == 3 { return 2; }
return -1;
}
if state == 3 { return -1; }
1
}
pub fn di_complete(state: i64) -> bool { state == 0 || state == 1 || state == 3 }
// For a token stream, report [rows, fields], or [] on malformed input.
pub fn di_shape(tokens: vector) -> vector {
let mut state = 0;
let mut rows = 0;
let mut fields = 0;
let mut pending = false;
let mut i = 0;
while i < len(tokens) {
let value = at(tokens, i);
let mut kind = 0;
while kind < 4 && at([kind], 0) != value { kind += 1; }
let next = di_transition(state, kind);
if next < 0 { return []; }
pending = true;
if state != 2 {
if kind == 1 { fields += 1; }
if kind == 3 { fields += 1; rows += 1; pending = false; }
}
state = next;
i += 1;
}
if !di_complete(state) { return []; }
if pending { fields += 1; rows += 1; }
[rows, fields]
}
fn main() {
// Tokens for a quoted field containing a comma followed by a second field.
let shape = di_shape([2, 0, 1, 0, 2, 1, 0, 3]);
println!(at(shape, 0));
println!(at(shape, 1));
println!(len(di_shape([2, 0])));
}
Expected output
1
2
0
Practice
Append a third field before the final record break.
Hint
Change only the worked example’s input. The API table describes the output.
Solution
The extra delimiter is outside quotes, so the row now has three fields.
Find
[2, 0, 1, 0, 2, 1, 0, 3]
Replace with
[2, 0, 1, 0, 2, 1, 0, 1, 0, 3]
Output after the change
1
3
0
Framework projects
Kestrel · Replay a bouncing ball across a stalled frame
Run a bounded number of simulation ticks per rendered frame, carry fractional frame time and interpolate a moving object between updates.
The developer problem
Rendering at a changing frame rate can change simulation speed. A long pause can also produce a burst of catch-up work. Godot’s physics interpolation guide explains the separate clocks. Kestrel makes the carry, interpolation fraction and discarded time visible to the application.
Feed the same five frame times into a fixed-step ball simulation. One 100 ms stall exceeds the catch-up limit. The replay reports positions and the number of milliseconds discarded. Install Blyx 0.2.1, Rust and a host linker, then run these commands.
Use whole milliseconds from 0 to 1,000,000,000, a positive step and a remainder smaller than that step. max_steps is 1–1,000,000. The clock returns an empty vector for invalid input. A frame cap discards whole ticks only. The simulation takes frame durations from the caller so a replay needs no wall clock.
Function
Behavior
ke_clock(carry, elapsed, step, max_steps)
Return [updates, remainder_ms, discarded_ms, interpolation_fraction]. Feed remainder_ms into the next frame.
ke_lerp(previous, current, fraction)
Interpolate a render position between the last two simulated positions.
ke_bounce(position, velocity, dt, low, high)
Advance one object on a bounded 1D track. The result holds position and velocity, including repeated wall crossings.
Verify a change
Run the package checks from its release directory. Compare the browser example with its expected output, then change the input in the exercise below.
// Blyx Kestrel 0.1.0, MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-kestrel/tree/v0.1.0
fn ke_time(ms: f64) -> bool {
ms >= 0.0 && ms <= 1000000000.0 && ms % 1.0 == 0.0
}
// Return [fixed updates, carried milliseconds, dropped milliseconds, render alpha].
pub fn ke_clock(carry: f64, elapsed: f64, step: f64, max_steps: i64) -> vector {
if !ke_time(step) || step == 0.0 || !ke_time(elapsed) || !ke_time(carry) || carry >= step || max_steps < 1 || max_steps > 1000000 { return []; }
let total = carry + elapsed;
let next = total % step;
let available = (total - next) / step;
let mut updates = available;
let limit = at([max_steps], 0);
if updates > limit { updates = limit; }
[updates, next, (available - updates) * step, next / step]
}
pub fn ke_lerp(previous: f64, current: f64, alpha: f64) -> f64 {
(1.0 - alpha) * previous + alpha * current
}
// Advance an object along a bounded one-dimensional track with elastic walls.
// At an exact wall the stored velocity points inward for the next update.
pub fn ke_bounce(position: f64, velocity: f64, dt: f64, low: f64, high: f64) -> vector {
if !(low < high && position >= low && position <= high && dt >= 0.0) { return []; }
let span = high - low;
let period = 2.0 * span;
let travel = (position - low) + velocity * dt;
if period - period != 0.0 || travel - travel != 0.0 { return []; }
let mut phase = travel % period;
if phase < 0.0 { phase += period; }
let mut speed = velocity;
if speed < 0.0 { speed = -speed; }
if phase == 0.0 { return [low, speed]; }
if phase == span { return [high, -speed]; }
if phase < span { return [low + phase, velocity]; }
[high - (phase - span), -velocity]
}
fn main() {
let frame = ke_clock(5.0, 50.0, 10.0, 3);
println!(at(frame, 0));
println!(at(frame, 1));
println!(at(frame, 2));
println!(at(frame, 3));
}
Expected output
3
5
20
0.5
Practice
Increase the catch-up limit from three ticks to five. What happens to the carry?
Hint
Change only the worked example’s input. The API table describes the output.
Solution
All five whole ticks run; the remaining five milliseconds still set the render fraction to 0.5.
Find
50.0, 10.0, 3
Replace with
50.0, 10.0, 5
Output after the change
5
5
0
0.5
Framework projects
Heron · Audit a sensor heartbeat trace
Track one sensor feed’s accepted messages, duplicate sequence numbers, out-of-order arrivals and missed deadlines.
The developer problem
A replayed packet can make an idle sensor appear healthy if every arrival resets its last-seen timer. ROS 2 distinguishes delivery and deadline policies. Heron lets an application choose a freshness deadline and updates that timer only when it accepts a new sample.
Replay sequence and local receipt-time pairs. The bundled trace contains a duplicate, a two-ID gap and one out-of-order delivery. You can feed your own two-column headerless trace into the same program. Install Blyx 0.2.1, Rust and a host linker, then run these commands.
Maintain one state per sensor. Use a monotonically increasing integer sequence and a monotonic local receipt clock in milliseconds, both at most 2^53−1. Reset the state when the sensor restarts or its sequence wraps. The gap counter records skipped IDs at acceptance time. Late arrivals do not reduce it. This release monitors application data and exposes its state to the host.
// Blyx Heron 0.1.0, MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-heron/tree/v0.1.0
// [last sequence, receipt ms, accepted, duplicates, out of order, skipped IDs].
pub fn he_start() -> vector { [-1, -1, 0, 0, 0, 0] }
fn he_integer(n: f64) -> bool { n >= 0.0 && n <= 9007199254740991.0 && n % 1.0 == 0.0 }
pub fn he_observe(state: vector, sequence: f64, receipt: f64) -> vector {
if len(state) != 6 || !he_integer(sequence) || !he_integer(receipt) { return []; }
let last = at(state, 0);
let stamp = at(state, 1);
let accepted = at(state, 2);
let duplicate = at(state, 3);
let late = at(state, 4);
let gaps = at(state, 5);
if sequence < last || receipt < stamp { return [last, stamp, accepted, duplicate, late + 1.0, gaps]; }
if sequence == last { return [last, stamp, accepted, duplicate + 1.0, late, gaps]; }
let mut missing = 0.0;
if last >= 0.0 { missing = sequence - last - 1.0; }
[sequence, receipt, accepted + 1.0, duplicate, late, gaps + missing]
}
pub fn he_age(state: vector, now: f64) -> f64 {
if len(state) != 6 || at(state, 1) < 0.0 || !he_integer(now) || now < at(state, 1) { return -1.0; }
now - at(state, 1)
}
pub fn he_status(state: vector, now: f64, deadline: f64) -> str {
if len(state) != 6 || !he_integer(now) || !he_integer(deadline) { return "invalid"; }
if at(state, 0) < 0.0 { return "unseen"; }
let age = he_age(state, now);
if age < 0.0 { return "invalid"; }
if age > deadline { return "late"; }
"current"
}
fn main() {
let first = he_observe(he_start(), 10.0, 100.0);
let next = he_observe(first, 13.0, 120.0);
let repeated = he_observe(next, 13.0, 145.0);
println!(at(repeated, 5));
println!(at(repeated, 3));
println!(he_status(repeated, 151.0, 30.0));
}
Expected output
2
1
late
Practice
Check the feed exactly 30 ms after its last accepted receipt.
Hint
Change only the worked example’s input. The API table describes the output.
Solution
Age equals the deadline, so the feed is current. It becomes late one millisecond later.
Find
151.0, 30.0
Replace with
150.0, 30.0
Output after the change
2
1
current
Workflow recipes
Oriole · Decide when a reviewed revision can go live
Decide whether a scheduled revision can go live after independent review.
Decide when a reviewed revision can go live
A scheduled revision can reach its start time while a second approval is still missing. Track both conditions against the same clock. At tick 12 two distinct reviewers have approved the revision. A duplicate approval cannot replace the second reviewer.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [publish now, lifecycle phase, approvals missing, ticks to next transition]. The caller supplies the clock and persists the revision. Invalid input returns an empty vector.
Argument
Accepted input
now
exact signed integer
opens
exact signed integer
closes
exact signed integer
reviewers
Vector of: nonnegative exact integer
required
positive exact integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Oriole 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-oriole/tree/v0.1.0
fn releasewindow_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn releasewindow_compute(now: f64, opens: f64, closes: f64) -> vector {
if closes <= opens {
return [];
}
if now < opens {
return [0, opens - now];
}
if now < closes {
return [1, closes - now];
}
[2, 0]
}
// Locate a clock tick within a scheduled publication window.
// Returns [phase, ticks until the next change]. Phase 0 is scheduled, 1 is live and 2 is expired. The closing tick is exclusive.
pub fn releasewindow_locate(now: f64, opens: f64, closes: f64) -> vector {
if !(now >= -9007199254740991.0 && now <= 9007199254740991.0 && now % 1.0 == 0.0) { return []; }
if !(opens >= -9007199254740991.0 && opens <= 9007199254740991.0 && opens % 1.0 == 0.0) { return []; }
if !(closes >= -9007199254740991.0 && closes <= 9007199254740991.0 && closes % 1.0 == 0.0) { return []; }
let result = releasewindow_compute(now, opens, closes);
if !releasewindow_finite(result) { return []; }
result
}
fn reviewquorum_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn reviewquorum_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn reviewquorum_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn reviewquorum_compute(reviewers: vector, required: f64) -> vector {
let mut unique = 0.0;
let mut i = 0;
while i < len(reviewers) {
let mut j = 0;
while j < i && at(reviewers, j) != at(reviewers, i) {
j += 1;
}
if j == i {
unique += 1.0;
}
i += 1;
}
[unique, reviewquorum_max2(0.0, required - unique)]
}
// Count independent reviewers and calculate outstanding approvals.
// Returns [unique reviewer IDs, approvals still required]. A repeated ID contributes once.
pub fn reviewquorum_tally(reviewers: vector, required: f64) -> vector {
if !reviewquorum_counts(reviewers) { return []; }
if !(required >= 1.0 && required <= 9007199254740991.0 && required % 1.0 == 0.0) { return []; }
let result = reviewquorum_compute(reviewers, required);
if !reviewquorum_finite(result) { return []; }
result
}
fn oriole_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn oriole_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn oriole_compute(now: f64, opens: f64, closes: f64, reviewers: vector, required: f64) -> vector {
let window = releasewindow_locate(now, opens, closes);
let votes = reviewquorum_tally(reviewers, required);
if len(window) == 0 || len(votes) == 0 {
return [];
}
let mut publish = 0;
if at(window, 0) == 1.0 && at(votes, 1) == 0.0 {
publish = 1;
}
[publish, at(window, 0), at(votes, 1), at(window, 1)]
}
// Decide whether a scheduled revision can go live after independent review.
// Returns [publish now, lifecycle phase, approvals missing, ticks to next transition]. The caller supplies the clock and persists the revision.
pub fn oriole_decide(now: f64, opens: f64, closes: f64, reviewers: vector, required: f64) -> vector {
if !(now >= -9007199254740991.0 && now <= 9007199254740991.0 && now % 1.0 == 0.0) { return []; }
if !(opens >= -9007199254740991.0 && opens <= 9007199254740991.0 && opens % 1.0 == 0.0) { return []; }
if !(closes >= -9007199254740991.0 && closes <= 9007199254740991.0 && closes % 1.0 == 0.0) { return []; }
if !oriole_counts(reviewers) { return []; }
if !(required >= 1.0 && required <= 9007199254740991.0 && required % 1.0 == 0.0) { return []; }
let result = oriole_compute(now, opens, closes, reviewers, required);
if !oriole_finite(result) { return []; }
result
}
fn main() {
let now = 12.0;
let opens = 10.0;
let closes = 20.0;
let reviewers = [4, 4, 8];
let required = 2.0;
let result = oriole_decide(now, opens, closes, reviewers, required);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
1
1
0
8
Practice
Change reviewers = [4, 4]. Predict the result, then run the program.
Hint
Returns [publish now, lifecycle phase, approvals missing, ticks to next transition]. The caller supplies the clock and persists the revision.
Solution
The result vector is [0, 1, 1, 8]. Compare its fields with the return layout in the API section.
Find
let reviewers = [4, 4, 8];
Replace with
let reviewers = [4, 4];
Output after the change
0
1
1
8
Workflow recipes
Avocet · Reorder stock after reservations
Plan replenishment after existing reservations and supplier lot sizes.
Reorder stock after reservations
Reservations can exhaust a shelf before a reorder calculation runs. Lot-size rounding must include existing backorders. Seven units are on hold. Three units remain free, so buying two lots of four brings free stock to eleven.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [available, existing shortage, purchase units, projected free units]. Target is the desired free stock after all holds. Invalid input returns an empty vector.
Argument
Accepted input
onhand
nonnegative exact integer
holds
Vector of: nonnegative exact integer
target
nonnegative exact integer
lot
positive exact integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Avocet 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-avocet/tree/v0.1.0
fn stockledger_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn stockledger_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn stockledger_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn stockledger_compute(onhand: f64, holds: vector) -> vector {
let used = sum(holds);
if used > 9007199254740991.0 {
return [];
}
[stockledger_max2(0.0, onhand - used), stockledger_max2(0.0, used - onhand)]
}
// Reconcile on-hand inventory with individual outstanding reservations.
// Returns [available units, overcommitted units]. Reservations are nonnegative whole units.
pub fn stockledger_balance(onhand: f64, holds: vector) -> vector {
if !(onhand >= 0.0 && onhand <= 9007199254740991.0 && onhand % 1.0 == 0.0) { return []; }
if !stockledger_counts(holds) { return []; }
let result = stockledger_compute(onhand, holds);
if !stockledger_finite(result) { return []; }
result
}
fn lotround_ceilpos(value: f64) -> f64 {
let rest = value % 1.0;
if rest > 0.0 {
return value - rest + 1.0;
}
value
}
fn lotround_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn lotround_compute(need: f64, lot: f64) -> vector {
let lots = lotround_ceilpos(need / lot);
let units = lots * lot;
if units > 9007199254740991.0 {
return [];
}
[lots, units, units - need]
}
// Round a shortage to a supplier's whole purchase lots.
// Returns [lots to order, supplied units, surplus]. A zero shortage orders zero lots.
pub fn lotround_order(need: f64, lot: f64) -> vector {
if !(need >= 0.0 && need <= 9007199254740991.0 && need % 1.0 == 0.0) { return []; }
if !(lot >= 1.0 && lot <= 9007199254740991.0 && lot % 1.0 == 0.0) { return []; }
let result = lotround_compute(need, lot);
if !lotround_finite(result) { return []; }
result
}
fn avocet_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn avocet_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn avocet_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn avocet_compute(onhand: f64, holds: vector, target: f64, lot: f64) -> vector {
let stock = stockledger_balance(onhand, holds);
if len(stock) == 0 {
return [];
}
let missing = avocet_max2(0.0, target - at(stock, 0) + at(stock, 1));
let order = lotround_order(missing, lot);
if len(order) == 0 {
return [];
}
[at(stock, 0), at(stock, 1), at(order, 1), at(stock, 0) - at(stock, 1) + at(order, 1)]
}
// Plan replenishment after existing reservations and supplier lot sizes.
// Returns [available, existing shortage, purchase units, projected free units]. Target is the desired free stock after all holds.
pub fn avocet_plan(onhand: f64, holds: vector, target: f64, lot: f64) -> vector {
if !(onhand >= 0.0 && onhand <= 9007199254740991.0 && onhand % 1.0 == 0.0) { return []; }
if !avocet_counts(holds) { return []; }
if !(target >= 0.0 && target <= 9007199254740991.0 && target % 1.0 == 0.0) { return []; }
if !(lot >= 1.0 && lot <= 9007199254740991.0 && lot % 1.0 == 0.0) { return []; }
let result = avocet_compute(onhand, holds, target, lot);
if !avocet_finite(result) { return []; }
result
}
fn main() {
let onhand = 10.0;
let holds = [3, 4];
let target = 8.0;
let lot = 4.0;
let result = avocet_plan(onhand, holds, target, lot);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
3
0
8
11
Practice
Change onhand = 2.0, holds = [5], target = 4.0, lot = 3.0. Predict the result, then run the program.
Hint
Returns [available, existing shortage, purchase units, projected free units]. Target is the desired free stock after all holds.
Solution
The result vector is [0, 3, 9, 6]. Compare its fields with the return layout in the API section.
Find
let onhand = 10.0;
Replace with
let onhand = 2.0;
Find
let holds = [3, 4];
Replace with
let holds = [5];
Find
let target = 8.0;
Replace with
let target = 4.0;
Find
let lot = 4.0;
Replace with
let lot = 3.0;
Output after the change
0
3
9
6
Workflow recipes
Ibis · Reconcile split invoice payments
Reconcile an invoice with split payments in integer minor units.
Reconcile split invoice payments
Partial payments and overpayments must remain distinguishable when an invoice is reconciled. Two invoice lines total 300 minor units. The payments total 325, leaving 25 as credit.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [subtotal, applied payment, open balance, credit]. Use a single currency and already-posted amounts. Invalid input returns an empty vector.
Argument
Accepted input
units
Vector of: nonnegative exact integer
prices
Vector of: nonnegative exact integer
payments
Vector of: nonnegative exact integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Ibis 0.1.1 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-ibis/tree/v0.1.1
fn lineamount_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn lineamount_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn lineamount_compute(units: vector, prices: vector) -> vector {
if len(units) != len(prices) {
return [];
}
let mut total = 0.0;
let mut lines = 0;
let mut i = 0;
while i < len(units) {
let q = at(units, i);
let price = at(prices, i);
if q > 0.0 && price > (9007199254740991.0 - total) / q {
return [];
}
total += q * price;
if q > 0.0 {
lines += 1;
}
i += 1;
}
[total, lines]
}
// Extend paired invoice quantities and prices in integer minor units.
// Returns [subtotal, nonzero lines]. Rejects unmatched columns and totals beyond exact integer representation.
pub fn lineamount_subtotal(units: vector, prices: vector) -> vector {
if !lineamount_counts(units) { return []; }
if !lineamount_counts(prices) { return []; }
let result = lineamount_compute(units, prices);
if !lineamount_finite(result) { return []; }
result
}
fn cashmatch_min2(a: f64, b: f64) -> f64 {
if a < b {
return a;
}
b
}
fn cashmatch_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn cashmatch_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn cashmatch_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn cashmatch_compute(due: f64, payments: vector) -> vector {
let paid = sum(payments);
if paid > 9007199254740991.0 {
return [];
}
[cashmatch_min2(paid, due), cashmatch_max2(0.0, due - paid), cashmatch_max2(0.0, paid - due)]
}
// Apply posted payments and preserve customer credit separately.
// Returns [applied, still due, overpayment] in a single currency's minor units.
pub fn cashmatch_apply(due: f64, payments: vector) -> vector {
if !(due >= 0.0 && due <= 9007199254740991.0 && due % 1.0 == 0.0) { return []; }
if !cashmatch_counts(payments) { return []; }
let result = cashmatch_compute(due, payments);
if !cashmatch_finite(result) { return []; }
result
}
fn ibis_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn ibis_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn ibis_compute(units: vector, prices: vector, payments: vector) -> vector {
let lines = lineamount_subtotal(units, prices);
if len(lines) == 0 {
return [];
}
let settle = cashmatch_apply(at(lines, 0), payments);
if len(settle) == 0 {
return [];
}
[at(lines, 0), at(settle, 0), at(settle, 1), at(settle, 2)]
}
// Reconcile an invoice with split payments in integer minor units.
// Returns [subtotal, applied payment, open balance, credit]. Use a single currency and already-posted amounts.
pub fn ibis_reconcile(units: vector, prices: vector, payments: vector) -> vector {
if !ibis_counts(units) { return []; }
if !ibis_counts(prices) { return []; }
if !ibis_counts(payments) { return []; }
let result = ibis_compute(units, prices, payments);
if !ibis_finite(result) { return []; }
result
}
fn main() {
let units = [2, 1];
let prices = [125, 50];
let payments = [200, 125];
let result = ibis_reconcile(units, prices, payments);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
300
300
0
25
Practice
Change units = [2], prices = [10], payments = [4]. Predict the result, then run the program.
Hint
Returns [subtotal, applied payment, open balance, credit]. Use a single currency and already-posted amounts.
Solution
The result vector is [20, 4, 16, 0]. Compare its fields with the return layout in the API section.
Find
let units = [2, 1];
Replace with
let units = [2];
Find
let prices = [125, 50];
Replace with
let prices = [10];
Find
let payments = [200, 125];
Replace with
let payments = [4];
Output after the change
20
4
16
0
Workflow recipes
Pipit · Resume a batch after a failed command
Plan the next CLI batch from child exit codes and a failure allowance.
Resume a batch after a failed command
A batch script can erase an earlier error when the last child exits successfully. Use the whole exit trace to decide whether work should continue. One of three commands failed with exit code 3. The configured allowance permits two further commands.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [next offset, next count, failures, first nonzero exit]. The next count becomes zero once failures exceed the allowance. Invalid input returns an empty vector.
Argument
Accepted input
codes
Vector of: whole byte in [0,255]
total
nonnegative exact integer
batch
positive exact integer
tolerance
nonnegative exact integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Pipit 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-pipit/tree/v0.1.0
fn exitpolicy_bytes(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 255.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn exitpolicy_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn exitpolicy_compute(codes: vector) -> vector {
let mut failures = 0;
let mut first = -1;
let mut code = 0.0;
let mut i = 0;
while i < len(codes) {
if at(codes, i) != 0.0 {
if first < 0 {
first = i;
code = at(codes, i);
}
failures += 1;
}
i += 1;
}
[failures, code, first]
}
// Summarize portable process exit codes without losing the first failure.
// Returns [failed commands, first nonzero exit code, first failing index]. An all-success run uses index -1.
pub fn exitpolicy_summarize(codes: vector) -> vector {
if !exitpolicy_bytes(codes) { return []; }
let result = exitpolicy_compute(codes);
if !exitpolicy_finite(result) { return []; }
result
}
fn batchquota_min2(a: f64, b: f64) -> f64 {
if a < b {
return a;
}
b
}
fn batchquota_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn batchquota_compute(done: f64, total: f64, limit: f64) -> vector {
if done > total {
return [];
}
let take = batchquota_min2(limit, total - done);
[done, take, total - done - take]
}
// Bound the next batch of an interrupted command.
// Returns [next offset, batch length, remaining after batch]. A finished batch has zero length.
pub fn batchquota_allow(done: f64, total: f64, limit: f64) -> vector {
if !(done >= 0.0 && done <= 9007199254740991.0 && done % 1.0 == 0.0) { return []; }
if !(total >= 0.0 && total <= 9007199254740991.0 && total % 1.0 == 0.0) { return []; }
if !(limit >= 1.0 && limit <= 9007199254740991.0 && limit % 1.0 == 0.0) { return []; }
let result = batchquota_compute(done, total, limit);
if !batchquota_finite(result) { return []; }
result
}
fn pipit_num(value: i64) -> f64 {
at([value], 0)
}
fn pipit_bytes(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 255.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn pipit_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn pipit_compute(codes: vector, total: f64, batch: f64, tolerance: f64) -> vector {
let status = exitpolicy_summarize(codes);
let next = batchquota_allow(pipit_num(len(codes)), total, batch);
if len(next) == 0 || len(status) == 0 {
return [];
}
let mut count = at(next, 1);
if at(status, 0) > tolerance {
count = 0.0;
}
[at(next, 0), count, at(status, 0), at(status, 1)]
}
// Plan the next CLI batch from child exit codes and a failure allowance.
// Returns [next offset, next count, failures, first nonzero exit]. The next count becomes zero once failures exceed the allowance.
pub fn pipit_continue_batch(codes: vector, total: f64, batch: f64, tolerance: f64) -> vector {
if !pipit_bytes(codes) { return []; }
if !(total >= 0.0 && total <= 9007199254740991.0 && total % 1.0 == 0.0) { return []; }
if !(batch >= 1.0 && batch <= 9007199254740991.0 && batch % 1.0 == 0.0) { return []; }
if !(tolerance >= 0.0 && tolerance <= 9007199254740991.0 && tolerance % 1.0 == 0.0) { return []; }
let result = pipit_compute(codes, total, batch, tolerance);
if !pipit_finite(result) { return []; }
result
}
fn main() {
let codes = [0, 3, 0];
let total = 8.0;
let batch = 2.0;
let tolerance = 1.0;
let result = pipit_continue_batch(codes, total, batch, tolerance);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
3
2
1
3
Practice
Change codes = [0, 3], tolerance = 0.0. Predict the result, then run the program.
Hint
Returns [next offset, next count, failures, first nonzero exit]. The next count becomes zero once failures exceed the allowance.
Solution
The result vector is [2, 0, 1, 3]. Compare its fields with the return layout in the API section.
Find
let codes = [0, 3, 0];
Replace with
let codes = [0, 3];
Find
let tolerance = 1.0;
Replace with
let tolerance = 0.0;
Output after the change
2
0
1
3
Workflow recipes
Nuthatch · Keep terminal help visible after a resize
Wrap a message and preserve a valid scroll position after resizing a terminal.
Keep terminal help visible after a resize
After a terminal becomes wider, the old scroll offset can leave an otherwise valid help screen blank. Four words each occupy their own line. A scroll request past the end selects the last two visible lines.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [wrapped line count, first visible line, exclusive end, last line width]. The host supplies display-cell widths for its font. Invalid input returns an empty vector.
Argument
Accepted input
widths
Vector of: nonnegative exact integer
columns
positive exact integer
start
nonnegative exact integer
height
positive exact integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Nuthatch 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-nuthatch/tree/v0.1.0
fn wordrows_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn wordrows_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn wordrows_compute(widths: vector, columns: f64) -> vector {
let mut lines = 0;
let mut used = 0.0;
let mut i = 0;
while i < len(widths) {
let width = at(widths, i);
if width == 0.0 || width > columns {
return [];
}
if used == 0.0 || used + 1.0 + width > columns {
lines += 1;
used = width;
} else {
used += 1.0 + width;
}
i += 1;
}
[lines, used]
}
// Count greedy terminal lines from premeasured word widths.
// Returns [lines, last line width]. One display cell separates words. Empty input uses zero lines; zero-width and oversize words are rejected.
pub fn wordrows_measure(widths: vector, columns: f64) -> vector {
if !wordrows_counts(widths) { return []; }
if !(columns >= 1.0 && columns <= 9007199254740991.0 && columns % 1.0 == 0.0) { return []; }
let result = wordrows_compute(widths, columns);
if !wordrows_finite(result) { return []; }
result
}
fn viewportion_min2(a: f64, b: f64) -> f64 {
if a < b {
return a;
}
b
}
fn viewportion_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn viewportion_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn viewportion_compute(rows: f64, start: f64, height: f64) -> vector {
let first = viewportion_min2(start, viewportion_max2(0.0, rows - height));
let end = viewportion_min2(rows, first + height);
[first, end, rows - end]
}
// Clamp a terminal scroll offset to a filled viewport.
// Returns [first visible row, exclusive end row, rows hidden below]. A short document starts at zero.
pub fn viewportion_slice(rows: f64, start: f64, height: f64) -> vector {
if !(rows >= 0.0 && rows <= 9007199254740991.0 && rows % 1.0 == 0.0) { return []; }
if !(start >= 0.0 && start <= 9007199254740991.0 && start % 1.0 == 0.0) { return []; }
if !(height >= 1.0 && height <= 9007199254740991.0 && height % 1.0 == 0.0) { return []; }
let result = viewportion_compute(rows, start, height);
if !viewportion_finite(result) { return []; }
result
}
fn nuthatch_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn nuthatch_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn nuthatch_compute(widths: vector, columns: f64, start: f64, height: f64) -> vector {
let flow = wordrows_measure(widths, columns);
if len(flow) == 0 {
return [];
}
let view = viewportion_slice(at(flow, 0), start, height);
if len(view) == 0 {
return [];
}
[at(flow, 0), at(view, 0), at(view, 1), at(flow, 1)]
}
// Wrap a message and preserve a valid scroll position after resizing a terminal.
// Returns [wrapped line count, first visible line, exclusive end, last line width]. The host supplies display-cell widths for its font.
pub fn nuthatch_layout(widths: vector, columns: f64, start: f64, height: f64) -> vector {
if !nuthatch_counts(widths) { return []; }
if !(columns >= 1.0 && columns <= 9007199254740991.0 && columns % 1.0 == 0.0) { return []; }
if !(start >= 0.0 && start <= 9007199254740991.0 && start % 1.0 == 0.0) { return []; }
if !(height >= 1.0 && height <= 9007199254740991.0 && height % 1.0 == 0.0) { return []; }
let result = nuthatch_compute(widths, columns, start, height);
if !nuthatch_finite(result) { return []; }
result
}
fn main() {
let widths = [4, 4, 4, 4];
let columns = 6.0;
let start = 99.0;
let height = 2.0;
let result = nuthatch_layout(widths, columns, start, height);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
4
2
4
4
Practice
Change widths = [2, 2], columns = 5.0, start = 0.0, height = 3.0. Predict the result, then run the program.
Hint
Returns [wrapped line count, first visible line, exclusive end, last line width]. The host supplies display-cell widths for its font.
Solution
The result vector is [1, 0, 1, 5]. Compare its fields with the return layout in the API section.
Find
let widths = [4, 4, 4, 4];
Replace with
let widths = [2, 2];
Find
let columns = 6.0;
Replace with
let columns = 5.0;
Find
let start = 99.0;
Replace with
let start = 0.0;
Find
let height = 2.0;
Replace with
let height = 3.0;
Output after the change
1
0
1
5
Workflow recipes
Turnstone · Restart an interrupted chunked file job
Resume a chunked file job from acknowledged checkpoints.
Restart an interrupted chunked file job
A resumed batch can skip the final partial chunk when it treats a repeated acknowledgement as new progress. Ten bytes form three chunks of width four. The repeated checkpoint for chunk zero leaves the two-byte final chunk to process.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [next offset, byte count, remaining chunks, replayed checkpoints]. Offsets use half-open ranges. Invalid input returns an empty vector.
Argument
Accepted input
size
nonnegative exact integer
width
positive exact integer
checkpoints
Vector of: nonnegative exact integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
The result vector is [10, 0, 0, 0]. Compare its fields with the return layout in the API section.
Find
let checkpoints = [0, 0, 1];
Replace with
let checkpoints = [0, 1, 2];
Output after the change
10
0
0
0
Workflow recipes
Osprey · Score detections at the edge of a camera frame
Score a detection against a reference after clipping both to the camera frame.
Score detections at the edge of a camera frame
An out-of-frame detection can change IoU even when the visible pixels agree. Clip both boxes before evaluating their overlap. Clipping the predicted box gives four visible intersection pixels and a union of eight. IoU reaches the inclusive 0.5 threshold.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [visible IoU, matched, visible intersection area]. Match requires positive overlap and a score at least equal to the threshold. Invalid input returns an empty vector.
Argument
Accepted input
pred
Vector of: finite number
truth
Vector of: finite number
width
positive finite number
height
positive finite number
threshold
probability in [0,1]
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Osprey 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-osprey/tree/v0.1.0
fn boxoverlap_min2(a: f64, b: f64) -> f64 {
if a < b {
return a;
}
b
}
fn boxoverlap_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn boxoverlap_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn boxoverlap_compute(a: vector, b: vector) -> vector {
if len(a) != 4 || len(b) != 4 {
return [];
}
let aw = at(a, 2) - at(a, 0);
let ah = at(a, 3) - at(a, 1);
let bw = at(b, 2) - at(b, 0);
let bh = at(b, 3) - at(b, 1);
if aw <= 0.0 || ah <= 0.0 || bw <= 0.0 || bh <= 0.0 {
return [];
}
let w = boxoverlap_max2(0.0, boxoverlap_min2(at(a, 2), at(b, 2)) - boxoverlap_max2(at(a, 0), at(b, 0)));
let h = boxoverlap_max2(0.0, boxoverlap_min2(at(a, 3), at(b, 3)) - boxoverlap_max2(at(a, 1), at(b, 1)));
let hit = w * h;
let combined = aw * ah + bw * bh - hit;
if combined <= 0.0 {
return [];
}
[hit, combined, hit / combined]
}
// Measure intersection and union of two axis-aligned image boxes.
// Each rectangle is [left, top, right, bottom]. Returns [intersection area, union area, IoU]. Zero-area boxes and reversed edges are rejected.
pub fn boxoverlap_measure(a: vector, b: vector) -> vector {
if !boxoverlap_finite(a) { return []; }
if !boxoverlap_finite(b) { return []; }
let result = boxoverlap_compute(a, b);
if !boxoverlap_finite(result) { return []; }
result
}
fn boxclip_min2(a: f64, b: f64) -> f64 {
if a < b {
return a;
}
b
}
fn boxclip_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn boxclip_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn boxclip_compute(box: vector, width: f64, height: f64) -> vector {
if len(box) != 4 {
return [];
}
let left = boxclip_max2(0.0, at(box, 0));
let top = boxclip_max2(0.0, at(box, 1));
let right = boxclip_min2(width, at(box, 2));
let bottom = boxclip_min2(height, at(box, 3));
if right <= left || bottom <= top {
return [];
}
[left, top, right, bottom]
}
// Clip a detection rectangle to the visible image.
// Returns the visible [left, top, right, bottom] in continuous pixel-edge coordinates. An empty intersection is invalid.
pub fn boxclip_inside(box: vector, width: f64, height: f64) -> vector {
if !boxclip_finite(box) { return []; }
if !(width > 0.0 && width - width == 0.0) { return []; }
if !(height > 0.0 && height - height == 0.0) { return []; }
let result = boxclip_compute(box, width, height);
if !boxclip_finite(result) { return []; }
result
}
fn osprey_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn osprey_compute(pred: vector, truth: vector, width: f64, height: f64, threshold: f64) -> vector {
let pbox = boxclip_inside(pred, width, height);
let tbox = boxclip_inside(truth, width, height);
let scores = boxoverlap_measure(pbox, tbox);
if len(scores) == 0 {
return [];
}
let mut matched = 0;
if at(scores, 0) > 0.0 && at(scores, 2) >= threshold {
matched = 1;
}
[at(scores, 2), matched, at(scores, 0)]
}
// Score a detection against a reference after clipping both to the camera frame.
// Returns [visible IoU, matched, visible intersection area]. Match requires positive overlap and a score at least equal to the threshold.
pub fn osprey_compare(pred: vector, truth: vector, width: f64, height: f64, threshold: f64) -> vector {
if !osprey_finite(pred) { return []; }
if !osprey_finite(truth) { return []; }
if !(width > 0.0 && width - width == 0.0) { return []; }
if !(height > 0.0 && height - height == 0.0) { return []; }
if !(threshold >= 0.0 && threshold <= 1.0) { return []; }
let result = osprey_compute(pred, truth, width, height, threshold);
if !osprey_finite(result) { return []; }
result
}
fn main() {
let pred = [-2, 0, 2, 2];
let truth = [0, 0, 4, 2];
let width = 4.0;
let height = 4.0;
let threshold = 0.5;
let result = osprey_compare(pred, truth, width, height, threshold);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
0.5
1
4
Practice
Change pred = [0, 0, 1, 1], truth = [1, 0, 2, 1], threshold = 0.0. Predict the result, then run the program.
Hint
Returns [visible IoU, matched, visible intersection area]. Match requires positive overlap and a score at least equal to the threshold.
Solution
The result vector is [0, 0, 0]. Compare its fields with the return layout in the API section.
Find
let pred = [-2, 0, 2, 2];
Replace with
let pred = [0, 0, 1, 1];
Find
let truth = [0, 0, 4, 2];
Replace with
let truth = [1, 0, 2, 1];
Find
let threshold = 0.5;
Replace with
let threshold = 0.0;
Output after the change
0
0
0
Workflow recipes
Warbler · Distinguish a clipped transient from a sustained overload
Flag sustained clipping while reporting the energy of an audio frame.
Distinguish a clipped transient from a sustained overload
Identical peak readings can represent a single transient or a sustained overload. Inspect run length alongside frame energy. Two adjacent full-scale samples breach the one-sample allowance. Separating them with silence changes the alert.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [peak, mean square, longest clipped run, alert]. Alert means the longest run exceeded the allowed number of samples. Invalid input returns an empty vector.
Argument
Accepted input
samples
Vector of: finite number
ceiling
positive finite number
allowed
nonnegative exact integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Warbler 0.1.1 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-warbler/tree/v0.1.1
fn framesignal_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn framesignal_absolute(value: f64) -> f64 {
if value < 0.0 {
return - value;
}
value
}
fn framesignal_num(value: i64) -> f64 {
at([value], 0)
}
fn framesignal_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn framesignal_compute(samples: vector) -> vector {
if len(samples) == 0 {
return [];
}
let mut peak = 0.0;
let mut i = 0;
while i < len(samples) {
peak = framesignal_max2(peak, framesignal_absolute(at(samples, i)));
i += 1;
}
[peak, dot(samples, samples) / framesignal_num(len(samples))]
}
// Measure peak amplitude and mean-square energy of a signal frame.
// Returns [peak absolute amplitude, mean square]. Empty frames are invalid. Supply amplitudes in a common linear scale.
pub fn framesignal_level(samples: vector) -> vector {
if !framesignal_finite(samples) { return []; }
let result = framesignal_compute(samples);
if !framesignal_finite(result) { return []; }
result
}
fn clipruns_absolute(value: f64) -> f64 {
if value < 0.0 {
return - value;
}
value
}
fn clipruns_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn clipruns_compute(samples: vector, ceiling: f64) -> vector {
let mut total = 0;
let mut run = 0;
let mut longest = 0;
let mut runs = 0;
let mut i = 0;
while i < len(samples) {
if clipruns_absolute(at(samples, i)) >= ceiling {
if run == 0 {
runs += 1;
}
run += 1;
total += 1;
if run > longest {
longest = run;
}
} else {
run = 0;
}
i += 1;
}
[total, longest, runs]
}
// Count overloaded samples and the longest continuous run.
// Returns [samples at or above the absolute ceiling, longest run, run count]. Equality counts as a clipped sample.
pub fn clipruns_count(samples: vector, ceiling: f64) -> vector {
if !clipruns_finite(samples) { return []; }
if !(ceiling > 0.0 && ceiling - ceiling == 0.0) { return []; }
let result = clipruns_compute(samples, ceiling);
if !clipruns_finite(result) { return []; }
result
}
fn warbler_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn warbler_compute(samples: vector, ceiling: f64, allowed: f64) -> vector {
let signal = framesignal_level(samples);
let clips = clipruns_count(samples, ceiling);
if len(signal) == 0 || len(clips) == 0 {
return [];
}
let mut alert = 0;
if at(clips, 1) > allowed {
alert = 1;
}
[at(signal, 0), at(signal, 1), at(clips, 1), alert]
}
// Flag sustained clipping while reporting the energy of an audio frame.
// Returns [peak, mean square, longest clipped run, alert]. Alert means the longest run exceeded the allowed number of samples.
pub fn warbler_meter(samples: vector, ceiling: f64, allowed: f64) -> vector {
if !warbler_finite(samples) { return []; }
if !(ceiling > 0.0 && ceiling - ceiling == 0.0) { return []; }
if !(allowed >= 0.0 && allowed <= 9007199254740991.0 && allowed % 1.0 == 0.0) { return []; }
let result = warbler_compute(samples, ceiling, allowed);
if !warbler_finite(result) { return []; }
result
}
fn main() {
let samples = [1, -1, 0, 0];
let ceiling = 1.0;
let allowed = 1.0;
let result = warbler_meter(samples, ceiling, allowed);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
1
0.5
2
1
Practice
Change samples = [1, 0, -1, 0]. Predict the result, then run the program.
Hint
Returns [peak, mean square, longest clipped run, alert]. Alert means the longest run exceeded the allowed number of samples.
Solution
The result vector is [1, 0.5, 1, 0]. Compare its fields with the return layout in the API section.
Find
let samples = [1, -1, 0, 0];
Replace with
let samples = [1, 0, -1, 0];
Output after the change
1
0.5
1
0
Workflow recipes
Linnet · Bridge short pauses in a speech-activity trace
Summarize speech-activity intervals from a precomputed frame-level envelope.
Bridge short pauses in a speech-activity trace
A brief pause inside an utterance can split a segment. Accept a caller-selected gap and preserve the original time axis. With ten milliseconds per frame, a one-frame gap stays inside a segment. A two-frame gap starts another segment.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [first active millisecond, exclusive active end, segment count, retained active-or-bridged milliseconds]. A silent trace returns [-1,-1,0,0]. Invalid input returns an empty vector.
Argument
Accepted input
levels
Vector of: nonnegative finite number
threshold
nonnegative finite number
gap
nonnegative exact integer
frame_ms
positive finite number
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Linnet 0.1.1 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-linnet/tree/v0.1.1
fn activityspan_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn activityspan_magnitudes(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn activityspan_compute(levels: vector, threshold: f64) -> vector {
let mut first = -1;
let mut end = -1;
let mut count = 0;
let mut i = 0;
while i < len(levels) {
if at(levels, i) > threshold {
if first < 0 {
first = i;
}
end = i + 1;
count += 1;
}
i += 1;
}
[first, end, count]
}
// Locate active frames in a sequence of nonnegative signal levels.
// Returns [first active index, exclusive final active index, active frames]. Silence returns [-1,-1,0]. Activity is strictly above threshold.
pub fn activityspan_bounds(levels: vector, threshold: f64) -> vector {
if !activityspan_magnitudes(levels) { return []; }
if !(threshold >= 0.0 && threshold - threshold == 0.0) { return []; }
let result = activityspan_compute(levels, threshold);
if !activityspan_finite(result) { return []; }
result
}
fn gaphold_num(value: i64) -> f64 {
at([value], 0)
}
fn gaphold_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn gaphold_magnitudes(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn gaphold_compute(levels: vector, threshold: f64, gap: f64) -> vector {
let mut last = -1;
let mut segments = 0;
let mut bridged = 0;
let mut i = 0;
while i < len(levels) {
if at(levels, i) > threshold {
let silent = i - last - 1;
if last < 0 || gaphold_num(silent) > gap {
segments += 1;
} else {
bridged += silent;
}
last = i;
}
i += 1;
}
[segments, bridged]
}
// Count activity segments while bridging short internal silences.
// Returns [segments, bridged silent frames]. Leading and trailing silence are excluded. A gap exactly equal to the allowance is bridged.
pub fn gaphold_segments(levels: vector, threshold: f64, gap: f64) -> vector {
if !gaphold_magnitudes(levels) { return []; }
if !(threshold >= 0.0 && threshold - threshold == 0.0) { return []; }
if !(gap >= 0.0 && gap <= 9007199254740991.0 && gap % 1.0 == 0.0) { return []; }
let result = gaphold_compute(levels, threshold, gap);
if !gaphold_finite(result) { return []; }
result
}
fn linnet_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn linnet_magnitudes(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn linnet_compute(levels: vector, threshold: f64, gap: f64, frame_ms: f64) -> vector {
let span = activityspan_bounds(levels, threshold);
let segments = gaphold_segments(levels, threshold, gap);
if len(span) == 0 || len(segments) == 0 {
return [];
}
if at(span, 0) < 0.0 {
return [-1, -1, 0, 0];
}
[at(span, 0) * frame_ms, at(span, 1) * frame_ms, at(segments, 0), (at(span, 2) + at(segments, 1)) * frame_ms]
}
// Summarize speech-activity intervals from a precomputed frame-level envelope.
// Returns [first active millisecond, exclusive active end, segment count, retained active-or-bridged milliseconds]. A silent trace returns [-1,-1,0,0].
pub fn linnet_segment(levels: vector, threshold: f64, gap: f64, frame_ms: f64) -> vector {
if !linnet_magnitudes(levels) { return []; }
if !(threshold >= 0.0 && threshold - threshold == 0.0) { return []; }
if !(gap >= 0.0 && gap <= 9007199254740991.0 && gap % 1.0 == 0.0) { return []; }
if !(frame_ms > 0.0 && frame_ms - frame_ms == 0.0) { return []; }
let result = linnet_compute(levels, threshold, gap, frame_ms);
if !linnet_finite(result) { return []; }
result
}
fn main() {
let levels = [0, 3, 0, 3, 0, 0, 3];
let threshold = 1.0;
let gap = 1.0;
let frame_ms = 10.0;
let result = linnet_segment(levels, threshold, gap, frame_ms);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
10
70
2
40
Practice
Change levels = [0, 0], gap = 2.0. Predict the result, then run the program.
Hint
Returns [first active millisecond, exclusive active end, segment count, retained active-or-bridged milliseconds]. A silent trace returns [-1,-1,0,0].
Solution
The result vector is [-1, -1, 0, 0]. Compare its fields with the return layout in the API section.
Find
let levels = [0, 3, 0, 3, 0, 0, 3];
Replace with
let levels = [0, 0];
Find
let gap = 1.0;
Replace with
let gap = 2.0;
Output after the change
-1
-1
0
0
Workflow recipes
Curlew · Cover a survey that crosses a grid origin
Plan grid tiles covering every observation in a projected point survey.
Cover a survey that crosses a grid origin
Truncating a negative coordinate toward zero puts a survey point in the wrong tile. Include both extrema and use mathematical floor. A point at east -1 lies in column -1 with two-unit cells. Both end tiles count toward the coverage area.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [first column, first row, last column, last row, tile count]. Both bounds are inclusive; coordinates must already use the same projected CRS. Invalid input returns an empty vector.
Argument
Accepted input
east
Vector of: finite number
north
Vector of: finite number
cell
positive finite number
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Curlew 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-curlew/tree/v0.1.0
fn geobounds_min2(a: f64, b: f64) -> f64 {
if a < b {
return a;
}
b
}
fn geobounds_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn geobounds_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn geobounds_compute(east: vector, north: vector) -> vector {
if len(east) == 0 || len(east) != len(north) {
return [];
}
let mut west = at(east, 0);
let mut right = west;
let mut south = at(north, 0);
let mut top = south;
let mut i = 1;
while i < len(east) {
west = geobounds_min2(west, at(east, i));
right = geobounds_max2(right, at(east, i));
south = geobounds_min2(south, at(north, i));
top = geobounds_max2(top, at(north, i));
i += 1;
}
[west, south, right, top]
}
// Find a projected planar extent from paired point coordinates.
// Returns [west, south, east, north]. A single point has a zero-area extent. Supply a common planar CRS for both axes.
pub fn geobounds_extent(east: vector, north: vector) -> vector {
if !geobounds_finite(east) { return []; }
if !geobounds_finite(north) { return []; }
let result = geobounds_compute(east, north);
if !geobounds_finite(result) { return []; }
result
}
fn gridcover_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn gridcover_absolute(value: f64) -> f64 {
if value < 0.0 {
return - value;
}
value
}
fn gridcover_floorreal(value: f64) -> f64 {
let trunc = value - value % 1.0;
if trunc > value {
return trunc - 1.0;
}
trunc
}
fn gridcover_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn gridcover_compute(box: vector, cell: f64) -> vector {
if len(box) != 4 || at(box, 0) > at(box, 2) || at(box, 1) > at(box, 3) {
return [];
}
let a = at(box, 0) / cell;
let b = at(box, 1) / cell;
let c = at(box, 2) / cell;
let d = at(box, 3) / cell;
if gridcover_max2(gridcover_max2(gridcover_absolute(a), gridcover_absolute(b)), gridcover_max2(gridcover_absolute(c), gridcover_absolute(d))) > 9007199254740991.0 {
return [];
}
[gridcover_floorreal(a), gridcover_floorreal(b), gridcover_floorreal(c), gridcover_floorreal(d)]
}
// Find grid indices containing both extrema of a closed planar extent.
// Returns [min column, min row, max column, max row]. Grid origin is (0,0); exact upper-boundary points belong to the next cell.
pub fn gridcover_cells(box: vector, cell: f64) -> vector {
if !gridcover_finite(box) { return []; }
if !(cell > 0.0 && cell - cell == 0.0) { return []; }
let result = gridcover_compute(box, cell);
if !gridcover_finite(result) { return []; }
result
}
fn curlew_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn curlew_compute(east: vector, north: vector, cell: f64) -> vector {
let box = geobounds_extent(east, north);
let cells = gridcover_cells(box, cell);
if len(cells) == 0 {
return [];
}
let count = (at(cells, 2) - at(cells, 0) + 1.0) * (at(cells, 3) - at(cells, 1) + 1.0);
if count > 9007199254740991.0 {
return [];
}
[at(cells, 0), at(cells, 1), at(cells, 2), at(cells, 3), count]
}
// Plan grid tiles covering every observation in a projected point survey.
// Returns [first column, first row, last column, last row, tile count]. Both bounds are inclusive; coordinates must already use the same projected CRS.
pub fn curlew_tile(east: vector, north: vector, cell: f64) -> vector {
if !curlew_finite(east) { return []; }
if !curlew_finite(north) { return []; }
if !(cell > 0.0 && cell - cell == 0.0) { return []; }
let result = curlew_compute(east, north, cell);
if !curlew_finite(result) { return []; }
result
}
fn main() {
let east = [-1, 4];
let north = [1, 3];
let cell = 2.0;
let result = curlew_tile(east, north, cell);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
-1
0
2
1
8
Practice
Change east = [0], north = [0], cell = 1.0. Predict the result, then run the program.
Hint
Returns [first column, first row, last column, last row, tile count]. Both bounds are inclusive; coordinates must already use the same projected CRS.
Solution
The result vector is [0, 0, 0, 0, 1]. Compare its fields with the return layout in the API section.
Find
let east = [-1, 4];
Replace with
let east = [0];
Find
let north = [1, 3];
Replace with
let north = [0];
Find
let cell = 2.0;
Replace with
let cell = 1.0;
Output after the change
0
0
0
0
1
Workflow recipes
Egret · Compare abundance and diversity in a field survey
Summarize richness, singletons and dominance in an ecological field survey.
Compare abundance and diversity in a field survey
Two surveys can have the same species count and very different abundance patterns. Report diversity alongside observed richness. Two equally abundant taxa give Simpson dominance 0.5 and an effective count of two.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [individuals, observed taxa, singletons, dominance, effective taxa]. An entirely empty survey has no diversity estimate. Invalid input returns an empty vector.
Argument
Accepted input
counts
Vector of: nonnegative exact integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Egret 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-egret/tree/v0.1.0
fn richness_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn richness_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn richness_compute(counts: vector) -> vector {
let mut taxa = 0;
let mut singles = 0;
let mut i = 0;
while i < len(counts) {
let x = at(counts, i);
if x > 0.0 {
taxa += 1;
}
if x == 1.0 {
singles += 1;
}
i += 1;
}
let total = sum(counts);
if total > 9007199254740991.0 {
return [];
}
[taxa, singles, total]
}
// Count observed taxa and singletons from an abundance vector.
// Returns [observed taxa, singletons, individuals]. Zero-count categories do not increase richness.
pub fn richness_observe(counts: vector) -> vector {
if !richness_counts(counts) { return []; }
let result = richness_compute(counts);
if !richness_finite(result) { return []; }
result
}
fn dominance_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn dominance_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn dominance_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn dominance_compute(counts: vector) -> vector {
let total = sum(counts);
if total == 0.0 || total > 9007199254740991.0 {
return [];
}
let mut concentration = 0.0;
let mut i = 0;
while i < len(counts) {
let share = at(counts, i) / total;
concentration += share * share;
i += 1;
}
[concentration, dominance_max2(0.0, 1.0 - concentration)]
}
// Compute Simpson dominance and its complement from abundance counts.
// Returns [sum of squared relative abundances, Gini–Simpson diversity]. Uses sampling with replacement. Empty surveys have no proportions.
pub fn dominance_simpson(counts: vector) -> vector {
if !dominance_counts(counts) { return []; }
let result = dominance_compute(counts);
if !dominance_finite(result) { return []; }
result
}
fn egret_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn egret_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn egret_compute(counts: vector) -> vector {
let detail = richness_observe(counts);
let conc = dominance_simpson(counts);
if len(detail) == 0 || len(conc) == 0 {
return [];
}
[at(detail, 2), at(detail, 0), at(detail, 1), at(conc, 0), 1.0 / at(conc, 0)]
}
// Summarize richness, singletons and dominance in an ecological field survey.
// Returns [individuals, observed taxa, singletons, dominance, effective taxa]. An entirely empty survey has no diversity estimate.
pub fn egret_survey(counts: vector) -> vector {
if !egret_counts(counts) { return []; }
let result = egret_compute(counts);
if !egret_finite(result) { return []; }
result
}
fn main() {
let counts = [2, 0, 2];
let result = egret_survey(counts);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
4
2
0
0.5
2
Practice
Change counts = [1]. Predict the result, then run the program.
Hint
Returns [individuals, observed taxa, singletons, dominance, effective taxa]. An entirely empty survey has no diversity estimate.
Solution
The result vector is [1, 1, 1, 1, 1]. Compare its fields with the return layout in the API section.
Find
let counts = [2, 0, 2];
Replace with
let counts = [1];
Output after the change
1
1
1
1
1
Workflow recipes
Tanager · Audit a directed graph export
Audit a directed edge list before interpreting a vertex's degree.
Audit a directed graph export
Duplicated edge rows and loops change degree in a multigraph. Surface those counts before downstream graph analysis. A duplicate edge inflates degree and a self-loop contributes to both directions. The simple-graph flag records either condition.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [incoming, outgoing, graph-wide duplicate edges, graph-wide loops, simple graph flag]. Duplicate detection uses quadratic time for short edge lists. Invalid input returns an empty vector.
Argument
Accepted input
starts
Vector of: exact signed integer
ends
Vector of: exact signed integer
node
exact signed integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Tanager 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-tanager/tree/v0.1.0
fn graphdegree_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn graphdegree_integers(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= -9007199254740991.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn graphdegree_compute(starts: vector, ends: vector, node: f64) -> vector {
if len(starts) != len(ends) {
return [];
}
let mut incoming = 0;
let mut outgoing = 0;
let mut loops = 0;
let mut i = 0;
while i < len(starts) {
if at(starts, i) == node {
outgoing += 1;
}
if at(ends, i) == node {
incoming += 1;
}
if at(starts, i) == node && at(ends, i) == node {
loops += 1;
}
i += 1;
}
[incoming, outgoing, loops]
}
// Count incoming and outgoing edges at a named numeric vertex.
// Returns [incoming, outgoing, incident self-loops] for a directed multigraph. Each loop adds one to each direction.
pub fn graphdegree_at_node(starts: vector, ends: vector, node: f64) -> vector {
if !graphdegree_integers(starts) { return []; }
if !graphdegree_integers(ends) { return []; }
if !(node >= -9007199254740991.0 && node <= 9007199254740991.0 && node % 1.0 == 0.0) { return []; }
let result = graphdegree_compute(starts, ends, node);
if !graphdegree_finite(result) { return []; }
result
}
fn edgeaudit_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn edgeaudit_integers(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= -9007199254740991.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn edgeaudit_compute(starts: vector, ends: vector) -> vector {
if len(starts) != len(ends) {
return [];
}
let mut dup = 0;
let mut loops = 0;
let mut i = 0;
while i < len(starts) {
if at(starts, i) == at(ends, i) {
loops += 1;
}
let mut j = 0;
while j < i {
if at(starts, i) == at(starts, j) && at(ends, i) == at(ends, j) {
dup += 1;
break;
}
j += 1;
}
i += 1;
}
[dup, loops, len(starts) - dup]
}
// Audit exact repeated directed edges and self-loops.
// Returns [duplicate occurrences beyond the first, self-loop occurrences, unique directed edges]. Reversed edges are distinct.
pub fn edgeaudit_duplicates(starts: vector, ends: vector) -> vector {
if !edgeaudit_integers(starts) { return []; }
if !edgeaudit_integers(ends) { return []; }
let result = edgeaudit_compute(starts, ends);
if !edgeaudit_finite(result) { return []; }
result
}
fn tanager_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn tanager_integers(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= -9007199254740991.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn tanager_compute(starts: vector, ends: vector, node: f64) -> vector {
let degree = graphdegree_at_node(starts, ends, node);
let audit = edgeaudit_duplicates(starts, ends);
if len(degree) == 0 || len(audit) == 0 {
return [];
}
let mut simple = 0;
if at(audit, 0) == 0.0 && at(audit, 1) == 0.0 {
simple = 1;
}
[at(degree, 0), at(degree, 1), at(audit, 0), at(audit, 1), simple]
}
// Audit a directed edge list before interpreting a vertex's degree.
// Returns [incoming, outgoing, graph-wide duplicate edges, graph-wide loops, simple graph flag]. Duplicate detection uses quadratic time for short edge lists.
pub fn tanager_inspect(starts: vector, ends: vector, node: f64) -> vector {
if !tanager_integers(starts) { return []; }
if !tanager_integers(ends) { return []; }
if !(node >= -9007199254740991.0 && node <= 9007199254740991.0 && node % 1.0 == 0.0) { return []; }
let result = tanager_compute(starts, ends, node);
if !tanager_finite(result) { return []; }
result
}
fn main() {
let starts = [1, 1, 2];
let ends = [2, 2, 2];
let node = 2.0;
let result = tanager_inspect(starts, ends, node);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
3
1
1
1
0
Practice
Change starts = [1, 2], ends = [2, 1], node = 1.0. Predict the result, then run the program.
Hint
Returns [incoming, outgoing, graph-wide duplicate edges, graph-wide loops, simple graph flag]. Duplicate detection uses quadratic time for short edge lists.
Solution
The result vector is [1, 1, 0, 0, 1]. Compare its fields with the return layout in the API section.
Find
let starts = [1, 1, 2];
Replace with
let starts = [1, 2];
Find
let ends = [2, 2, 2];
Replace with
let ends = [2, 1];
Find
let node = 2.0;
Replace with
let node = 1.0;
Output after the change
1
1
0
0
1
Workflow recipes
Merganser · Measure a loss that recovered before the final observation
Report drawdown depth and time below the running peak for a historical series.
Measure a loss that recovered before the final observation
A recovered account can finish near its starting value while hiding a long underwater spell. Keep depth and duration visible together. The sample falls from 100 to 75 and recovers. Its depth meets the limit but its time below peak exceeds the duration limit.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Merganser 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-merganser/tree/v0.1.0
fn drawdepth_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn drawdepth_positive(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value > 0.0 && value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn drawdepth_compute(equity: vector) -> vector {
if len(equity) == 0 {
return [];
}
let mut high = at(equity, 0);
let mut peak = 0;
let mut best = 0.0;
let mut start = 0;
let mut bottom = 0;
let mut i = 1;
while i < len(equity) {
let x = at(equity, i);
if x >= high {
high = x;
peak = i;
} else {
let depth = 1.0 - x / high;
if depth > best {
best = depth;
start = peak;
bottom = i;
}
}
i += 1;
}
[best, start, bottom]
}
// Measure the deepest historical peak-to-trough equity decline.
// Returns [maximum fractional drawdown, peak index, trough index]. Uses the first trough at the maximum and the most recent equal peak.
pub fn drawdepth_deepest(equity: vector) -> vector {
if !drawdepth_positive(equity) { return []; }
let result = drawdepth_compute(equity);
if !drawdepth_finite(result) { return []; }
result
}
fn underwater_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn underwater_positive(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value > 0.0 && value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn underwater_compute(equity: vector) -> vector {
if len(equity) == 0 {
return [];
}
let mut high = at(equity, 0);
let mut run = 0;
let mut longest = 0;
let mut recover = 0;
let mut i = 1;
while i < len(equity) {
let x = at(equity, i);
if x >= high {
run = 0;
high = x;
recover = i;
} else {
run += 1;
if run > longest {
longest = run;
}
}
i += 1;
}
[longest, run, recover]
}
// Measure how long an equity series stayed below its running peak.
// Returns [longest consecutive underwater observations, current run, last recovered index]. A return exactly to the prior peak ends a run.
pub fn underwater_duration(equity: vector) -> vector {
if !underwater_positive(equity) { return []; }
let result = underwater_compute(equity);
if !underwater_finite(result) { return []; }
result
}
fn merganser_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn merganser_positive(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value > 0.0 && value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn merganser_compute(equity: vector, depth_limit: f64, duration_limit: f64) -> vector {
let depth = drawdepth_deepest(equity);
let time = underwater_duration(equity);
if len(depth) == 0 || len(time) == 0 {
return [];
}
let mut flag = 0;
if at(depth, 0) > depth_limit || at(time, 0) > duration_limit {
flag = 1;
}
[at(depth, 0), at(depth, 1), at(depth, 2), at(time, 0), flag]
}
// Report drawdown depth and time below the running peak for a historical series.
// Returns [deepest fractional loss, peak index, trough index, longest underwater spell, limit breached]. Durations count observations, not calendar days.
pub fn merganser_report(equity: vector, depth_limit: f64, duration_limit: f64) -> vector {
if !merganser_positive(equity) { return []; }
if !(depth_limit >= 0.0 && depth_limit <= 1.0) { return []; }
if !(duration_limit >= 0.0 && duration_limit <= 9007199254740991.0 && duration_limit % 1.0 == 0.0) { return []; }
let result = merganser_compute(equity, depth_limit, duration_limit);
if !merganser_finite(result) { return []; }
result
}
fn main() {
let equity = [100, 80, 75, 100];
let depth_limit = 0.25;
let duration_limit = 1.0;
let result = merganser_report(equity, depth_limit, duration_limit);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
0.25
0
2
2
1
Practice
Change equity = [4, 2, 4], depth_limit = 0.5. Predict the result, then run the program.
The result vector is [0.5, 0, 1, 1, 0]. Compare its fields with the return layout in the API section.
Find
let equity = [100, 80, 75, 100];
Replace with
let equity = [4, 2, 4];
Find
let depth_limit = 0.25;
Replace with
let depth_limit = 0.5;
Output after the change
0.5
0
1
1
0
Workflow recipes
Pintail · Measure turnover between two weight snapshots
Compare long-only portfolio snapshots under a one-way turnover budget.
Measure turnover between two weight snapshots
Netting buys against sells can hide turnover in an allocation comparison. Keep gross directional changes and the one-way budget explicit. Moving a quarter of the portfolio between two assets requires 0.25 one-way turnover. A 0.125 cap leaves 0.125 excess.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [largest drift index, absolute asset drift, one-way turnover, excess over the budget]. Inputs are aligned historical or hypothetical weights, including cash if applicable. Invalid input returns an empty vector.
Argument
Accepted input
current
Vector of: probability in [0,1]
target
Vector of: probability in [0,1]
turnover_cap
probability in [0,1]
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Pintail 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-pintail/tree/v0.1.0
fn weightdrift_absolute(value: f64) -> f64 {
if value < 0.0 {
return - value;
}
value
}
fn weightdrift_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn weightdrift_probabilities(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 1.0) {
return false;
}
i += 1;
}
true
}
fn weightdrift_compute(current: vector, target: vector) -> vector {
if len(current) == 0 || len(current) != len(target) {
return [];
}
let mut winner = 0;
let mut delta = at(current, 0) - at(target, 0);
let mut i = 1;
while i < len(current) {
let d = at(current, i) - at(target, i);
if weightdrift_absolute(d) > weightdrift_absolute(delta) {
winner = i;
delta = d;
}
i += 1;
}
[winner, delta, weightdrift_absolute(delta)]
}
// Find the largest per-asset deviation between two weight vectors.
// Returns [index, signed current minus target weight, absolute deviation]. First index wins an absolute tie.
pub fn weightdrift_largest(current: vector, target: vector) -> vector {
if !weightdrift_probabilities(current) { return []; }
if !weightdrift_probabilities(target) { return []; }
let result = weightdrift_compute(current, target);
if !weightdrift_finite(result) { return []; }
result
}
fn turnover_absolute(value: f64) -> f64 {
if value < 0.0 {
return - value;
}
value
}
fn turnover_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn turnover_probabilities(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 1.0) {
return false;
}
i += 1;
}
true
}
fn turnover_compute(current: vector, target: vector) -> vector {
if len(current) != len(target) || turnover_absolute(sum(current) - 1.0) > 0.000000001 || turnover_absolute(sum(target) - 1.0) > 0.000000001 {
return [];
}
let mut buys = 0.0;
let mut sells = 0.0;
let mut i = 0;
while i < len(current) {
let d = at(target, i) - at(current, i);
if d > 0.0 {
buys += d;
} else {
sells -= d;
}
i += 1;
}
[(buys + sells) / 2.0, buys, sells]
}
// Calculate one-way turnover for two fully allocated long-only weight vectors.
// Returns [one-way turnover, total weight increases, total weight decreases]. Each portfolio must sum to one within 1e-9.
pub fn turnover_one_way(current: vector, target: vector) -> vector {
if !turnover_probabilities(current) { return []; }
if !turnover_probabilities(target) { return []; }
let result = turnover_compute(current, target);
if !turnover_finite(result) { return []; }
result
}
fn pintail_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn pintail_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn pintail_probabilities(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 1.0) {
return false;
}
i += 1;
}
true
}
fn pintail_compute(current: vector, target: vector, turnover_cap: f64) -> vector {
let drift = weightdrift_largest(current, target);
let trades = turnover_one_way(current, target);
if len(drift) == 0 || len(trades) == 0 {
return [];
}
[at(drift, 0), at(drift, 2), at(trades, 0), pintail_max2(0.0, at(trades, 0) - turnover_cap)]
}
// Compare long-only portfolio snapshots under a one-way turnover budget.
// Returns [largest drift index, absolute asset drift, one-way turnover, excess over the budget]. Inputs are aligned historical or hypothetical weights, including cash if applicable.
pub fn pintail_compare(current: vector, target: vector, turnover_cap: f64) -> vector {
if !pintail_probabilities(current) { return []; }
if !pintail_probabilities(target) { return []; }
if !(turnover_cap >= 0.0 && turnover_cap <= 1.0) { return []; }
let result = pintail_compute(current, target, turnover_cap);
if !pintail_finite(result) { return []; }
result
}
fn main() {
let current = [0.75, 0.25];
let target = [0.5, 0.5];
let turnover_cap = 0.125;
let result = pintail_compare(current, target, turnover_cap);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
0
0.25
0.25
0.125
Practice
Change current = [1], target = [1], turnover_cap = 0.0. Predict the result, then run the program.
Hint
Returns [largest drift index, absolute asset drift, one-way turnover, excess over the budget]. Inputs are aligned historical or hypothetical weights, including cash if applicable.
Solution
The result vector is [0, 0, 0, 0]. Compare its fields with the return layout in the API section.
Find
let current = [0.75, 0.25];
Replace with
let current = [1];
Find
let target = [0.5, 0.5];
Replace with
let target = [1];
Find
let turnover_cap = 0.125;
Replace with
let turnover_cap = 0.0;
Output after the change
0
0
0
0
Workflow recipes
Siskin · Find a funding gap inside an otherwise positive cash schedule
Inspect a cash-flow schedule for shortfalls that disappear by the closing date.
Find a funding gap inside an otherwise positive cash schedule
A positive closing balance can conceal a mid-period reserve breach. Replay the signed flows in order. The closing balance is 25, but two period ends fall below the reserve and the worst gap is 15.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [closing balance, low-water balance, first deficient period, deficient periods, period-end funding gap]. Flows must be in date order. Invalid input returns an empty vector.
Argument
Accepted input
opening
exact signed integer
flows
Vector of: exact signed integer
reserve
exact signed integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Siskin 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-siskin/tree/v0.1.0
fn cashladder_absolute(value: f64) -> f64 {
if value < 0.0 {
return - value;
}
value
}
fn cashladder_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn cashladder_integers(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= -9007199254740991.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn cashladder_compute(opening: f64, flows: vector) -> vector {
let mut cash = opening;
let mut low = cash;
let mut idx = -1;
let mut i = 0;
while i < len(flows) {
cash += at(flows, i);
if cashladder_absolute(cash) > 9007199254740991.0 {
return [];
}
if cash < low {
low = cash;
idx = i;
}
i += 1;
}
[cash, low, idx]
}
// Find closing and lowest balances along an ordered cash-flow schedule.
// Returns [closing, lowest balance including opening, first low index]. Opening uses index -1. Use a single currency's minor units.
pub fn cashladder_balance(opening: f64, flows: vector) -> vector {
if !(opening >= -9007199254740991.0 && opening <= 9007199254740991.0 && opening % 1.0 == 0.0) { return []; }
if !cashladder_integers(flows) { return []; }
let result = cashladder_compute(opening, flows);
if !cashladder_finite(result) { return []; }
result
}
fn floorbreach_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn floorbreach_absolute(value: f64) -> f64 {
if value < 0.0 {
return - value;
}
value
}
fn floorbreach_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn floorbreach_integers(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= -9007199254740991.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn floorbreach_compute(opening: f64, flows: vector, reserve: f64) -> vector {
let mut cash = opening;
let mut first = -1;
let mut count = 0;
let mut gap = 0.0;
let mut i = 0;
while i < len(flows) {
cash += at(flows, i);
if floorbreach_absolute(cash) > 9007199254740991.0 {
return [];
}
if cash < reserve {
if first < 0 {
first = i;
}
count += 1;
gap = floorbreach_max2(gap, reserve - cash);
}
i += 1;
}
[first, count, gap]
}
// Locate the first reserve breach and count all deficient period ends.
// Returns [first deficient period, deficient periods, largest shortfall]. The opening balance initializes the trace; only period ends are counted.
pub fn floorbreach_trace(opening: f64, flows: vector, reserve: f64) -> vector {
if !(opening >= -9007199254740991.0 && opening <= 9007199254740991.0 && opening % 1.0 == 0.0) { return []; }
if !floorbreach_integers(flows) { return []; }
if !(reserve >= -9007199254740991.0 && reserve <= 9007199254740991.0 && reserve % 1.0 == 0.0) { return []; }
let result = floorbreach_compute(opening, flows, reserve);
if !floorbreach_finite(result) { return []; }
result
}
fn siskin_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn siskin_integers(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= -9007199254740991.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn siskin_compute(opening: f64, flows: vector, reserve: f64) -> vector {
let ladder = cashladder_balance(opening, flows);
let risk = floorbreach_trace(opening, flows, reserve);
if len(ladder) == 0 || len(risk) == 0 {
return [];
}
[at(ladder, 0), at(ladder, 1), at(risk, 0), at(risk, 1), at(risk, 2)]
}
// Inspect a cash-flow schedule for shortfalls that disappear by the closing date.
// Returns [closing balance, low-water balance, first deficient period, deficient periods, period-end funding gap]. Flows must be in date order.
pub fn siskin_project(opening: f64, flows: vector, reserve: f64) -> vector {
if !(opening >= -9007199254740991.0 && opening <= 9007199254740991.0 && opening % 1.0 == 0.0) { return []; }
if !siskin_integers(flows) { return []; }
if !(reserve >= -9007199254740991.0 && reserve <= 9007199254740991.0 && reserve % 1.0 == 0.0) { return []; }
let result = siskin_compute(opening, flows, reserve);
if !siskin_finite(result) { return []; }
result
}
fn main() {
let opening = 20.0;
let flows = [-15, -10, 30];
let reserve = 10.0;
let result = siskin_project(opening, flows, reserve);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
25
-5
0
2
15
Practice
Change opening = 0.0, flows = [10]. Predict the result, then run the program.
Hint
Returns [closing balance, low-water balance, first deficient period, deficient periods, period-end funding gap]. Flows must be in date order.
Solution
The result vector is [10, 0, -1, 0, 0]. Compare its fields with the return layout in the API section.
Find
let opening = 20.0;
Replace with
let opening = 0.0;
Find
let flows = [-15, -10, 30];
Replace with
let flows = [10];
Output after the change
10
0
-1
0
0
Workflow recipes
Sandpiper · Schedule redelivery after a lease expires
Schedule a deterministic redelivery after both lease expiry and retry backoff.
Schedule redelivery after a lease expires
Redelivery before a worker's lease expires can duplicate work. Make retry time depend on both the lease and the attempt count. The eight-tick lease ends at tick 18. A four-tick backoff makes tick 22 the earliest eligible retry.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [ready, ticks to eligibility, retry delay]. Delay begins when the lease expires. The queue host owns acknowledgement and delivery. Invalid input returns an empty vector.
Argument
Accepted input
issued
nonnegative exact integer
ttl
positive exact integer
now
nonnegative exact integer
base
positive exact integer
ceiling
positive exact integer
attempt
nonnegative exact integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Sandpiper 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-sandpiper/tree/v0.1.0
fn leaseclock_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn leaseclock_compute(issued: f64, ttl: f64, now: f64) -> vector {
if now < issued {
return [];
}
let age = now - issued;
if age < ttl {
return [1, ttl - age, 0];
}
[0, 0, age - ttl]
}
// Classify a message lease against a single monotonic clock.
// Returns [active, remaining ticks, overdue ticks]. A lease expires exactly at its TTL; clocks earlier than issuance are invalid.
pub fn leaseclock_remaining(issued: f64, ttl: f64, now: f64) -> vector {
if !(issued >= 0.0 && issued <= 9007199254740991.0 && issued % 1.0 == 0.0) { return []; }
if !(ttl >= 1.0 && ttl <= 9007199254740991.0 && ttl % 1.0 == 0.0) { return []; }
if !(now >= 0.0 && now <= 9007199254740991.0 && now % 1.0 == 0.0) { return []; }
let result = leaseclock_compute(issued, ttl, now);
if !leaseclock_finite(result) { return []; }
result
}
fn retrydelay_min2(a: f64, b: f64) -> f64 {
if a < b {
return a;
}
b
}
fn retrydelay_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn retrydelay_compute(base: f64, ceiling: f64, attempt: f64) -> vector {
if ceiling < base {
return [];
}
let mut delay = base;
let mut i = 0.0;
while i < attempt && delay < ceiling {
delay = retrydelay_min2(ceiling, delay * 2.0);
i += 1.0;
}
if delay == ceiling {
return [delay, 1];
}
[delay, 0]
}
// Compute saturating exponential retry delays without unbounded exponentiation.
// Returns [delay ticks, cap reached]. Attempt zero uses the base. Ceilings below base are invalid.
pub fn retrydelay_capped(base: f64, ceiling: f64, attempt: f64) -> vector {
if !(base >= 1.0 && base <= 9007199254740991.0 && base % 1.0 == 0.0) { return []; }
if !(ceiling >= 1.0 && ceiling <= 9007199254740991.0 && ceiling % 1.0 == 0.0) { return []; }
if !(attempt >= 0.0 && attempt <= 9007199254740991.0 && attempt % 1.0 == 0.0) { return []; }
let result = retrydelay_compute(base, ceiling, attempt);
if !retrydelay_finite(result) { return []; }
result
}
fn sandpiper_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn sandpiper_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn sandpiper_compute(issued: f64, ttl: f64, now: f64, base: f64, ceiling: f64, attempt: f64) -> vector {
let clock = leaseclock_remaining(issued, ttl, now);
let delay = retrydelay_capped(base, ceiling, attempt);
if len(clock) == 0 || len(delay) == 0 {
return [];
}
let wait = sandpiper_max2(0.0, at(clock, 1) + at(delay, 0) - at(clock, 2));
if wait == 0.0 {
return [1, 0, at(delay, 0)];
}
[0, wait, at(delay, 0)]
}
// Schedule a deterministic redelivery after both lease expiry and retry backoff.
// Returns [ready, ticks to eligibility, retry delay]. Delay begins when the lease expires. The queue host owns acknowledgement and delivery.
pub fn sandpiper_redeliver(issued: f64, ttl: f64, now: f64, base: f64, ceiling: f64, attempt: f64) -> vector {
if !(issued >= 0.0 && issued <= 9007199254740991.0 && issued % 1.0 == 0.0) { return []; }
if !(ttl >= 1.0 && ttl <= 9007199254740991.0 && ttl % 1.0 == 0.0) { return []; }
if !(now >= 0.0 && now <= 9007199254740991.0 && now % 1.0 == 0.0) { return []; }
if !(base >= 1.0 && base <= 9007199254740991.0 && base % 1.0 == 0.0) { return []; }
if !(ceiling >= 1.0 && ceiling <= 9007199254740991.0 && ceiling % 1.0 == 0.0) { return []; }
if !(attempt >= 0.0 && attempt <= 9007199254740991.0 && attempt % 1.0 == 0.0) { return []; }
let result = sandpiper_compute(issued, ttl, now, base, ceiling, attempt);
if !sandpiper_finite(result) { return []; }
result
}
fn main() {
let issued = 10.0;
let ttl = 8.0;
let now = 19.0;
let base = 2.0;
let ceiling = 16.0;
let attempt = 1.0;
let result = sandpiper_redeliver(issued, ttl, now, base, ceiling, attempt);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
0
3
4
Practice
Change now = 22.0. Predict the result, then run the program.
Hint
Returns [ready, ticks to eligibility, retry delay]. Delay begins when the lease expires. The queue host owns acknowledgement and delivery.
Solution
The result vector is [1, 0, 4]. Compare its fields with the return layout in the API section.
Find
let now = 19.0;
Replace with
let now = 22.0;
Output after the change
1
0
4
Workflow recipes
Petrel · Decide whether a queued request can afford to wait
Admit an immediate charge or report the wait a request can afford.
Decide whether a queued request can afford to wait
Charging a delayed request immediately can remove capacity from unrelated work. Return the wait separately from the updated balance. The bucket has four tokens and needs eight. At two tokens per tick the charge fits the two-tick deadline.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [charge now, balance after immediate decision, feasible by deadline, wait]. Deferred work consumes no tokens until resubmitted. Invalid input returns an empty vector.
Argument
Accepted input
tokens
nonnegative finite number
capacity
positive finite number
rate
positive finite number
elapsed
nonnegative finite number
cost
positive finite number
deadline
nonnegative finite number
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Petrel 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-petrel/tree/v0.1.0
fn tokenbucket_min2(a: f64, b: f64) -> f64 {
if a < b {
return a;
}
b
}
fn tokenbucket_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn tokenbucket_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn tokenbucket_compute(tokens: f64, capacity: f64, rate: f64, elapsed: f64) -> vector {
if tokens > capacity {
return [];
}
let grown = tokens + rate * elapsed;
[tokenbucket_min2(capacity, grown), tokenbucket_max2(0.0, grown - capacity)]
}
// Refill a rate bucket up to its burst capacity.
// Returns [available tokens, refill discarded at capacity]. Tokens, capacity and rate use the same work unit.
pub fn tokenbucket_refill(tokens: f64, capacity: f64, rate: f64, elapsed: f64) -> vector {
if !(tokens >= 0.0 && tokens - tokens == 0.0) { return []; }
if !(capacity > 0.0 && capacity - capacity == 0.0) { return []; }
if !(rate > 0.0 && rate - rate == 0.0) { return []; }
if !(elapsed >= 0.0 && elapsed - elapsed == 0.0) { return []; }
let result = tokenbucket_compute(tokens, capacity, rate, elapsed);
if !tokenbucket_finite(result) { return []; }
result
}
fn waitbudget_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn waitbudget_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn waitbudget_compute(tokens: f64, capacity: f64, rate: f64, cost: f64, deadline: f64) -> vector {
if tokens > capacity {
return [];
}
if cost > capacity {
return [0, -1];
}
let wait = waitbudget_max2(0.0, (cost - tokens) / rate);
if wait <= deadline {
return [1, wait];
}
[0, wait]
}
// Compute the wait required for a token charge within a relative deadline.
// Returns [admissible by deadline, required wait]. A charge above capacity has no feasible wait and returns [0,-1].
pub fn waitbudget_admit(tokens: f64, capacity: f64, rate: f64, cost: f64, deadline: f64) -> vector {
if !(tokens >= 0.0 && tokens - tokens == 0.0) { return []; }
if !(capacity > 0.0 && capacity - capacity == 0.0) { return []; }
if !(rate > 0.0 && rate - rate == 0.0) { return []; }
if !(cost > 0.0 && cost - cost == 0.0) { return []; }
if !(deadline >= 0.0 && deadline - deadline == 0.0) { return []; }
let result = waitbudget_compute(tokens, capacity, rate, cost, deadline);
if !waitbudget_finite(result) { return []; }
result
}
fn petrel_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn petrel_compute(tokens: f64, capacity: f64, rate: f64, elapsed: f64, cost: f64, deadline: f64) -> vector {
let bucket = tokenbucket_refill(tokens, capacity, rate, elapsed);
if len(bucket) == 0 {
return [];
}
let available = at(bucket, 0);
let plan = waitbudget_admit(available, capacity, rate, cost, deadline);
if len(plan) == 0 {
return [];
}
if at(plan, 1) == 0.0 {
return [1, available - cost, 1, 0];
}
[0, available, at(plan, 0), at(plan, 1)]
}
// Admit an immediate charge or report the wait a request can afford.
// Returns [charge now, balance after immediate decision, feasible by deadline, wait]. Deferred work consumes no tokens until resubmitted.
pub fn petrel_admit(tokens: f64, capacity: f64, rate: f64, elapsed: f64, cost: f64, deadline: f64) -> vector {
if !(tokens >= 0.0 && tokens - tokens == 0.0) { return []; }
if !(capacity > 0.0 && capacity - capacity == 0.0) { return []; }
if !(rate > 0.0 && rate - rate == 0.0) { return []; }
if !(elapsed >= 0.0 && elapsed - elapsed == 0.0) { return []; }
if !(cost > 0.0 && cost - cost == 0.0) { return []; }
if !(deadline >= 0.0 && deadline - deadline == 0.0) { return []; }
let result = petrel_compute(tokens, capacity, rate, elapsed, cost, deadline);
if !petrel_finite(result) { return []; }
result
}
fn main() {
let tokens = 2.0;
let capacity = 10.0;
let rate = 2.0;
let elapsed = 1.0;
let cost = 8.0;
let deadline = 2.0;
let result = petrel_admit(tokens, capacity, rate, elapsed, cost, deadline);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
0
4
1
2
Practice
Change elapsed = 4.0, deadline = 0.0. Predict the result, then run the program.
Hint
Returns [charge now, balance after immediate decision, feasible by deadline, wait]. Deferred work consumes no tokens until resubmitted.
Solution
The result vector is [1, 2, 1, 0]. Compare its fields with the return layout in the API section.
Find
let elapsed = 1.0;
Replace with
let elapsed = 4.0;
Find
let deadline = 2.0;
Replace with
let deadline = 0.0;
Output after the change
1
2
1
0
Workflow recipes
Fulmar · Commit offsets without skipping unfinished deliveries
Choose a contiguous commit offset from an out-of-order delivery trace.
Commit offsets without skipping unfinished deliveries
Committing the largest acknowledged offset can skip a message that is still in flight. Advance only through a contiguous prefix. Acknowledging offsets 4 and 6 advances the cursor only to 5. Offset 6 can remain acknowledged until 5 completes.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [next commit, observed gaps, stale deliveries, per-trace high water]. Acknowledgements at or beyond start must refer to delivered offsets in this trace. Invalid input returns an empty vector.
Argument
Accepted input
delivered
Vector of: nonnegative exact integer
acked
Vector of: nonnegative exact integer
start
nonnegative exact integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Fulmar 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-fulmar/tree/v0.1.0
fn offsetgap_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn offsetgap_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn offsetgap_compute(offsets: vector, start: f64) -> vector {
let mut next = start;
let mut gaps = 0.0;
let mut stale = 0;
let mut i = 0;
while i < len(offsets) {
let x = at(offsets, i);
if x < next {
stale += 1;
} else {
gaps += x - next;
if x == 9007199254740991.0 {
return [];
}
next = x + 1.0;
}
i += 1;
}
[gaps, stale, next]
}
// Audit an ordered offset trace against an expected starting value.
// Returns [forward gaps counted at first observation, stale or replayed deliveries, next high-water offset]. Late arrivals do not erase earlier gaps.
pub fn offsetgap_scan(offsets: vector, start: f64) -> vector {
if !offsetgap_counts(offsets) { return []; }
if !(start >= 0.0 && start <= 9007199254740991.0 && start % 1.0 == 0.0) { return []; }
let result = offsetgap_compute(offsets, start);
if !offsetgap_finite(result) { return []; }
result
}
fn ackprefix_hasid(values: vector, key: f64) -> bool {
let mut i = 0;
while i < len(values) {
if at(values, i) == key {
return true;
}
i += 1;
}
false
}
fn ackprefix_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn ackprefix_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn ackprefix_compute(acked: vector, start: f64) -> vector {
let mut next = start;
while ackprefix_hasid(acked, next) {
if next == 9007199254740991.0 {
return [];
}
next += 1.0;
}
[next, next - start]
}
// Find the longest contiguous acknowledgement prefix in unordered deliveries.
// Returns [next unacknowledged offset, advanced count]. Duplicate acknowledgements never advance the cursor twice.
pub fn ackprefix_advance(acked: vector, start: f64) -> vector {
if !ackprefix_counts(acked) { return []; }
if !(start >= 0.0 && start <= 9007199254740991.0 && start % 1.0 == 0.0) { return []; }
let result = ackprefix_compute(acked, start);
if !ackprefix_finite(result) { return []; }
result
}
fn fulmar_hasid(values: vector, key: f64) -> bool {
let mut i = 0;
while i < len(values) {
if at(values, i) == key {
return true;
}
i += 1;
}
false
}
fn fulmar_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn fulmar_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn fulmar_compute(delivered: vector, acked: vector, start: f64) -> vector {
let seen = offsetgap_scan(delivered, start);
if len(seen) == 0 {
return [];
}
let mut i = 0;
while i < len(acked) {
let key = at(acked, i);
if key >= start && !fulmar_hasid(delivered, key) {
return [];
}
i += 1;
}
let prefix = ackprefix_advance(acked, start);
if len(prefix) == 0 {
return [];
}
[at(prefix, 0), at(seen, 0), at(seen, 1), at(seen, 2)]
}
// Choose a contiguous commit offset from an out-of-order delivery trace.
// Returns [next commit, observed gaps, stale deliveries, per-trace high water]. Acknowledgements at or beyond start must refer to delivered offsets in this trace.
pub fn fulmar_checkpoint(delivered: vector, acked: vector, start: f64) -> vector {
if !fulmar_counts(delivered) { return []; }
if !fulmar_counts(acked) { return []; }
if !(start >= 0.0 && start <= 9007199254740991.0 && start % 1.0 == 0.0) { return []; }
let result = fulmar_compute(delivered, acked, start);
if !fulmar_finite(result) { return []; }
result
}
fn main() {
let delivered = [4, 6, 5, 6];
let acked = [4, 6];
let start = 4.0;
let result = fulmar_checkpoint(delivered, acked, start);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
5
1
2
7
Practice
Change delivered = [2, 3], acked = [3, 2], start = 2.0. Predict the result, then run the program.
Hint
Returns [next commit, observed gaps, stale deliveries, per-trace high water]. Acknowledgements at or beyond start must refer to delivered offsets in this trace.
Solution
The result vector is [4, 0, 0, 4]. Compare its fields with the return layout in the API section.
Find
let delivered = [4, 6, 5, 6];
Replace with
let delivered = [2, 3];
Find
let acked = [4, 6];
Replace with
let acked = [3, 2];
Find
let start = 4.0;
Replace with
let start = 2.0;
Output after the change
4
0
0
4
Workflow recipes
Waxwing · Budget an expanded GraphQL field plan
Check the depth and weighted resolver cost of an expanded GraphQL field plan.
Budget an expanded GraphQL field plan
A flat query can cost more than a deep one when list fields fan out. Evaluate expanded cost and depth independently. The plan is only two levels deep, but its visit-weighted work is 17 against a budget of 15.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [admitted, maximum depth, total work, costliest field index]. Supply resolved aliases, fragments and list visit estimates from your parser. Invalid input returns an empty vector.
Argument
Accepted input
depths
Vector of: nonnegative exact integer
units
Vector of: nonnegative exact integer
visits
Vector of: nonnegative exact integer
max_depth
positive exact integer
budget
nonnegative exact integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Waxwing 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-waxwing/tree/v0.1.0
fn querydepth_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn querydepth_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn querydepth_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn querydepth_compute(depths: vector) -> vector {
let mut prev = 0.0;
let mut high = 0.0;
let mut roots = 0;
let mut i = 0;
while i < len(depths) {
let d = at(depths, i);
if d < 1.0 || d > prev + 1.0 {
return [];
}
if d == 1.0 {
roots += 1;
}
high = querydepth_max2(high, d);
prev = d;
i += 1;
}
[high, roots, len(depths)]
}
// Validate a preorder field-depth trace from an expanded query plan.
// Returns [maximum depth, root fields, total fields]. Depth starts at one. A child can descend only one level; siblings and ascent are allowed.
pub fn querydepth_shape(depths: vector) -> vector {
if !querydepth_counts(depths) { return []; }
let result = querydepth_compute(depths);
if !querydepth_finite(result) { return []; }
result
}
fn fieldcost_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn fieldcost_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn fieldcost_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn fieldcost_compute(units: vector, visits: vector) -> vector {
if len(units) != len(visits) {
return [];
}
let mut total = 0.0;
let mut largest = -1.0;
let mut idx = -1;
let mut i = 0;
while i < len(units) {
let cost = at(units, i) * at(visits, i);
if cost > 9007199254740991.0 - total {
return [];
}
total += cost;
if cost > largest {
largest = cost;
idx = i;
}
i += 1;
}
[total, idx, fieldcost_max2(0.0, largest)]
}
// Estimate expanded resolver work using per-field costs and visit counts.
// Returns [total work, costliest field index, largest single field contribution]. Empty input uses index -1. Inputs come from the host query planner.
pub fn fieldcost_weighted(units: vector, visits: vector) -> vector {
if !fieldcost_counts(units) { return []; }
if !fieldcost_counts(visits) { return []; }
let result = fieldcost_compute(units, visits);
if !fieldcost_finite(result) { return []; }
result
}
fn waxwing_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn waxwing_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn waxwing_compute(depths: vector, units: vector, visits: vector, max_depth: f64, budget: f64) -> vector {
if len(depths) != len(units) || len(depths) == 0 {
return [];
}
let shape = querydepth_shape(depths);
let cost = fieldcost_weighted(units, visits);
if len(shape) == 0 || len(cost) == 0 {
return [];
}
let mut allow = 0;
if at(shape, 0) <= max_depth && at(cost, 0) <= budget {
allow = 1;
}
[allow, at(shape, 0), at(cost, 0), at(cost, 1)]
}
// Check the depth and weighted resolver cost of an expanded GraphQL field plan.
// Returns [admitted, maximum depth, total work, costliest field index]. Supply resolved aliases, fragments and list visit estimates from your parser.
pub fn waxwing_budget(depths: vector, units: vector, visits: vector, max_depth: f64, budget: f64) -> vector {
if !waxwing_counts(depths) { return []; }
if !waxwing_counts(units) { return []; }
if !waxwing_counts(visits) { return []; }
if !(max_depth >= 1.0 && max_depth <= 9007199254740991.0 && max_depth % 1.0 == 0.0) { return []; }
if !(budget >= 0.0 && budget <= 9007199254740991.0 && budget % 1.0 == 0.0) { return []; }
let result = waxwing_compute(depths, units, visits, max_depth, budget);
if !waxwing_finite(result) { return []; }
result
}
fn main() {
let depths = [1, 2, 2];
let units = [1, 3, 2];
let visits = [1, 4, 2];
let max_depth = 3.0;
let budget = 15.0;
let result = waxwing_budget(depths, units, visits, max_depth, budget);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
0
2
17
1
Practice
Change depths = [1, 2], units = [2, 3], visits = [1, 2], max_depth = 2.0, budget = 8.0. Predict the result, then run the program.
Hint
Returns [admitted, maximum depth, total work, costliest field index]. Supply resolved aliases, fragments and list visit estimates from your parser.
Solution
The result vector is [1, 2, 8, 1]. Compare its fields with the return layout in the API section.
Find
let depths = [1, 2, 2];
Replace with
let depths = [1, 2];
Find
let units = [1, 3, 2];
Replace with
let units = [2, 3];
Find
let visits = [1, 4, 2];
Replace with
let visits = [1, 2];
Find
let max_depth = 3.0;
Replace with
let max_depth = 2.0;
Find
let budget = 15.0;
Replace with
let budget = 8.0;
Output after the change
1
2
8
1
Workflow recipes
Martin · Fit a retry into an RPC deadline
Decide whether another RPC attempt fits the remaining end-to-end deadline.
Fit a retry into an RPC deadline
Resetting a timeout at each hop lets a retry outlive its caller. Subtract already-spent time and the coming backoff. Fifty ticks have elapsed and ten are reserved for backoff. An idempotent retry has forty ticks available.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [retry now or after wait, attempt budget after wait, attempts left]. The minimum is the shortest useful child duration. Invalid input returns an empty vector.
Argument
Accepted input
budget
nonnegative finite number
stages
Vector of: nonnegative finite number
wait
nonnegative finite number
minimum
positive finite number
status
nonnegative exact integer
idempotent
nonnegative exact integer
attempts
nonnegative exact integer
limit
positive exact integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Martin 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-martin/tree/v0.1.0
fn deadlinepath_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn deadlinepath_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn deadlinepath_magnitudes(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn deadlinepath_compute(budget: f64, stages: vector, reserve: f64) -> vector {
let elapsed = sum(stages);
let left = budget - elapsed - reserve;
[deadlinepath_max2(0.0, left), deadlinepath_max2(0.0, -left), elapsed]
}
// Propagate a parent time budget across elapsed RPC stages.
// Returns [usable child budget, overrun after reserve, elapsed total]. Durations use one clock unit.
pub fn deadlinepath_remaining(budget: f64, stages: vector, reserve: f64) -> vector {
if !(budget >= 0.0 && budget - budget == 0.0) { return []; }
if !deadlinepath_magnitudes(stages) { return []; }
if !(reserve >= 0.0 && reserve - reserve == 0.0) { return []; }
let result = deadlinepath_compute(budget, stages, reserve);
if !deadlinepath_finite(result) { return []; }
result
}
fn statusretry_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn statusretry_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn statusretry_compute(status: f64, idempotent: f64, attempts: f64, max_attempts: f64) -> vector {
if idempotent > 1.0 || status > 16.0 {
return [];
}
let left = statusretry_max2(0.0, max_attempts - attempts);
if idempotent == 1.0 && left > 0.0 && (status == 14.0 || status == 4.0) {
return [1, left];
}
[0, left]
}
// Check a conservative retry policy for selected gRPC status codes.
// Returns [retry eligible, attempts remaining]. Retries require an idempotent operation, a remaining attempt, and status 14 (UNAVAILABLE) or 4 (DEADLINE_EXCEEDED). Status is in 0–16.
pub fn statusretry_classify(status: f64, idempotent: f64, attempts: f64, max_attempts: f64) -> vector {
if !(status >= 0.0 && status <= 9007199254740991.0 && status % 1.0 == 0.0) { return []; }
if !(idempotent >= 0.0 && idempotent <= 9007199254740991.0 && idempotent % 1.0 == 0.0) { return []; }
if !(attempts >= 0.0 && attempts <= 9007199254740991.0 && attempts % 1.0 == 0.0) { return []; }
if !(max_attempts >= 1.0 && max_attempts <= 9007199254740991.0 && max_attempts % 1.0 == 0.0) { return []; }
let result = statusretry_compute(status, idempotent, attempts, max_attempts);
if !statusretry_finite(result) { return []; }
result
}
fn martin_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn martin_magnitudes(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn martin_compute(budget: f64, stages: vector, wait: f64, minimum: f64, status: f64, idempotent: f64, attempts: f64, limit: f64) -> vector {
let time = deadlinepath_remaining(budget, stages, wait);
let policy = statusretry_classify(status, idempotent, attempts, limit);
if len(time) == 0 || len(policy) == 0 {
return [];
}
let mut retry = 0;
if at(policy, 0) == 1.0 && at(time, 0) >= minimum {
retry = 1;
}
[retry, at(time, 0), at(policy, 1)]
}
// Decide whether another RPC attempt fits the remaining end-to-end deadline.
// Returns [retry now or after wait, attempt budget after wait, attempts left]. The minimum is the shortest useful child duration.
pub fn martin_retry(budget: f64, stages: vector, wait: f64, minimum: f64, status: f64, idempotent: f64, attempts: f64, limit: f64) -> vector {
if !(budget >= 0.0 && budget - budget == 0.0) { return []; }
if !martin_magnitudes(stages) { return []; }
if !(wait >= 0.0 && wait - wait == 0.0) { return []; }
if !(minimum > 0.0 && minimum - minimum == 0.0) { return []; }
if !(status >= 0.0 && status <= 9007199254740991.0 && status % 1.0 == 0.0) { return []; }
if !(idempotent >= 0.0 && idempotent <= 9007199254740991.0 && idempotent % 1.0 == 0.0) { return []; }
if !(attempts >= 0.0 && attempts <= 9007199254740991.0 && attempts % 1.0 == 0.0) { return []; }
if !(limit >= 1.0 && limit <= 9007199254740991.0 && limit % 1.0 == 0.0) { return []; }
let result = martin_compute(budget, stages, wait, minimum, status, idempotent, attempts, limit);
if !martin_finite(result) { return []; }
result
}
fn main() {
let budget = 100.0;
let stages = [20, 30];
let wait = 10.0;
let minimum = 35.0;
let status = 14.0;
let idempotent = 1.0;
let attempts = 1.0;
let limit = 3.0;
let result = martin_retry(budget, stages, wait, minimum, status, idempotent, attempts, limit);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
1
40
2
Practice
Change budget = 60.0, stages = [50], wait = 8.0, minimum = 5.0. Predict the result, then run the program.
Hint
Returns [retry now or after wait, attempt budget after wait, attempts left]. The minimum is the shortest useful child duration.
Solution
The result vector is [0, 2, 2]. Compare its fields with the return layout in the API section.
Find
let budget = 100.0;
Replace with
let budget = 60.0;
Find
let stages = [20, 30];
Replace with
let stages = [50];
Find
let wait = 10.0;
Replace with
let wait = 8.0;
Find
let minimum = 35.0;
Replace with
let minimum = 5.0;
Output after the change
0
2
2
Workflow recipes
Kinglet · Serve a byte range at end of file
Plan a full or single-range HTTP response against a known representation size.
Serve a byte range at end of file
An inclusive last byte becomes a read length with a plus one. Handle suffixes, empty resources and unsatisfied offsets explicitly. A request for bytes 90 through 200 of a 100-byte resource returns ten bytes beginning at 90.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [status, body offset, body length, full length]. Mode 0 sends the full body, 1 uses first/last, 2 uses first as a suffix count. Header parsing and multipart ranges belong to the host. Invalid input returns an empty vector.
Argument
Accepted input
size
nonnegative exact integer
mode
nonnegative exact integer
first
nonnegative exact integer
last
exact signed integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Kinglet 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-kinglet/tree/v0.1.0
fn byterange_min2(a: f64, b: f64) -> f64 {
if a < b {
return a;
}
b
}
fn byterange_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn byterange_compute(size: f64, first: f64, last: f64) -> vector {
if last < -1.0 || (last != -1.0 && last < first) {
return [];
}
if first >= size {
return [0, 0, 0];
}
let mut end = size - 1.0;
if last >= 0.0 {
end = byterange_min2(end, last);
}
[1, first, end - first + 1.0]
}
// Resolve a single inclusive HTTP byte range to an offset and length.
// Returns [satisfiable, offset, length]. Set last to -1 for an open-ended range. A syntactically reversed range is invalid.
pub fn byterange_resolve(size: f64, first: f64, last: f64) -> vector {
if !(size >= 0.0 && size <= 9007199254740991.0 && size % 1.0 == 0.0) { return []; }
if !(first >= 0.0 && first <= 9007199254740991.0 && first % 1.0 == 0.0) { return []; }
if !(last >= -9007199254740991.0 && last <= 9007199254740991.0 && last % 1.0 == 0.0) { return []; }
let result = byterange_compute(size, first, last);
if !byterange_finite(result) { return []; }
result
}
fn suffixrange_min2(a: f64, b: f64) -> f64 {
if a < b {
return a;
}
b
}
fn suffixrange_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn suffixrange_compute(size: f64, suffix: f64) -> vector {
if suffix == 0.0 || size == 0.0 {
return [0, 0, 0];
}
let count = suffixrange_min2(size, suffix);
[1, size - count, count]
}
// Resolve an HTTP suffix-byte specification without negative offsets.
// Returns [satisfiable, offset, length]. A suffix longer than the entity selects the full entity. Zero bytes or an empty entity produce an unsatisfied range.
pub fn suffixrange_resolve(size: f64, suffix: f64) -> vector {
if !(size >= 0.0 && size <= 9007199254740991.0 && size % 1.0 == 0.0) { return []; }
if !(suffix >= 0.0 && suffix <= 9007199254740991.0 && suffix % 1.0 == 0.0) { return []; }
let result = suffixrange_compute(size, suffix);
if !suffixrange_finite(result) { return []; }
result
}
fn kinglet_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn kinglet_compute(size: f64, mode: f64, first: f64, last: f64) -> vector {
if mode == 0.0 {
return [200, 0, size, size];
}
let mut range = byterange_resolve(size, first, last);
if mode == 2.0 {
range = suffixrange_resolve(size, first);
}
if mode > 2.0 || len(range) == 0 {
return [];
}
if at(range, 0) == 0.0 {
return [416, 0, 0, size];
}
[206, at(range, 1), at(range, 2), size]
}
// Plan a full or single-range HTTP response against a known representation size.
// Returns [status, body offset, body length, full length]. Mode 0 sends the full body, 1 uses first/last, 2 uses first as a suffix count. Header parsing and multipart ranges belong to the host.
pub fn kinglet_respond(size: f64, mode: f64, first: f64, last: f64) -> vector {
if !(size >= 0.0 && size <= 9007199254740991.0 && size % 1.0 == 0.0) { return []; }
if !(mode >= 0.0 && mode <= 9007199254740991.0 && mode % 1.0 == 0.0) { return []; }
if !(first >= 0.0 && first <= 9007199254740991.0 && first % 1.0 == 0.0) { return []; }
if !(last >= -9007199254740991.0 && last <= 9007199254740991.0 && last % 1.0 == 0.0) { return []; }
let result = kinglet_compute(size, mode, first, last);
if !kinglet_finite(result) { return []; }
result
}
fn main() {
let size = 100.0;
let mode = 1.0;
let first = 90.0;
let last = 200.0;
let result = kinglet_respond(size, mode, first, last);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
206
90
10
100
Practice
Change mode = 2.0, first = 12.0, last = -1.0. Predict the result, then run the program.
Hint
Returns [status, body offset, body length, full length]. Mode 0 sends the full body, 1 uses first/last, 2 uses first as a suffix count. Header parsing and multipart ranges belong to the host.
Solution
The result vector is [206, 88, 12, 100]. Compare its fields with the return layout in the API section.
Find
let mode = 1.0;
Replace with
let mode = 2.0;
Find
let first = 90.0;
Replace with
let first = 12.0;
Find
let last = 200.0;
Replace with
let last = -1.0;
Output after the change
206
88
12
100
Workflow recipes
Barnowl · Find clock reversals and gaps in an audit export
Inspect a supplied audit export for sequence gaps, replays and clock reversals.
Find clock reversals and gaps in an audit export
Sorting an export by timestamp can conceal a clock rollback. Audit receipt order and sequence continuity as separate signals. The sample skips sequence 41, repeats 42 and ends with a backward clock step. The result identifies the reversed row.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [gap count, nonadvancing IDs, backward clock steps, first reversed row, clean flag]. Preserve original receipt order; a gap is an observation for investigation. Invalid input returns an empty vector.
Argument
Accepted input
ids
Vector of: nonnegative exact integer
times
Vector of: exact signed integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Barnowl 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-barnowl/tree/v0.1.0
fn eventorder_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn eventorder_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn eventorder_integers(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= -9007199254740991.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn eventorder_compute(times: vector) -> vector {
let mut backward = 0;
let mut biggest = 0.0;
let mut first = -1;
let mut i = 1;
while i < len(times) {
let step = at(times, i - 1) - at(times, i);
if step > 0.0 {
if first < 0 {
first = i;
}
backward += 1;
biggest = eventorder_max2(biggest, step);
}
i += 1;
}
[backward, biggest, first]
}
// Locate time-order anomalies in a log stream in receipt order.
// Returns [adjacent clock reversals, largest backward step, first reversal index]. Equal timestamps preserve order.
pub fn eventorder_scan(times: vector) -> vector {
if !eventorder_integers(times) { return []; }
let result = eventorder_compute(times);
if !eventorder_finite(result) { return []; }
result
}
fn auditgaps_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn auditgaps_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn auditgaps_compute(ids: vector) -> vector {
if len(ids) == 0 {
return [0, 0, -1];
}
let mut high = at(ids, 0);
let mut holes = 0.0;
let mut replay = 0;
let mut i = 1;
while i < len(ids) {
let id = at(ids, i);
if id <= high {
replay += 1;
} else {
holes += id - high - 1.0;
high = id;
}
i += 1;
}
[holes, replay, high]
}
// Count forward gaps and nonadvancing IDs in an audit export.
// Returns [missing at first observation, nonadvancing rows, highest observed ID]. The first row establishes the baseline; the empty sentinel is -1.
pub fn auditgaps_sequence(ids: vector) -> vector {
if !auditgaps_counts(ids) { return []; }
let result = auditgaps_compute(ids);
if !auditgaps_finite(result) { return []; }
result
}
fn barnowl_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn barnowl_integers(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= -9007199254740991.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn barnowl_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn barnowl_compute(ids: vector, times: vector) -> vector {
if len(ids) != len(times) {
return [];
}
let seq = auditgaps_sequence(ids);
let clock = eventorder_scan(times);
if len(seq) == 0 || len(clock) == 0 {
return [];
}
let mut clean = 0;
if at(seq, 0) == 0.0 && at(seq, 1) == 0.0 && at(clock, 0) == 0.0 {
clean = 1;
}
[at(seq, 0), at(seq, 1), at(clock, 0), at(clock, 2), clean]
}
// Inspect a supplied audit export for sequence gaps, replays and clock reversals.
// Returns [gap count, nonadvancing IDs, backward clock steps, first reversed row, clean flag]. Preserve original receipt order; a gap is an observation for investigation.
pub fn barnowl_audit(ids: vector, times: vector) -> vector {
if !barnowl_counts(ids) { return []; }
if !barnowl_integers(times) { return []; }
let result = barnowl_compute(ids, times);
if !barnowl_finite(result) { return []; }
result
}
fn main() {
let ids = [40, 42, 42];
let times = [10, 14, 12];
let result = barnowl_audit(ids, times);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
1
1
1
2
0
Practice
Change ids = [1, 2], times = [4, 4]. Predict the result, then run the program.
Hint
Returns [gap count, nonadvancing IDs, backward clock steps, first reversed row, clean flag]. Preserve original receipt order; a gap is an observation for investigation.
Solution
The result vector is [0, 0, 0, -1, 1]. Compare its fields with the return layout in the API section.
Find
let ids = [40, 42, 42];
Replace with
let ids = [1, 2];
Find
let times = [10, 14, 12];
Replace with
let times = [4, 4];
Output after the change
0
0
0
-1
1
Workflow recipes
Harrier · Apply freshness policy to a verified session
Apply time and assurance policy to a session after upstream identity verification.
Apply freshness policy to a verified session
A still-valid token can represent an old or insufficiently verified session. Apply application policy after the identity provider has verified the token. The verified session is eight ticks old and meets the required assurance level. The expiration boundary remains exclusive.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [policy accepted, claims time accepted, assurance/freshness accepted, session age]. Use only after the host has authenticated and verified the issuer, audience and signature. Invalid input returns an empty vector.
Argument
Accepted input
now
exact signed integer
begins
exact signed integer
expires
exact signed integer
skew
nonnegative exact integer
observed
nonnegative exact integer
required
nonnegative exact integer
auth_time
exact signed integer
max_age
nonnegative exact integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Harrier 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-harrier/tree/v0.1.0
fn claimclock_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn claimclock_compute(now: f64, begins: f64, expires: f64, skew: f64) -> vector {
if expires <= begins {
return [];
}
let early = begins - now;
let late = now - expires;
if early > skew {
return [0, early, 0];
}
if late >= skew {
return [0, 0, late];
}
[1, 0, 0]
}
// Evaluate activation and expiration bounds on previously verified claims.
// Returns [time accepted, early ticks, expired ticks]. Expiration is exclusive and applies symmetric caller-supplied clock tolerance.
pub fn claimclock_check(now: f64, begins: f64, expires: f64, skew: f64) -> vector {
if !(now >= -9007199254740991.0 && now <= 9007199254740991.0 && now % 1.0 == 0.0) { return []; }
if !(begins >= -9007199254740991.0 && begins <= 9007199254740991.0 && begins % 1.0 == 0.0) { return []; }
if !(expires >= -9007199254740991.0 && expires <= 9007199254740991.0 && expires % 1.0 == 0.0) { return []; }
if !(skew >= 0.0 && skew <= 9007199254740991.0 && skew % 1.0 == 0.0) { return []; }
let result = claimclock_compute(now, begins, expires, skew);
if !claimclock_finite(result) { return []; }
result
}
fn assurancelevel_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn assurancelevel_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn assurancelevel_compute(observed: f64, required: f64, auth_time: f64, now: f64, max_age: f64) -> vector {
if auth_time > now {
return [];
}
let age = now - auth_time;
let gap = assurancelevel_max2(0.0, required - observed);
if gap == 0.0 && age <= max_age {
return [1, age, 0];
}
[0, age, gap]
}
// Check session freshness and an application-defined ordered assurance level.
// Returns [meets both, age, missing assurance levels]. A future authentication time is invalid; equality at the age limit is accepted.
pub fn assurancelevel_policy(observed: f64, required: f64, auth_time: f64, now: f64, max_age: f64) -> vector {
if !(observed >= 0.0 && observed <= 9007199254740991.0 && observed % 1.0 == 0.0) { return []; }
if !(required >= 0.0 && required <= 9007199254740991.0 && required % 1.0 == 0.0) { return []; }
if !(auth_time >= -9007199254740991.0 && auth_time <= 9007199254740991.0 && auth_time % 1.0 == 0.0) { return []; }
if !(now >= -9007199254740991.0 && now <= 9007199254740991.0 && now % 1.0 == 0.0) { return []; }
if !(max_age >= 0.0 && max_age <= 9007199254740991.0 && max_age % 1.0 == 0.0) { return []; }
let result = assurancelevel_compute(observed, required, auth_time, now, max_age);
if !assurancelevel_finite(result) { return []; }
result
}
fn harrier_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn harrier_compute(now: f64, begins: f64, expires: f64, skew: f64, observed: f64, required: f64, auth_time: f64, max_age: f64) -> vector {
let claim = claimclock_check(now, begins, expires, skew);
let level = assurancelevel_policy(observed, required, auth_time, now, max_age);
if len(claim) == 0 || len(level) == 0 {
return [];
}
[at(claim, 0) * at(level, 0), at(claim, 0), at(level, 0), at(level, 1)]
}
// Apply time and assurance policy to a session after upstream identity verification.
// Returns [policy accepted, claims time accepted, assurance/freshness accepted, session age]. Use only after the host has authenticated and verified the issuer, audience and signature.
pub fn harrier_session(now: f64, begins: f64, expires: f64, skew: f64, observed: f64, required: f64, auth_time: f64, max_age: f64) -> vector {
if !(now >= -9007199254740991.0 && now <= 9007199254740991.0 && now % 1.0 == 0.0) { return []; }
if !(begins >= -9007199254740991.0 && begins <= 9007199254740991.0 && begins % 1.0 == 0.0) { return []; }
if !(expires >= -9007199254740991.0 && expires <= 9007199254740991.0 && expires % 1.0 == 0.0) { return []; }
if !(skew >= 0.0 && skew <= 9007199254740991.0 && skew % 1.0 == 0.0) { return []; }
if !(observed >= 0.0 && observed <= 9007199254740991.0 && observed % 1.0 == 0.0) { return []; }
if !(required >= 0.0 && required <= 9007199254740991.0 && required % 1.0 == 0.0) { return []; }
if !(auth_time >= -9007199254740991.0 && auth_time <= 9007199254740991.0 && auth_time % 1.0 == 0.0) { return []; }
if !(max_age >= 0.0 && max_age <= 9007199254740991.0 && max_age % 1.0 == 0.0) { return []; }
let result = harrier_compute(now, begins, expires, skew, observed, required, auth_time, max_age);
if !harrier_finite(result) { return []; }
result
}
fn main() {
let now = 100.0;
let begins = 90.0;
let expires = 110.0;
let skew = 0.0;
let observed = 2.0;
let required = 2.0;
let auth_time = 92.0;
let max_age = 10.0;
let result = harrier_session(now, begins, expires, skew, observed, required, auth_time, max_age);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
1
1
1
8
Practice
Change now = 110.0, auth_time = 105.0. Predict the result, then run the program.
Hint
Returns [policy accepted, claims time accepted, assurance/freshness accepted, session age]. Use only after the host has authenticated and verified the issuer, audience and signature.
Solution
The result vector is [0, 0, 1, 5]. Compare its fields with the return layout in the API section.
Find
let now = 100.0;
Replace with
let now = 110.0;
Find
let auth_time = 92.0;
Replace with
let auth_time = 105.0;
Output after the change
0
0
1
5
Workflow recipes
Plover · Gate an alert on short and long error windows
Gate alerts on error-budget burn in both a short and a long window.
Gate an alert on short and long error windows
A brief burst or stale long-window average can trigger a noisy alert on its own. Require both windows to cross the selected burn threshold. The short window burns four times its error budget and the long window burns twice. Both reach the selected threshold.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [alert, short burn, long burn, long-window excess failures]. The short window must be a subset of the long window, including its good events. Invalid input returns an empty vector.
Argument
Accepted input
fast_bad
nonnegative exact integer
fast_total
positive exact integer
slow_bad
nonnegative exact integer
slow_total
positive exact integer
allowed
positive finite number
trigger
positive finite number
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Plover 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-plover/tree/v0.1.0
fn sloburn_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn sloburn_compute(bad: f64, total: f64, allowed: f64) -> vector {
if bad > total || allowed > 1.0 {
return [];
}
let rate = bad / total;
[rate, rate / allowed]
}
// Normalize observed failures by an allowed error fraction.
// Returns [observed error fraction, burn multiple]. The allowed error fraction is greater than zero and at most one.
pub fn sloburn_rate(bad: f64, total: f64, allowed: f64) -> vector {
if !(bad >= 0.0 && bad <= 9007199254740991.0 && bad % 1.0 == 0.0) { return []; }
if !(total >= 1.0 && total <= 9007199254740991.0 && total % 1.0 == 0.0) { return []; }
if !(allowed > 0.0 && allowed - allowed == 0.0) { return []; }
let result = sloburn_compute(bad, total, allowed);
if !sloburn_finite(result) { return []; }
result
}
fn budgetleft_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn budgetleft_floorpos(value: f64) -> f64 {
value - value % 1.0
}
fn budgetleft_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn budgetleft_compute(bad: f64, total: f64, allowance: f64) -> vector {
if bad > total {
return [];
}
let capacity = budgetleft_floorpos(total * allowance);
[capacity, budgetleft_max2(0.0, capacity - bad), budgetleft_max2(0.0, bad - capacity)]
}
// Account for whole allowed failures in an observed window.
// Returns [whole failures permitted, remaining, excess]. Rounds the nonnegative product of sample count and allowance down.
pub fn budgetleft_events(bad: f64, total: f64, allowance: f64) -> vector {
if !(bad >= 0.0 && bad <= 9007199254740991.0 && bad % 1.0 == 0.0) { return []; }
if !(total >= 0.0 && total <= 9007199254740991.0 && total % 1.0 == 0.0) { return []; }
if !(allowance >= 0.0 && allowance <= 1.0) { return []; }
let result = budgetleft_compute(bad, total, allowance);
if !budgetleft_finite(result) { return []; }
result
}
fn plover_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn plover_compute(fast_bad: f64, fast_total: f64, slow_bad: f64, slow_total: f64, allowed: f64, trigger: f64) -> vector {
if fast_total > slow_total || fast_bad > slow_bad || fast_total - fast_bad > slow_total - slow_bad {
return [];
}
let fast = sloburn_rate(fast_bad, fast_total, allowed);
let slow = sloburn_rate(slow_bad, slow_total, allowed);
let balance = budgetleft_events(slow_bad, slow_total, allowed);
if len(fast) == 0 || len(slow) == 0 || len(balance) == 0 {
return [];
}
let mut alert = 0;
if at(fast, 1) >= trigger && at(slow, 1) >= trigger {
alert = 1;
}
[alert, at(fast, 1), at(slow, 1), at(balance, 2)]
}
// Gate alerts on error-budget burn in both a short and a long window.
// Returns [alert, short burn, long burn, long-window excess failures]. The short window must be a subset of the long window, including its good events.
pub fn plover_alert(fast_bad: f64, fast_total: f64, slow_bad: f64, slow_total: f64, allowed: f64, trigger: f64) -> vector {
if !(fast_bad >= 0.0 && fast_bad <= 9007199254740991.0 && fast_bad % 1.0 == 0.0) { return []; }
if !(fast_total >= 1.0 && fast_total <= 9007199254740991.0 && fast_total % 1.0 == 0.0) { return []; }
if !(slow_bad >= 0.0 && slow_bad <= 9007199254740991.0 && slow_bad % 1.0 == 0.0) { return []; }
if !(slow_total >= 1.0 && slow_total <= 9007199254740991.0 && slow_total % 1.0 == 0.0) { return []; }
if !(allowed > 0.0 && allowed - allowed == 0.0) { return []; }
if !(trigger > 0.0 && trigger - trigger == 0.0) { return []; }
let result = plover_compute(fast_bad, fast_total, slow_bad, slow_total, allowed, trigger);
if !plover_finite(result) { return []; }
result
}
fn main() {
let fast_bad = 2.0;
let fast_total = 10.0;
let slow_bad = 10.0;
let slow_total = 100.0;
let allowed = 0.05;
let trigger = 2.0;
let result = plover_alert(fast_bad, fast_total, slow_bad, slow_total, allowed, trigger);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
1
4
2
5
Practice
Change slow_bad = 5.0. Predict the result, then run the program.
Hint
Returns [alert, short burn, long burn, long-window excess failures]. The short window must be a subset of the long window, including its good events.
Solution
The result vector is [0, 4, 1, 0]. Compare its fields with the return layout in the API section.
Find
let slow_bad = 10.0;
Replace with
let slow_bad = 5.0;
Output after the change
0
4
1
0
Workflow recipes
Jacana · Compare a crude rate with a standardized rate
Compare a crude event rate with a directly standardized rate.
Compare a crude rate with a standardized rate
A change in the mix of observed groups can move the pooled rate. Recalculate rates against fixed reference weights before comparing populations. The crude event rate is 0.75. Equal reference weights give each stratum the same influence and reduce the standardized rate to 0.5.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [crude rate, standardized rate, standardized minus crude, total observations]. Each reported stratum needs observations for the crude comparison. Causal interpretation depends on study design. Invalid input returns an empty vector.
Argument
Accepted input
events
Vector of: nonnegative exact integer
trials
Vector of: nonnegative exact integer
weights
Vector of: nonnegative finite number
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Jacana 0.1.1 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-jacana/tree/v0.1.1
fn stratamean_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn stratamean_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn stratamean_compute(events: vector, trials: vector) -> vector {
if len(events) == 0 || len(events) != len(trials) {
return [];
}
let mut i = 0;
while i < len(events) {
if at(trials, i) == 0.0 || at(events, i) > at(trials, i) {
return [];
}
i += 1;
}
let n = sum(trials);
if n > 9007199254740991.0 {
return [];
}
let successes = sum(events);
[successes, n, successes / n]
}
// Pool event counts and expose the crude observed rate.
// Returns [total events, total trials, crude rate]. Every stratum must have observations and events cannot exceed trials.
pub fn stratamean_pooled(events: vector, trials: vector) -> vector {
if !stratamean_counts(events) { return []; }
if !stratamean_counts(trials) { return []; }
let result = stratamean_compute(events, trials);
if !stratamean_finite(result) { return []; }
result
}
fn stdweight_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn stdweight_magnitudes(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn stdweight_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn stdweight_compute(events: vector, trials: vector, weights: vector) -> vector {
if len(events) != len(trials) || len(events) != len(weights) {
return [];
}
let w = sum(weights);
if w <= 0.0 {
return [];
}
let mut result = 0.0;
let mut i = 0;
while i < len(events) {
let n = at(trials, i);
let e = at(events, i);
let part = at(weights, i);
if e > n || (part > 0.0 && n == 0.0) {
return [];
}
if part > 0.0 {
result += (part / w) * (e / n);
}
i += 1;
}
[result, w]
}
// Directly standardize stratum-specific rates to a reference population.
// Returns [standardized rate, total reference weight]. Positive-weight strata require observations. Zero-weight strata may be empty.
pub fn stdweight_direct(events: vector, trials: vector, weights: vector) -> vector {
if !stdweight_counts(events) { return []; }
if !stdweight_counts(trials) { return []; }
if !stdweight_magnitudes(weights) { return []; }
let result = stdweight_compute(events, trials, weights);
if !stdweight_finite(result) { return []; }
result
}
fn jacana_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn jacana_magnitudes(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn jacana_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn jacana_compute(events: vector, trials: vector, weights: vector) -> vector {
let pooled = stratamean_pooled(events, trials);
let std = stdweight_direct(events, trials, weights);
if len(pooled) == 0 || len(std) == 0 {
return [];
}
[at(pooled, 2), at(std, 0), at(std, 0) - at(pooled, 2), at(pooled, 1)]
}
// Compare a crude event rate with a directly standardized rate.
// Returns [crude rate, standardized rate, standardized minus crude, total observations]. Each reported stratum needs observations for the crude comparison. Causal interpretation depends on study design.
pub fn jacana_standardize(events: vector, trials: vector, weights: vector) -> vector {
if !jacana_counts(events) { return []; }
if !jacana_counts(trials) { return []; }
if !jacana_magnitudes(weights) { return []; }
let result = jacana_compute(events, trials, weights);
if !jacana_finite(result) { return []; }
result
}
fn main() {
let events = [0, 6];
let trials = [2, 6];
let weights = [1, 1];
let result = jacana_standardize(events, trials, weights);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
0.75
0.5
-0.25
8
Practice
Change events = [1, 1], trials = [2, 2], weights = [2, 1]. Predict the result, then run the program.
Hint
Returns [crude rate, standardized rate, standardized minus crude, total observations]. Each reported stratum needs observations for the crude comparison. Causal interpretation depends on study design.
Solution
The result vector is [0.5, 0.5, 0, 4]. Compare its fields with the return layout in the API section.
Find
let events = [0, 6];
Replace with
let events = [1, 1];
Find
let trials = [2, 6];
Replace with
let trials = [2, 2];
Find
let weights = [1, 1];
Replace with
let weights = [2, 1];
Output after the change
0.5
0.5
0
4
Workflow recipes
Redstart · Update a binary-event probability after observations
Update a binary-event model and report uncertainty in its probability.
Update a binary-event probability after observations
A point estimate alone hides the difference between two observations and two thousand. Return posterior variance with the updated mean. One success and one failure update a uniform prior to Beta(2,2). The posterior mean is 0.5 and its variance is 0.05.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [posterior mean, posterior variance, posterior alpha, posterior beta]. This conjugate model assumes exchangeable Bernoulli observations. Invalid input returns an empty vector.
Argument
Accepted input
alpha
positive finite number
beta
positive finite number
positive
nonnegative exact integer
negative
nonnegative exact integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Redstart 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-redstart/tree/v0.1.0
fn betaupdate_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn betaupdate_compute(alpha: f64, beta: f64, positive: f64, negative: f64) -> vector {
[alpha + positive, beta + negative]
}
// Update a Beta prior with Bernoulli counts.
// Returns [posterior alpha, posterior beta]. Use one count for each independent binary observation.
pub fn betaupdate_observe(alpha: f64, beta: f64, positive: f64, negative: f64) -> vector {
if !(alpha > 0.0 && alpha - alpha == 0.0) { return []; }
if !(beta > 0.0 && beta - beta == 0.0) { return []; }
if !(positive >= 0.0 && positive <= 9007199254740991.0 && positive % 1.0 == 0.0) { return []; }
if !(negative >= 0.0 && negative <= 9007199254740991.0 && negative % 1.0 == 0.0) { return []; }
let result = betaupdate_compute(alpha, beta, positive, negative);
if !betaupdate_finite(result) { return []; }
result
}
fn betamoment_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn betamoment_compute(alpha: f64, beta: f64) -> vector {
let total = alpha + beta;
let mean = alpha / total;
[mean, mean * (beta / total) / (total + 1.0), total]
}
// Calculate the mean and variance of a Beta distribution.
// Returns [mean, variance, concentration]. Uses mean times its complement divided by concentration plus one.
pub fn betamoment_summary(alpha: f64, beta: f64) -> vector {
if !(alpha > 0.0 && alpha - alpha == 0.0) { return []; }
if !(beta > 0.0 && beta - beta == 0.0) { return []; }
let result = betamoment_compute(alpha, beta);
if !betamoment_finite(result) { return []; }
result
}
fn redstart_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn redstart_compute(alpha: f64, beta: f64, positive: f64, negative: f64) -> vector {
let next = betaupdate_observe(alpha, beta, positive, negative);
if len(next) == 0 {
return [];
}
let stats = betamoment_summary(at(next, 0), at(next, 1));
if len(stats) == 0 {
return [];
}
[at(stats, 0), at(stats, 1), at(next, 0), at(next, 1)]
}
// Update a binary-event model and report uncertainty in its probability.
// Returns [posterior mean, posterior variance, posterior alpha, posterior beta]. This conjugate model assumes exchangeable Bernoulli observations.
pub fn redstart_posterior(alpha: f64, beta: f64, positive: f64, negative: f64) -> vector {
if !(alpha > 0.0 && alpha - alpha == 0.0) { return []; }
if !(beta > 0.0 && beta - beta == 0.0) { return []; }
if !(positive >= 0.0 && positive <= 9007199254740991.0 && positive % 1.0 == 0.0) { return []; }
if !(negative >= 0.0 && negative <= 9007199254740991.0 && negative % 1.0 == 0.0) { return []; }
let result = redstart_compute(alpha, beta, positive, negative);
if !redstart_finite(result) { return []; }
result
}
fn main() {
let alpha = 1.0;
let beta = 1.0;
let positive = 1.0;
let negative = 1.0;
let result = redstart_posterior(alpha, beta, positive, negative);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
0.5
0.05
2
2
Practice
Change positive = 0.0, negative = 0.0. Predict the result, then run the program.
Hint
Returns [posterior mean, posterior variance, posterior alpha, posterior beta]. This conjugate model assumes exchangeable Bernoulli observations.
Solution
The result vector is [0.5, 0.08333333333333333, 1, 1]. Compare its fields with the return layout in the API section.
Find
let positive = 1.0;
Replace with
let positive = 0.0;
Find
let negative = 1.0;
Replace with
let negative = 0.0;
Output after the change
0.5
0.08333333333333333
1
1
Workflow recipes
Quail · Compare a real-qubit circuit with observed shots
Simulate a short real-amplitude single-qubit circuit and compare shot counts.
Compare a real-qubit circuit with observed shots
Shot frequencies can differ from circuit predictions. Keep amplitudes through the gate sequence and compare probabilities only at readout. The X and Z sequence prepares a state whose probability of one is 1. Six ones in eight measured shots give a 0.25 discrepancy.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [predicted P(1), observed P(1), absolute discrepancy]. Gates are applied left to right. Complex phase gates and hardware execution require a different state representation. Invalid input returns an empty vector.
Argument
Accepted input
state
Vector of: finite number
gates
Vector of: nonnegative exact integer
zero
nonnegative exact integer
one
nonnegative exact integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Quail 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-quail/tree/v0.1.0
fn realqubit_absolute(value: f64) -> f64 {
if value < 0.0 {
return - value;
}
value
}
fn realqubit_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn realqubit_compute(state: vector, gate: f64) -> vector {
if len(state) != 2 || realqubit_absolute(dot(state, state) - 1.0) > 0.000000001 || gate > 3.0 {
return [];
}
let a = at(state, 0);
let b = at(state, 1);
if gate == 0.0 {
return [a, b];
}
if gate == 1.0 {
return [b, a];
}
if gate == 2.0 {
return [a, -b];
}
let scale = 0.7071067811865475;
[(a + b) * scale, (a - b) * scale]
}
// Apply I, X, Z or Hadamard to a normalized real-amplitude qubit.
// Input [a,b] must have unit squared norm within 1e-9. Gate IDs 0,1,2,3 denote I,X,Z,H. Returns transformed amplitudes.
pub fn realqubit_gate(state: vector, gate: f64) -> vector {
if !realqubit_finite(state) { return []; }
if !(gate >= 0.0 && gate <= 9007199254740991.0 && gate % 1.0 == 0.0) { return []; }
let result = realqubit_compute(state, gate);
if !realqubit_finite(result) { return []; }
result
}
fn readoutfreq_absolute(value: f64) -> f64 {
if value < 0.0 {
return - value;
}
value
}
fn readoutfreq_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn readoutfreq_compute(state: vector, zero: f64, one: f64) -> vector {
if len(state) != 2 || readoutfreq_absolute(dot(state, state) - 1.0) > 0.000000001 || zero + one <= 0.0 || zero + one > 9007199254740991.0 {
return [];
}
let prob = at(state, 1) * at(state, 1);
let seen = one / (zero + one);
[prob, seen, readoutfreq_absolute(prob - seen)]
}
// Compare computational-basis shot frequencies to a real qubit's probabilities.
// Returns [predicted P(1), observed P(1), absolute difference]. At least one observed shot and a normalized two-amplitude state are required.
pub fn readoutfreq_compare(state: vector, zero: f64, one: f64) -> vector {
if !readoutfreq_finite(state) { return []; }
if !(zero >= 0.0 && zero <= 9007199254740991.0 && zero % 1.0 == 0.0) { return []; }
if !(one >= 0.0 && one <= 9007199254740991.0 && one % 1.0 == 0.0) { return []; }
let result = readoutfreq_compute(state, zero, one);
if !readoutfreq_finite(result) { return []; }
result
}
fn quail_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn quail_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn quail_compute(state: vector, gates: vector, zero: f64, one: f64) -> vector {
let mut wave = realqubit_gate(state, 0.0);
if len(wave) == 0 {
return [];
}
let mut i = 0;
while i < len(gates) {
wave = realqubit_gate(wave, at(gates, i));
if len(wave) == 0 {
return [];
}
i += 1;
}
readoutfreq_compare(wave, zero, one)
}
// Simulate a short real-amplitude single-qubit circuit and compare shot counts.
// Returns [predicted P(1), observed P(1), absolute discrepancy]. Gates are applied left to right. Complex phase gates and hardware execution require a different state representation.
pub fn quail_experiment(state: vector, gates: vector, zero: f64, one: f64) -> vector {
if !quail_finite(state) { return []; }
if !quail_counts(gates) { return []; }
if !(zero >= 0.0 && zero <= 9007199254740991.0 && zero % 1.0 == 0.0) { return []; }
if !(one >= 0.0 && one <= 9007199254740991.0 && one % 1.0 == 0.0) { return []; }
let result = quail_compute(state, gates, zero, one);
if !quail_finite(result) { return []; }
result
}
fn main() {
let state = [1, 0];
let gates = [1, 2];
let zero = 2.0;
let one = 6.0;
let result = quail_experiment(state, gates, zero, one);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
1
0.75
0.25
Practice
Change gates = [], zero = 4.0, one = 0.0. Predict the result, then run the program.
Hint
Returns [predicted P(1), observed P(1), absolute discrepancy]. Gates are applied left to right. Complex phase gates and hardware execution require a different state representation.
Solution
The result vector is [0, 0, 0]. Compare its fields with the return layout in the API section.
Find
let gates = [1, 2];
Replace with
let gates = [];
Find
let zero = 2.0;
Replace with
let zero = 4.0;
Find
let one = 6.0;
Replace with
let one = 0.0;
Output after the change
0
0
0
Workflow recipes
Skimmer · Read parity alongside two-bit marginals
Compare parity and marginal balance in two-bit shot data.
Read parity alongside two-bit marginals
Balanced single-bit frequencies can mask different joint outcomes. Inspect parity alongside both marginals. Four 00 and four 11 shots have equally balanced individual bits, while every shot has even parity.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [parity expectation, left-one frequency, right-one frequency, parity matches target]. A single measurement basis characterizes this histogram only. Invalid input returns an empty vector.
Argument
Accepted input
counts
Vector of: nonnegative exact integer
expected_even
probability in [0,1]
tolerance
probability in [0,1]
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Skimmer 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-skimmer/tree/v0.1.0
fn bitparity_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn bitparity_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn bitparity_compute(counts: vector) -> vector {
if len(counts) != 4 {
return [];
}
let total = sum(counts);
if total <= 0.0 || total > 9007199254740991.0 {
return [];
}
let even = (at(counts, 0) + at(counts, 3)) / total;
let odd = (at(counts, 1) + at(counts, 2)) / total;
[even, odd, even - odd]
}
// Measure even/odd parity from a two-bit measurement histogram.
// Bin order is 00,01,10,11. Returns [even frequency, odd frequency, parity expectation]. At least one shot is required.
pub fn bitparity_measure(counts: vector) -> vector {
if !bitparity_counts(counts) { return []; }
let result = bitparity_compute(counts);
if !bitparity_finite(result) { return []; }
result
}
fn shotmargins_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn shotmargins_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn shotmargins_compute(counts: vector) -> vector {
if len(counts) != 4 {
return [];
}
let total = sum(counts);
if total <= 0.0 || total > 9007199254740991.0 {
return [];
}
[(at(counts, 2) + at(counts, 3)) / total, (at(counts, 1) + at(counts, 3)) / total, total]
}
// Extract both individual bit frequencies from joint two-bit shots.
// Bin order is 00,01,10,11. Returns [P(left=1), P(right=1), shots]. At least one shot is required.
pub fn shotmargins_bits(counts: vector) -> vector {
if !shotmargins_counts(counts) { return []; }
let result = shotmargins_compute(counts);
if !shotmargins_finite(result) { return []; }
result
}
fn skimmer_absolute(value: f64) -> f64 {
if value < 0.0 {
return - value;
}
value
}
fn skimmer_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn skimmer_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn skimmer_compute(counts: vector, expected_even: f64, tolerance: f64) -> vector {
let joint = bitparity_measure(counts);
let margins = shotmargins_bits(counts);
if len(joint) == 0 || len(margins) == 0 {
return [];
}
let mut good = 0;
if skimmer_absolute(at(joint, 0) - expected_even) <= tolerance {
good = 1;
}
[at(joint, 2), at(margins, 0), at(margins, 1), good]
}
// Compare parity and marginal balance in two-bit shot data.
// Returns [parity expectation, left-one frequency, right-one frequency, parity matches target]. A single measurement basis characterizes this histogram only.
pub fn skimmer_characterize(counts: vector, expected_even: f64, tolerance: f64) -> vector {
if !skimmer_counts(counts) { return []; }
if !(expected_even >= 0.0 && expected_even <= 1.0) { return []; }
if !(tolerance >= 0.0 && tolerance <= 1.0) { return []; }
let result = skimmer_compute(counts, expected_even, tolerance);
if !skimmer_finite(result) { return []; }
result
}
fn main() {
let counts = [4, 0, 0, 4];
let expected_even = 1.0;
let tolerance = 0.1;
let result = skimmer_characterize(counts, expected_even, tolerance);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
1
0.5
0.5
1
Practice
Change counts = [2, 2, 2, 2]. Predict the result, then run the program.
Hint
Returns [parity expectation, left-one frequency, right-one frequency, parity matches target]. A single measurement basis characterizes this histogram only.
Solution
The result vector is [0, 0.5, 0.5, 0]. Compare its fields with the return layout in the API section.
Find
let counts = [4, 0, 0, 4];
Replace with
let counts = [2, 2, 2, 2];
Output after the change
0
0.5
0.5
0
Workflow recipes
Magpie · Integrate unevenly spaced observations
Integrate an increasing sample grid and flag under-sampled sections.
Integrate unevenly spaced observations
An arithmetic average ignores the spacing between measurements. Integrate on the supplied time grid and flag large gaps. A constant value of two across four time units gives an area of eight. The largest interval exceeds the allowed two-unit gap.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [area, span-weighted mean, widest gap, exceeds gap limit]. Rejects duplicate or reversed sample times. Invalid input returns an empty vector.
Argument
Accepted input
x
Vector of: finite number
y
Vector of: finite number
max_gap
positive finite number
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Magpie 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-magpie/tree/v0.1.0
fn trapezoid_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn trapezoid_compute(x: vector, y: vector) -> vector {
if len(x) < 2 || len(x) != len(y) {
return [];
}
let mut area = 0.0;
let mut i = 1;
while i < len(x) {
let width = at(x, i) - at(x, i - 1);
let middle = at(y, i) * 0.5 + at(y, i - 1) * 0.5;
area += width * middle;
i += 1;
}
[area, at(x, len(x) - 1) - at(x, 0)]
}
// Integrate sampled values by the composite trapezoidal rule in input order.
// Returns [signed integral, signed span]. A descending grid reverses the integral sign. At least two paired samples are required.
pub fn trapezoid_integrate(x: vector, y: vector) -> vector {
if !trapezoid_finite(x) { return []; }
if !trapezoid_finite(y) { return []; }
let result = trapezoid_compute(x, y);
if !trapezoid_finite(result) { return []; }
result
}
fn gridgap_absolute(value: f64) -> f64 {
if value < 0.0 {
return - value;
}
value
}
fn gridgap_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn gridgap_compute(x: vector) -> vector {
if len(x) < 2 {
return [];
}
let mut widest = -1.0;
let mut idx = -1;
let mut bad = 0;
let mut i = 1;
while i < len(x) {
let step = at(x, i) - at(x, i - 1);
if step <= 0.0 {
bad += 1;
}
if gridgap_absolute(step) > widest {
widest = gridgap_absolute(step);
idx = i;
}
i += 1;
}
[widest, idx, bad]
}
// Locate the coarsest gap and count nonincreasing steps in a sample grid.
// Returns [largest absolute step, right index of the first largest step, nonincreasing steps]. At least two points are required.
pub fn gridgap_inspect(x: vector) -> vector {
if !gridgap_finite(x) { return []; }
let result = gridgap_compute(x);
if !gridgap_finite(result) { return []; }
result
}
fn magpie_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn magpie_compute(x: vector, y: vector, max_gap: f64) -> vector {
let gaps = gridgap_inspect(x);
if len(gaps) == 0 || at(gaps, 2) > 0.0 {
return [];
}
let result = trapezoid_integrate(x, y);
if len(result) == 0 {
return [];
}
let mut sparse = 0;
if at(gaps, 0) > max_gap {
sparse = 1;
}
[at(result, 0), at(result, 0) / at(result, 1), at(gaps, 0), sparse]
}
// Integrate an increasing sample grid and flag under-sampled sections.
// Returns [area, span-weighted mean, widest gap, exceeds gap limit]. Rejects duplicate or reversed sample times.
pub fn magpie_integrate(x: vector, y: vector, max_gap: f64) -> vector {
if !magpie_finite(x) { return []; }
if !magpie_finite(y) { return []; }
if !(max_gap > 0.0 && max_gap - max_gap == 0.0) { return []; }
let result = magpie_compute(x, y, max_gap);
if !magpie_finite(result) { return []; }
result
}
fn main() {
let x = [0, 1, 4];
let y = [2, 2, 2];
let max_gap = 2.0;
let result = magpie_integrate(x, y, max_gap);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
8
2
3
1
Practice
Change x = [0, 2], y = [0, 2]. Predict the result, then run the program.
Hint
Returns [area, span-weighted mean, widest gap, exceeds gap limit]. Rejects duplicate or reversed sample times.
Solution
The result vector is [2, 1, 2, 0]. Compare its fields with the return layout in the API section.
Find
let x = [0, 1, 4];
Replace with
let x = [0, 2];
Find
let y = [2, 2, 2];
Replace with
let y = [0, 2];
Output after the change
2
1
2
0
Workflow recipes
Flamingo · Choose chart ticks for an observed range
Produce chart-ready axis limits and labeled tick spacing from raw data.
Choose chart ticks for an observed range
A constant series collapses a chart axis; raw decimal steps make labels hard to read. Expand the domain before choosing a tick lattice. Including zero extends the data range to 0–11. A five-unit tick step covers that range through 15.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [first tick, last tick, step, tick count]. The tick count can differ from the requested interval target. Invalid input returns an empty vector.
Argument
Accepted input
samples
Vector of: finite number
include_zero
nonnegative exact integer
intervals
positive exact integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Flamingo 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-flamingo/tree/v0.1.0
fn axisrange_min2(a: f64, b: f64) -> f64 {
if a < b {
return a;
}
b
}
fn axisrange_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn axisrange_absolute(value: f64) -> f64 {
if value < 0.0 {
return - value;
}
value
}
fn axisrange_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn axisrange_compute(samples: vector, zero: f64) -> vector {
if len(samples) == 0 || zero > 1.0 {
return [];
}
let mut lo = at(samples, 0);
let mut hi = lo;
let mut i = 1;
while i < len(samples) {
lo = axisrange_min2(lo, at(samples, i));
hi = axisrange_max2(hi, at(samples, i));
i += 1;
}
if zero == 1.0 {
lo = axisrange_min2(lo, 0.0);
hi = axisrange_max2(hi, 0.0);
}
if hi == lo {
let pad = axisrange_max2(0.5, axisrange_absolute(lo) * 0.05);
lo -= pad;
hi += pad;
}
[lo, hi]
}
// Compute a chart domain and expand a constant-valued series.
// Returns [lower, upper]. Set zero to 1 to include the origin. A constant domain receives ±0.5 or ±5% of its magnitude, whichever is larger.
pub fn axisrange_extent(samples: vector, zero: f64) -> vector {
if !axisrange_finite(samples) { return []; }
if !(zero >= 0.0 && zero <= 9007199254740991.0 && zero % 1.0 == 0.0) { return []; }
let result = axisrange_compute(samples, zero);
if !axisrange_finite(result) { return []; }
result
}
fn tickstep_absolute(value: f64) -> f64 {
if value < 0.0 {
return - value;
}
value
}
fn tickstep_floorreal(value: f64) -> f64 {
let trunc = value - value % 1.0;
if trunc > value {
return trunc - 1.0;
}
trunc
}
fn tickstep_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn tickstep_compute(lo: f64, hi: f64, intervals: f64) -> vector {
if hi <= lo {
return [];
}
let raw = (hi - lo) / intervals;
if raw < 1.0e-100 || raw > 1.0e100 {
return [];
}
let mut unit = 1.0;
while unit * 10.0 <= raw {
unit *= 10.0;
}
while unit > raw {
unit /= 10.0;
}
let ratio = raw / unit;
let mut step = unit;
if ratio > 5.0 {
step *= 10.0;
} else {
if ratio > 2.0 {
step *= 5.0;
} else {
if ratio > 1.0 {
step *= 2.0;
}
}
}
let first = tickstep_floorreal(lo / step);
let last = -tickstep_floorreal(-hi / step);
if tickstep_absolute(first) > 9007199254740991.0 || tickstep_absolute(last) > 9007199254740991.0 {
return [];
}
[first * step, last * step, step, last - first + 1.0]
}
// Choose a covering linear tick lattice using steps 1, 2, 5 or 10 times a power of ten.
// Returns [first tick, last tick, step, tick count]. Interval count is a target. Supported raw steps range from 1e-100 to 1e100.
pub fn tickstep_cover(lo: f64, hi: f64, intervals: f64) -> vector {
if !(lo - lo == 0.0) { return []; }
if !(hi - hi == 0.0) { return []; }
if !(intervals >= 1.0 && intervals <= 9007199254740991.0 && intervals % 1.0 == 0.0) { return []; }
let result = tickstep_compute(lo, hi, intervals);
if !tickstep_finite(result) { return []; }
result
}
fn flamingo_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn flamingo_compute(samples: vector, include_zero: f64, intervals: f64) -> vector {
let domain = axisrange_extent(samples, include_zero);
if len(domain) == 0 {
return [];
}
tickstep_cover(at(domain, 0), at(domain, 1), intervals)
}
// Produce chart-ready axis limits and labeled tick spacing from raw data.
// Returns [first tick, last tick, step, tick count]. The tick count can differ from the requested interval target.
pub fn flamingo_axis(samples: vector, include_zero: f64, intervals: f64) -> vector {
if !flamingo_finite(samples) { return []; }
if !(include_zero >= 0.0 && include_zero <= 9007199254740991.0 && include_zero % 1.0 == 0.0) { return []; }
if !(intervals >= 1.0 && intervals <= 9007199254740991.0 && intervals % 1.0 == 0.0) { return []; }
let result = flamingo_compute(samples, include_zero, intervals);
if !flamingo_finite(result) { return []; }
result
}
fn main() {
let samples = [3, 11];
let include_zero = 1.0;
let intervals = 4.0;
let result = flamingo_axis(samples, include_zero, intervals);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
0
15
5
4
Practice
Change samples = [0, 0], include_zero = 0.0, intervals = 2.0. Predict the result, then run the program.
Hint
Returns [first tick, last tick, step, tick count]. The tick count can differ from the requested interval target.
Solution
The result vector is [-0.5, 0.5, 0.5, 3]. Compare its fields with the return layout in the API section.
Find
let samples = [3, 11];
Replace with
let samples = [0, 0];
Find
let include_zero = 1.0;
Replace with
let include_zero = 0.0;
Find
let intervals = 4.0;
Replace with
let intervals = 2.0;
Output after the change
-0.5
0.5
0.5
3
Workflow recipes
Bittern · Decide whether the next database migration can run
Plan the next migration only after history, fingerprints and dirty state agree.
Decide whether the next database migration can run
A version number can match even when a previous migration changed. Check the applied prefix and recorded fingerprints before planning the next step. The two applied versions form an exact prefix with matching fingerprints. Version 5 is ready to apply.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [can apply next, next available version, pending count, changed fingerprints]. This preflight consumes an exported history and executes no SQL. Invalid input returns an empty vector.
Argument
Accepted input
available
Vector of: nonnegative exact integer
applied
Vector of: nonnegative exact integer
expected
Vector of: nonnegative exact integer
actual
Vector of: nonnegative exact integer
dirty
nonnegative exact integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Bittern 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-bittern/tree/v0.1.0
fn versionchain_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn versionchain_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn versionchain_compute(available: vector, applied: vector) -> vector {
if len(applied) > len(available) {
return [];
}
let mut i = 0;
while i < len(available) {
if i > 0 && at(available, i) <= at(available, i - 1) {
return [];
}
if i < len(applied) && at(available, i) != at(applied, i) {
return [];
}
i += 1;
}
let mut next = -1.0;
if len(applied) < len(available) {
next = at(available, len(applied));
}
[len(applied), len(available) - len(applied), next]
}
// Validate an applied migration log against a strictly increasing release manifest.
// Returns [applied prefix length, pending count, next version or -1]. Every applied version must match the corresponding release entry.
pub fn versionchain_prefix(available: vector, applied: vector) -> vector {
if !versionchain_counts(available) { return []; }
if !versionchain_counts(applied) { return []; }
let result = versionchain_compute(available, applied);
if !versionchain_finite(result) { return []; }
result
}
fn schemaguard_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn schemaguard_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn schemaguard_compute(expected: vector, actual: vector) -> vector {
if len(expected) != len(actual) {
return [];
}
let mut first = -1;
let mut count = 0;
let mut i = 0;
while i < len(expected) {
if at(expected, i) != at(actual, i) {
if first < 0 {
first = i;
}
count += 1;
}
i += 1;
}
[first, count]
}
// Detect changed fingerprints for previously applied migrations.
// Returns [first mismatch index, mismatch count]. Supply aligned integer fingerprint IDs derived by a trusted host, with one ID per applied migration.
pub fn schemaguard_drift(expected: vector, actual: vector) -> vector {
if !schemaguard_counts(expected) { return []; }
if !schemaguard_counts(actual) { return []; }
let result = schemaguard_compute(expected, actual);
if !schemaguard_finite(result) { return []; }
result
}
fn bittern_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn bittern_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn bittern_compute(available: vector, applied: vector, expected: vector, actual: vector, dirty: f64) -> vector {
if dirty > 1.0 || len(expected) != len(applied) {
return [];
}
let chain = versionchain_prefix(available, applied);
let drift = schemaguard_drift(expected, actual);
if len(chain) == 0 || len(drift) == 0 {
return [];
}
let mut ready = 0;
if dirty == 0.0 && at(drift, 1) == 0.0 && at(chain, 1) > 0.0 {
ready = 1;
}
[ready, at(chain, 2), at(chain, 1), at(drift, 1)]
}
// Plan the next migration only after history, fingerprints and dirty state agree.
// Returns [can apply next, next available version, pending count, changed fingerprints]. This preflight consumes an exported history and executes no SQL.
pub fn bittern_preflight(available: vector, applied: vector, expected: vector, actual: vector, dirty: f64) -> vector {
if !bittern_counts(available) { return []; }
if !bittern_counts(applied) { return []; }
if !bittern_counts(expected) { return []; }
if !bittern_counts(actual) { return []; }
if !(dirty >= 0.0 && dirty <= 9007199254740991.0 && dirty % 1.0 == 0.0) { return []; }
let result = bittern_compute(available, applied, expected, actual, dirty);
if !bittern_finite(result) { return []; }
result
}
fn main() {
let available = [1, 2, 5];
let applied = [1, 2];
let expected = [10, 20];
let actual = [10, 20];
let dirty = 0.0;
let result = bittern_preflight(available, applied, expected, actual, dirty);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
1
5
1
0
Practice
Change available = [1, 2], applied = [1], expected = [4], actual = [7]. Predict the result, then run the program.
Hint
Returns [can apply next, next available version, pending count, changed fingerprints]. This preflight consumes an exported history and executes no SQL.
Solution
The result vector is [0, 2, 1, 1]. Compare its fields with the return layout in the API section.
Find
let available = [1, 2, 5];
Replace with
let available = [1, 2];
Find
let applied = [1, 2];
Replace with
let applied = [1];
Find
let expected = [10, 20];
Replace with
let expected = [4];
Find
let actual = [10, 20];
Replace with
let actual = [7];
Output after the change
0
2
1
1
Workflow recipes
Grebe · Resume a keyset page from its last emitted key
Build a repeatable keyset page and return the exact next cursor.
Resume a keyset page from its last emitted key
Offset pagination on changing data can repeat records. Validate the ordered key and return the final emitted key for the next request. A cursor between keys selects 20 and 30. Returning 30 lets the next page start at 40.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [first index, exclusive end, resume key, has more]. On an empty result the input cursor is retained. Supply stable unique numeric keys from a consistent snapshot. Invalid input returns an empty vector.
Argument
Accepted input
keys
Vector of: exact signed integer
cursor
exact signed integer
size
positive exact integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Grebe 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-grebe/tree/v0.1.0
fn keyorders_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn keyorders_integers(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= -9007199254740991.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn keyorders_compute(keys: vector) -> vector {
let mut equal = 0;
let mut down = 0;
let mut i = 1;
while i < len(keys) {
if at(keys, i) == at(keys, i - 1) {
equal += 1;
}
if at(keys, i) < at(keys, i - 1) {
down += 1;
}
i += 1;
}
if equal == 0 && down == 0 {
return [1, 0, 0];
}
[0, equal, down]
}
// Check a cursor key sequence for repeated and descending adjacent values.
// Returns [strictly increasing, adjacent duplicates, descending pairs]. Intended for unique ordered numeric keys.
pub fn keyorders_strict(keys: vector) -> vector {
if !keyorders_integers(keys) { return []; }
let result = keyorders_compute(keys);
if !keyorders_finite(result) { return []; }
result
}
fn pagecursor_min2(a: f64, b: f64) -> f64 {
if a < b {
return a;
}
b
}
fn pagecursor_num(value: i64) -> f64 {
at([value], 0)
}
fn pagecursor_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn pagecursor_integers(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= -9007199254740991.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn pagecursor_compute(keys: vector, cursor: f64, size: f64) -> vector {
let mut i = 1;
while i < len(keys) {
if at(keys, i) <= at(keys, i - 1) {
return [];
}
i += 1;
}
let mut low = 0;
let mut high = len(keys);
while low < high {
let mid = low + (high - low) / 2;
if at(keys, mid) <= cursor {
low = mid + 1;
} else {
high = mid;
}
}
let end = pagecursor_min2(pagecursor_num(len(keys)), pagecursor_num(low) + size);
let mut more = 0;
if end < pagecursor_num(len(keys)) {
more = 1;
}
[low, end, more]
}
// Find a keyset page strictly after a cursor in sorted keys.
// Returns [first index, exclusive end, has more]. Verifies strict ordering, then uses binary search. An absent cursor is valid.
pub fn pagecursor_after(keys: vector, cursor: f64, size: f64) -> vector {
if !pagecursor_integers(keys) { return []; }
if !(cursor >= -9007199254740991.0 && cursor <= 9007199254740991.0 && cursor % 1.0 == 0.0) { return []; }
if !(size >= 1.0 && size <= 9007199254740991.0 && size % 1.0 == 0.0) { return []; }
let result = pagecursor_compute(keys, cursor, size);
if !pagecursor_finite(result) { return []; }
result
}
fn grebe_num(value: i64) -> f64 {
at([value], 0)
}
fn grebe_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn grebe_integers(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= -9007199254740991.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn grebe_compute(keys: vector, cursor: f64, size: f64) -> vector {
let quality = keyorders_strict(keys);
if len(quality) == 0 || at(quality, 0) != 1.0 {
return [];
}
let page = pagecursor_after(keys, cursor, size);
if len(page) == 0 {
return [];
}
let mut resume = cursor;
let mut i = 0;
while i < len(keys) && grebe_num(i) < at(page, 1) {
if grebe_num(i) >= at(page, 0) {
resume = at(keys, i);
}
i += 1;
}
[at(page, 0), at(page, 1), resume, at(page, 2)]
}
// Build a repeatable keyset page and return the exact next cursor.
// Returns [first index, exclusive end, resume key, has more]. On an empty result the input cursor is retained. Supply stable unique numeric keys from a consistent snapshot.
pub fn grebe_page(keys: vector, cursor: f64, size: f64) -> vector {
if !grebe_integers(keys) { return []; }
if !(cursor >= -9007199254740991.0 && cursor <= 9007199254740991.0 && cursor % 1.0 == 0.0) { return []; }
if !(size >= 1.0 && size <= 9007199254740991.0 && size % 1.0 == 0.0) { return []; }
let result = grebe_compute(keys, cursor, size);
if !grebe_finite(result) { return []; }
result
}
fn main() {
let keys = [10, 20, 30, 40];
let cursor = 15.0;
let size = 2.0;
let result = grebe_page(keys, cursor, size);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
1
3
30
1
Practice
Change keys = [1, 2], cursor = 3.0. Predict the result, then run the program.
Hint
Returns [first index, exclusive end, resume key, has more]. On an empty result the input cursor is retained. Supply stable unique numeric keys from a consistent snapshot.
Solution
The result vector is [2, 2, 3, 0]. Compare its fields with the return layout in the API section.
Find
let keys = [10, 20, 30, 40];
Replace with
let keys = [1, 2];
Find
let cursor = 15.0;
Replace with
let cursor = 3.0;
Output after the change
2
2
3
0
Workflow recipes
Dunlin · Audit a parent and child table before import
Audit a table export for duplicate parents and orphaned child rows.
Audit a parent and child table before import
A child reference can look valid while the parent key is duplicated. Check uniqueness and referential integrity before a bulk import. The parent export repeats ID 1. Two child rows reference the missing ID 2.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [load acceptable, duplicate parent rows, orphan child rows, first orphan row]. This local check complements database-enforced constraints. Invalid input returns an empty vector.
Argument
Accepted input
parents
Vector of: exact signed integer
children
Vector of: exact signed integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Dunlin 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-dunlin/tree/v0.1.0
fn keyduplicates_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn keyduplicates_integers(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= -9007199254740991.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn keyduplicates_compute(keys: vector) -> vector {
let mut duplicates = 0;
let mut first = -1;
let mut i = 0;
while i < len(keys) {
let mut j = 0;
while j < i {
if at(keys, j) == at(keys, i) {
duplicates += 1;
if first < 0 {
first = i;
}
break;
}
j += 1;
}
i += 1;
}
[duplicates, first, len(keys) - duplicates]
}
// Find repeated primary-key occurrences in an offline table export.
// Returns [duplicate rows beyond first occurrence, first duplicate row, unique keys]. Uses pairwise comparison on a small batch.
pub fn keyduplicates_count(keys: vector) -> vector {
if !keyduplicates_integers(keys) { return []; }
let result = keyduplicates_compute(keys);
if !keyduplicates_finite(result) { return []; }
result
}
fn foreignmiss_hasid(values: vector, key: f64) -> bool {
let mut i = 0;
while i < len(values) {
if at(values, i) == key {
return true;
}
i += 1;
}
false
}
fn foreignmiss_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn foreignmiss_integers(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= -9007199254740991.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn foreignmiss_compute(parents: vector, children: vector) -> vector {
let mut count = 0;
let mut first = -1;
let mut i = 0;
while i < len(children) {
if !foreignmiss_hasid(parents, at(children, i)) {
if first < 0 {
first = i;
}
count += 1;
}
i += 1;
}
[count, first]
}
// Count child rows referencing absent numeric parent keys.
// Returns [orphan rows, first orphan row]. Repeated child references are checked independently; represent missing/null separately.
pub fn foreignmiss_count(parents: vector, children: vector) -> vector {
if !foreignmiss_integers(parents) { return []; }
if !foreignmiss_integers(children) { return []; }
let result = foreignmiss_compute(parents, children);
if !foreignmiss_finite(result) { return []; }
result
}
fn dunlin_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn dunlin_integers(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= -9007199254740991.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn dunlin_compute(parents: vector, children: vector) -> vector {
let dup = keyduplicates_count(parents);
let missing = foreignmiss_count(parents, children);
if len(dup) == 0 || len(missing) == 0 {
return [];
}
let mut ok = 0;
if at(dup, 0) == 0.0 && at(missing, 0) == 0.0 {
ok = 1;
}
[ok, at(dup, 0), at(missing, 0), at(missing, 1)]
}
// Audit a table export for duplicate parents and orphaned child rows.
// Returns [load acceptable, duplicate parent rows, orphan child rows, first orphan row]. This local check complements database-enforced constraints.
pub fn dunlin_check(parents: vector, children: vector) -> vector {
if !dunlin_integers(parents) { return []; }
if !dunlin_integers(children) { return []; }
let result = dunlin_compute(parents, children);
if !dunlin_finite(result) { return []; }
result
}
fn main() {
let parents = [1, 1, 3];
let children = [1, 2, 2];
let result = dunlin_check(parents, children);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
0
1
2
1
Practice
Change parents = [1, 3], children = [3, 1]. Predict the result, then run the program.
Hint
Returns [load acceptable, duplicate parent rows, orphan child rows, first orphan row]. This local check complements database-enforced constraints.
Solution
The result vector is [1, 0, 0, -1]. Compare its fields with the return layout in the API section.
Find
let parents = [1, 1, 3];
Replace with
let parents = [1, 3];
Find
let children = [1, 2, 2];
Replace with
let children = [3, 1];
Output after the change
1
0
0
-1
Workflow recipes
Sanderling · Carry cache age across a local storage interval
Choose a cache serving mode from stored age, local elapsed time and grace policy.
Carry cache age across a local storage interval
Starting freshness at zero on every cache hop can keep stale content alive. Carry the stored age forward before applying grace. An entry stored at age eight reaches age thirteen after five more ticks. Three ticks of its stale-serving grace remain.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [mode, current age, ticks until mode changes]. Mode 0 serves fresh, 1 serves under explicit stale grace, and 2 requires validation. The host parses and enforces other cache directives. Invalid input returns an empty vector.
Argument
Accepted input
age_at_store
nonnegative finite number
stored
nonnegative finite number
now
nonnegative finite number
lifetime
nonnegative finite number
grace
nonnegative finite number
mandatory
nonnegative exact integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Sanderling 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-sanderling/tree/v0.1.0
fn freshclock_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn freshclock_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn freshclock_compute(age_at_store: f64, stored: f64, now: f64, lifetime: f64) -> vector {
if now < stored {
return [];
}
let age = age_at_store + (now - stored);
[age, freshclock_max2(0.0, lifetime - age), freshclock_max2(0.0, age - lifetime)]
}
// Advance an already calculated HTTP cache age on a monotonic clock.
// Returns [current age, remaining freshness, stale age]. Supply corrected initial age. Equality with freshness lifetime is stale.
pub fn freshclock_age(age_at_store: f64, stored: f64, now: f64, lifetime: f64) -> vector {
if !(age_at_store >= 0.0 && age_at_store - age_at_store == 0.0) { return []; }
if !(stored >= 0.0 && stored - stored == 0.0) { return []; }
if !(now >= 0.0 && now - now == 0.0) { return []; }
if !(lifetime >= 0.0 && lifetime - lifetime == 0.0) { return []; }
let result = freshclock_compute(age_at_store, stored, now, lifetime);
if !freshclock_finite(result) { return []; }
result
}
fn stalewindow_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn stalewindow_compute(age: f64, lifetime: f64, grace: f64, mandatory: f64) -> vector {
if mandatory > 1.0 {
return [];
}
if age < lifetime {
return [0, lifetime - age];
}
if mandatory == 0.0 && age - lifetime < grace {
return [1, grace - (age - lifetime)];
}
[2, 0]
}
// Classify a cache entry under an explicit stale-serving policy.
// Returns [mode, ticks remaining in current window]. Mode 0 is fresh, 1 is stale within grace, 2 requires validation. Mandatory validation disables grace for stale entries.
pub fn stalewindow_classify(age: f64, lifetime: f64, grace: f64, mandatory: f64) -> vector {
if !(age >= 0.0 && age - age == 0.0) { return []; }
if !(lifetime >= 0.0 && lifetime - lifetime == 0.0) { return []; }
if !(grace >= 0.0 && grace - grace == 0.0) { return []; }
if !(mandatory >= 0.0 && mandatory <= 9007199254740991.0 && mandatory % 1.0 == 0.0) { return []; }
let result = stalewindow_compute(age, lifetime, grace, mandatory);
if !stalewindow_finite(result) { return []; }
result
}
fn sanderling_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn sanderling_compute(age_at_store: f64, stored: f64, now: f64, lifetime: f64, grace: f64, mandatory: f64) -> vector {
let clock = freshclock_age(age_at_store, stored, now, lifetime);
if len(clock) == 0 {
return [];
}
let policy = stalewindow_classify(at(clock, 0), lifetime, grace, mandatory);
if len(policy) == 0 {
return [];
}
[at(policy, 0), at(clock, 0), at(policy, 1)]
}
// Choose a cache serving mode from stored age, local elapsed time and grace policy.
// Returns [mode, current age, ticks until mode changes]. Mode 0 serves fresh, 1 serves under explicit stale grace, and 2 requires validation. The host parses and enforces other cache directives.
pub fn sanderling_lookup(age_at_store: f64, stored: f64, now: f64, lifetime: f64, grace: f64, mandatory: f64) -> vector {
if !(age_at_store >= 0.0 && age_at_store - age_at_store == 0.0) { return []; }
if !(stored >= 0.0 && stored - stored == 0.0) { return []; }
if !(now >= 0.0 && now - now == 0.0) { return []; }
if !(lifetime >= 0.0 && lifetime - lifetime == 0.0) { return []; }
if !(grace >= 0.0 && grace - grace == 0.0) { return []; }
if !(mandatory >= 0.0 && mandatory <= 9007199254740991.0 && mandatory % 1.0 == 0.0) { return []; }
let result = sanderling_compute(age_at_store, stored, now, lifetime, grace, mandatory);
if !sanderling_finite(result) { return []; }
result
}
fn main() {
let age_at_store = 8.0;
let stored = 100.0;
let now = 105.0;
let lifetime = 10.0;
let grace = 6.0;
let mandatory = 0.0;
let result = sanderling_lookup(age_at_store, stored, now, lifetime, grace, mandatory);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
1
13
3
Practice
Change mandatory = 1.0. Predict the result, then run the program.
Hint
Returns [mode, current age, ticks until mode changes]. Mode 0 serves fresh, 1 serves under explicit stale grace, and 2 requires validation. The host parses and enforces other cache directives.
Solution
The result vector is [2, 13, 0]. Compare its fields with the return layout in the API section.
Find
let mandatory = 0.0;
Replace with
let mandatory = 1.0;
Output after the change
2
13
0
Workflow recipes
Cormorant · Separate packet jitter from a fixed clock offset
Separate variation in packet delivery from a constant difference between clocks.
Separate packet jitter from a fixed clock offset
Absolute one-way delay depends on clock alignment. Changes in transit can still reveal jitter when the clock offset is stable. Transit changes by 32 ticks. Starting from zero, the one-sixteenth update yields two ticks of smoothed jitter.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [transit range, smoothed jitter, adjacent pairs]. Input rows must be in arrival order and use unwrapped sender timestamps. Invalid input returns an empty vector.
Argument
Accepted input
sent
Vector of: exact signed integer
arrived
Vector of: exact signed integer
initial
nonnegative finite number
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Cormorant 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-cormorant/tree/v0.1.0
fn transitspan_min2(a: f64, b: f64) -> f64 {
if a < b {
return a;
}
b
}
fn transitspan_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn transitspan_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn transitspan_integers(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= -9007199254740991.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn transitspan_compute(sent: vector, arrived: vector) -> vector {
if len(sent) == 0 || len(sent) != len(arrived) {
return [];
}
let mut lo = at(arrived, 0) - at(sent, 0);
let mut hi = lo;
let mut reversed = 0;
let mut i = 1;
while i < len(sent) {
let d = at(arrived, i) - at(sent, i);
lo = transitspan_min2(lo, d);
hi = transitspan_max2(hi, d);
if at(arrived, i) < at(arrived, i - 1) {
reversed += 1;
}
i += 1;
}
[lo, hi, reversed]
}
// Summarize observed packet transit differences and arrival reorderings.
// Returns [minimum arrival minus send, maximum, backward arrival steps]. Times use the same tick unit and a stable offset between clocks.
pub fn transitspan_profile(sent: vector, arrived: vector) -> vector {
if !transitspan_integers(sent) { return []; }
if !transitspan_integers(arrived) { return []; }
let result = transitspan_compute(sent, arrived);
if !transitspan_finite(result) { return []; }
result
}
fn jittermean_absolute(value: f64) -> f64 {
if value < 0.0 {
return - value;
}
value
}
fn jittermean_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn jittermean_integers(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= -9007199254740991.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn jittermean_compute(sent: vector, arrived: vector, initial: f64) -> vector {
if len(sent) == 0 || len(sent) != len(arrived) {
return [];
}
let mut jitter = initial;
let mut prev = at(arrived, 0) - at(sent, 0);
let mut i = 1;
while i < len(sent) {
let transit = at(arrived, i) - at(sent, i);
jitter += (jittermean_absolute(transit - prev) - jitter) / 16.0;
prev = transit;
i += 1;
}
[jitter, len(sent) - 1]
}
// Estimate interarrival jitter with the RFC 3550 one-sixteenth update.
// Returns [updated jitter, adjacent pairs]. Supply arrival-order packets in the same unwrapped timestamp units; the first observation establishes transit.
pub fn jittermean_rtp(sent: vector, arrived: vector, initial: f64) -> vector {
if !jittermean_integers(sent) { return []; }
if !jittermean_integers(arrived) { return []; }
if !(initial >= 0.0 && initial - initial == 0.0) { return []; }
let result = jittermean_compute(sent, arrived, initial);
if !jittermean_finite(result) { return []; }
result
}
fn cormorant_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn cormorant_integers(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= -9007199254740991.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn cormorant_compute(sent: vector, arrived: vector, initial: f64) -> vector {
let span = transitspan_profile(sent, arrived);
if len(span) == 0 || at(span, 2) > 0.0 {
return [];
}
let j = jittermean_rtp(sent, arrived, initial);
if len(j) == 0 {
return [];
}
[at(span, 1) - at(span, 0), at(j, 0), at(j, 1)]
}
// Separate variation in packet delivery from a constant difference between clocks.
// Returns [transit range, smoothed jitter, adjacent pairs]. Input rows must be in arrival order and use unwrapped sender timestamps.
pub fn cormorant_trace(sent: vector, arrived: vector, initial: f64) -> vector {
if !cormorant_integers(sent) { return []; }
if !cormorant_integers(arrived) { return []; }
if !(initial >= 0.0 && initial - initial == 0.0) { return []; }
let result = cormorant_compute(sent, arrived, initial);
if !cormorant_finite(result) { return []; }
result
}
fn main() {
let sent = [0, 16];
let arrived = [100, 148];
let initial = 0.0;
let result = cormorant_trace(sent, arrived, initial);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
32
2
1
Practice
Change sent = [0, 10], arrived = [3, 13]. Predict the result, then run the program.
Hint
Returns [transit range, smoothed jitter, adjacent pairs]. Input rows must be in arrival order and use unwrapped sender timestamps.
Solution
The result vector is [0, 0, 1]. Compare its fields with the return layout in the API section.
Find
let sent = [0, 16];
Replace with
let sent = [0, 10];
Find
let arrived = [100, 148];
Replace with
let arrived = [3, 13];
Output after the change
0
0
1
Workflow recipes
Bulbul · Validate required and extra object fields
Check required and extra fields in an already parsed object.
Validate required and extra object fields
Rejecting unknown fields and enforcing required fields are independent policy choices. Return both diagnostics in one pass through the workflow. The example both omits required field 2 and supplies unrecognized field 9. The report retains both counts.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [accepted, missing count, extra count, first missing ID]. Use an explicit field-name-to-ID map. Closed mode rejects extra fields; required IDs must be in the declared allowed set. Invalid input returns an empty vector.
Argument
Accepted input
present
Vector of: nonnegative exact integer
allowed
Vector of: nonnegative exact integer
required
Vector of: nonnegative exact integer
closed
nonnegative exact integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Bulbul 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-bulbul/tree/v0.1.0
fn allowfields_hasid(values: vector, key: f64) -> bool {
let mut i = 0;
while i < len(values) {
if at(values, i) == key {
return true;
}
i += 1;
}
false
}
fn allowfields_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn allowfields_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn allowfields_compute(present: vector, allowed: vector) -> vector {
let mut extras = 0;
let mut first = -1;
let mut i = 0;
while i < len(present) {
if !allowfields_hasid(allowed, at(present, i)) {
if first < 0 {
first = i;
}
extras += 1;
}
i += 1;
}
[extras, first]
}
// Find unrecognized fields after mapping schema keys to stable IDs.
// Returns [extra occurrences, first extra position]. Required-property presence is a separate check.
pub fn allowfields_extra(present: vector, allowed: vector) -> vector {
if !allowfields_counts(present) { return []; }
if !allowfields_counts(allowed) { return []; }
let result = allowfields_compute(present, allowed);
if !allowfields_finite(result) { return []; }
result
}
fn requiredset_hasid(values: vector, key: f64) -> bool {
let mut i = 0;
while i < len(values) {
if at(values, i) == key {
return true;
}
i += 1;
}
false
}
fn requiredset_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn requiredset_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn requiredset_compute(present: vector, required: vector) -> vector {
let mut missing = 0;
let mut first = -1.0;
let mut i = 0;
while i < len(required) {
let id = at(required, i);
let mut j = 0;
while j < i {
if at(required, j) == id {
return [];
}
j += 1;
}
if !requiredset_hasid(present, id) {
if missing == 0 {
first = id;
}
missing += 1;
}
i += 1;
}
[missing, first]
}
// Find missing unique required keys in an object shape.
// Returns [missing keys, first missing key ID]. Duplicate requirements are rejected as a malformed schema.
pub fn requiredset_missing(present: vector, required: vector) -> vector {
if !requiredset_counts(present) { return []; }
if !requiredset_counts(required) { return []; }
let result = requiredset_compute(present, required);
if !requiredset_finite(result) { return []; }
result
}
fn bulbul_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn bulbul_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn bulbul_compute(present: vector, allowed: vector, required: vector, closed: f64) -> vector {
if closed > 1.0 {
return [];
}
let schema = allowfields_extra(required, allowed);
if len(schema) == 0 || at(schema, 0) > 0.0 {
return [];
}
let extra = allowfields_extra(present, allowed);
let needed = requiredset_missing(present, required);
if len(extra) == 0 || len(needed) == 0 {
return [];
}
let mut ok = 0;
if at(needed, 0) == 0.0 && (closed == 0.0 || at(extra, 0) == 0.0) {
ok = 1;
}
[ok, at(needed, 0), at(extra, 0), at(needed, 1)]
}
// Check required and extra fields in an already parsed object.
// Returns [accepted, missing count, extra count, first missing ID]. Use an explicit field-name-to-ID map. Closed mode rejects extra fields; required IDs must be in the declared allowed set.
pub fn bulbul_shape(present: vector, allowed: vector, required: vector, closed: f64) -> vector {
if !bulbul_counts(present) { return []; }
if !bulbul_counts(allowed) { return []; }
if !bulbul_counts(required) { return []; }
if !(closed >= 0.0 && closed <= 9007199254740991.0 && closed % 1.0 == 0.0) { return []; }
let result = bulbul_compute(present, allowed, required, closed);
if !bulbul_finite(result) { return []; }
result
}
fn main() {
let present = [1, 9];
let allowed = [1, 2];
let required = [1, 2];
let closed = 1.0;
let result = bulbul_shape(present, allowed, required, closed);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
0
1
1
2
Practice
Change allowed = [1], required = [1], closed = 0.0. Predict the result, then run the program.
Hint
Returns [accepted, missing count, extra count, first missing ID]. Use an explicit field-name-to-ID map. Closed mode rejects extra fields; required IDs must be in the declared allowed set.
Solution
The result vector is [1, 0, 1, -1]. Compare its fields with the return layout in the API section.
Find
let allowed = [1, 2];
Replace with
let allowed = [1];
Find
let required = [1, 2];
Replace with
let required = [1];
Find
let closed = 1.0;
Replace with
let closed = 0.0;
Output after the change
1
0
1
-1
Workflow recipes
Fantail · Find which settings layer supplied an invalid override
Resolve a layered setting and report where an invalid override came from.
Find which settings layer supplied an invalid override
Treating zero as an absent setting silently restores older values. Carry a presence flag and the identity of the winning layer. The second layer sets the value to 15 and the last layer has no value. The effective override is five above the limit.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [accepted, selected value, winning layer, distance outside bounds]. An invalid override remains visible for diagnosis. Invalid input returns an empty vector.
Argument
Accepted input
values
Vector of: finite number
present
Vector of: nonnegative exact integer
fallback
finite number
minimum
finite number
maximum
finite number
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Fantail 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-fantail/tree/v0.1.0
fn optionlayer_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn optionlayer_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn optionlayer_compute(values: vector, present: vector, fallback: f64) -> vector {
if len(values) != len(present) {
return [];
}
let mut chosen = fallback;
let mut layer = -1;
let mut supplied = 0;
let mut i = 0;
while i < len(values) {
let flag = at(present, i);
if flag > 1.0 {
return [];
}
if flag == 1.0 {
chosen = at(values, i);
layer = i;
supplied += 1;
}
i += 1;
}
[chosen, layer, supplied]
}
// Resolve a numeric setting across ordered configuration layers.
// Returns [effective value, winning layer index, number of supplied values]. Later layers win; presence flags distinguish zero from an unset value.
pub fn optionlayer_resolve(values: vector, present: vector, fallback: f64) -> vector {
if !optionlayer_finite(values) { return []; }
if !optionlayer_counts(present) { return []; }
if !(fallback - fallback == 0.0) { return []; }
let result = optionlayer_compute(values, present, fallback);
if !optionlayer_finite(result) { return []; }
result
}
fn valuebounds_min2(a: f64, b: f64) -> f64 {
if a < b {
return a;
}
b
}
fn valuebounds_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn valuebounds_absolute(value: f64) -> f64 {
if value < 0.0 {
return - value;
}
value
}
fn valuebounds_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn valuebounds_compute(value: f64, minimum: f64, maximum: f64) -> vector {
if minimum > maximum {
return [];
}
let nearest = valuebounds_min2(valuebounds_max2(value, minimum), maximum);
if nearest == value {
return [1, value, 0];
}
[0, nearest, valuebounds_absolute(nearest - value)]
}
// Check a numeric setting against inclusive bounds and explain the violation.
// Returns [in bounds, nearest legal value, absolute distance outside]. Reversed bounds are invalid.
pub fn valuebounds_check(value: f64, minimum: f64, maximum: f64) -> vector {
if !(value - value == 0.0) { return []; }
if !(minimum - minimum == 0.0) { return []; }
if !(maximum - maximum == 0.0) { return []; }
let result = valuebounds_compute(value, minimum, maximum);
if !valuebounds_finite(result) { return []; }
result
}
fn fantail_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn fantail_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn fantail_compute(values: vector, present: vector, fallback: f64, minimum: f64, maximum: f64) -> vector {
let layer = optionlayer_resolve(values, present, fallback);
if len(layer) == 0 {
return [];
}
let rule = valuebounds_check(at(layer, 0), minimum, maximum);
if len(rule) == 0 {
return [];
}
[at(rule, 0), at(layer, 0), at(layer, 1), at(rule, 2)]
}
// Resolve a layered setting and report where an invalid override came from.
// Returns [accepted, selected value, winning layer, distance outside bounds]. An invalid override remains visible for diagnosis.
pub fn fantail_setting(values: vector, present: vector, fallback: f64, minimum: f64, maximum: f64) -> vector {
if !fantail_finite(values) { return []; }
if !fantail_counts(present) { return []; }
if !(fallback - fallback == 0.0) { return []; }
if !(minimum - minimum == 0.0) { return []; }
if !(maximum - maximum == 0.0) { return []; }
let result = fantail_compute(values, present, fallback, minimum, maximum);
if !fantail_finite(result) { return []; }
result
}
fn main() {
let values = [2, 15, 0];
let present = [1, 1, 0];
let fallback = 5.0;
let minimum = 0.0;
let maximum = 10.0;
let result = fantail_setting(values, present, fallback, minimum, maximum);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
0
15
1
5
Practice
Change values = [3, 0], present = [1, 1]. Predict the result, then run the program.
Hint
Returns [accepted, selected value, winning layer, distance outside bounds]. An invalid override remains visible for diagnosis.
Solution
The result vector is [1, 0, 1, 0]. Compare its fields with the return layout in the API section.
Find
let values = [2, 15, 0];
Replace with
let values = [3, 0];
Find
let present = [1, 1, 0];
Replace with
let present = [1, 1];
Output after the change
1
0
1
0
Workflow recipes
Swallow · Verify a record table before interpreting a byte offset
Validate an exported payload's declared spans and checksum, then locate a byte.
Verify a record table before interpreting a byte offset
A valid byte offset can point into the wrong serialized record if lengths have drifted. Verify the table and payload before interpreting the offset. The payload bytes 65 and 66 yield checksum 12976260. Offset 1 is the first byte of the second record.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [checksum matches, actual Adler-32, record index, in-record offset]. The sum of payload lengths must equal the byte count. Use a verified cryptographic signature when authenticity is required. Invalid input returns an empty vector.
Argument
Accepted input
lengths
Vector of: nonnegative exact integer
payload
Vector of: whole byte in [0,255]
offset
nonnegative exact integer
checksum
nonnegative exact integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Swallow 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-swallow/tree/v0.1.0
fn recordspan_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn recordspan_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn recordspan_compute(lengths: vector, offset: f64) -> vector {
let mut start = 0.0;
let mut i = 0;
while i < len(lengths) {
let size = at(lengths, i);
let end = start + size;
if end > 9007199254740991.0 {
return [];
}
if offset >= start && offset < end {
return [i, offset - start, size];
}
start = end;
i += 1;
}
if offset == start {
return [-1, 0, 0];
}
[]
}
// Locate the nonempty length-prefixed record containing a byte offset.
// Returns [record index, in-record offset, record length]. At end of stream the index is -1; an offset beyond the end is invalid. Lengths describe decoded payload spans.
pub fn recordspan_locate(lengths: vector, offset: f64) -> vector {
if !recordspan_counts(lengths) { return []; }
if !(offset >= 0.0 && offset <= 9007199254740991.0 && offset % 1.0 == 0.0) { return []; }
let result = recordspan_compute(lengths, offset);
if !recordspan_finite(result) { return []; }
result
}
fn adlerbytes_bytes(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 255.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn adlerbytes_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn adlerbytes_compute(bytes: vector) -> vector {
let mut a = 1.0;
let mut b = 0.0;
let mut i = 0;
while i < len(bytes) {
a = (a + at(bytes, i)) % 65521.0;
b = (b + a) % 65521.0;
i += 1;
}
[b * 65536.0 + a, a, b]
}
// Compute the RFC 1950 Adler-32 checksum over a sequence of bytes.
// Returns [unsigned checksum, rolling low accumulator, rolling high accumulator]. The empty digest is 1. Use for accidental corruption detection.
pub fn adlerbytes_digest(bytes: vector) -> vector {
if !adlerbytes_bytes(bytes) { return []; }
let result = adlerbytes_compute(bytes);
if !adlerbytes_finite(result) { return []; }
result
}
fn swallow_num(value: i64) -> f64 {
at([value], 0)
}
fn swallow_bytes(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 255.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn swallow_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn swallow_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn swallow_compute(lengths: vector, payload: vector, offset: f64, checksum: f64) -> vector {
if checksum > 4294967295.0 || sum(lengths) != swallow_num(len(payload)) {
return [];
}
let record = recordspan_locate(lengths, offset);
let digest = adlerbytes_digest(payload);
if len(record) == 0 || len(digest) == 0 {
return [];
}
let mut same = 0;
if at(digest, 0) == checksum {
same = 1;
}
[same, at(digest, 0), at(record, 0), at(record, 1)]
}
// Validate an exported payload's declared spans and checksum, then locate a byte.
// Returns [checksum matches, actual Adler-32, record index, in-record offset]. The sum of payload lengths must equal the byte count. Use a verified cryptographic signature when authenticity is required.
pub fn swallow_inspect(lengths: vector, payload: vector, offset: f64, checksum: f64) -> vector {
if !swallow_counts(lengths) { return []; }
if !swallow_bytes(payload) { return []; }
if !(offset >= 0.0 && offset <= 9007199254740991.0 && offset % 1.0 == 0.0) { return []; }
if !(checksum >= 0.0 && checksum <= 9007199254740991.0 && checksum % 1.0 == 0.0) { return []; }
let result = swallow_compute(lengths, payload, offset, checksum);
if !swallow_finite(result) { return []; }
result
}
fn main() {
let lengths = [1, 1];
let payload = [65, 66];
let offset = 1.0;
let checksum = 12976260.0;
let result = swallow_inspect(lengths, payload, offset, checksum);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
1
12976260
1
0
Practice
Change lengths = [1], payload = [0], offset = 0.0, checksum = 0.0. Predict the result, then run the program.
Hint
Returns [checksum matches, actual Adler-32, record index, in-record offset]. The sum of payload lengths must equal the byte count. Use a verified cryptographic signature when authenticity is required.
Solution
The result vector is [0, 65537, 0, 0]. Compare its fields with the return layout in the API section.
Find
let lengths = [1, 1];
Replace with
let lengths = [1];
Find
let payload = [65, 66];
Replace with
let payload = [0];
Find
let offset = 1.0;
Replace with
let offset = 0.0;
Find
let checksum = 12976260.0;
Replace with
let checksum = 0.0;
Output after the change
0
65537
0
0
Workflow recipes
Lapwing · Paginate a report with indivisible paragraphs
Preflight fixed-line document pagination with indivisible paragraphs.
Paginate a report with indivisible paragraphs
A report can fit in aggregate yet overflow when a paragraph must stay together. Pack the measured paragraphs into the usable page area. The first two paragraphs fill a ten-line page. Three lines move to the second page and leave seven available there.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [pages, lines used on final page, unused line slots, printable lines per page]. Blocks are positive paragraph line counts. The host measures text and renders the resulting pages. Invalid input returns an empty vector.
Argument
Accepted input
blocks
Vector of: nonnegative exact integer
paper
positive finite number
top
nonnegative finite number
bottom
nonnegative finite number
line
positive finite number
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Lapwing 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-lapwing/tree/v0.1.0
fn pagebreaks_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn pagebreaks_num(value: i64) -> f64 {
at([value], 0)
}
fn pagebreaks_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn pagebreaks_magnitudes(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn pagebreaks_compute(heights: vector, page: f64) -> vector {
let mut pages = 0;
let mut used = 0.0;
let mut i = 0;
while i < len(heights) {
let h = at(heights, i);
if h <= 0.0 || h > page {
return [];
}
if pages == 0 || used + h > page {
pages += 1;
used = 0.0;
}
used += h;
i += 1;
}
[pages, used, pagebreaks_max2(0.0, pagebreaks_num(pages) * page - sum(heights))]
}
// Place unsplittable document blocks on successive pages in input order.
// Returns [pages used, occupied height on final page, total unused height]. Positive block heights must fit individually. Empty input uses zero pages.
pub fn pagebreaks_pack(heights: vector, page: f64) -> vector {
if !pagebreaks_magnitudes(heights) { return []; }
if !(page > 0.0 && page - page == 0.0) { return []; }
let result = pagebreaks_compute(heights, page);
if !pagebreaks_finite(result) { return []; }
result
}
fn linefit_floorpos(value: f64) -> f64 {
value - value % 1.0
}
fn linefit_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn linefit_compute(paper: f64, top: f64, bottom: f64, line: f64) -> vector {
let area = paper - top - bottom;
if area <= 0.0 {
return [];
}
let lines = linefit_floorpos(area / line);
[area, lines, area - lines * line]
}
// Compute the usable print area and whole lines per page.
// Returns [usable height, whole-line capacity, residual height]. All dimensions use the same unit; a page with no usable height is invalid.
pub fn linefit_capacity(paper: f64, top: f64, bottom: f64, line: f64) -> vector {
if !(paper > 0.0 && paper - paper == 0.0) { return []; }
if !(top >= 0.0 && top - top == 0.0) { return []; }
if !(bottom >= 0.0 && bottom - bottom == 0.0) { return []; }
if !(line > 0.0 && line - line == 0.0) { return []; }
let result = linefit_compute(paper, top, bottom, line);
if !linefit_finite(result) { return []; }
result
}
fn lapwing_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn lapwing_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn lapwing_compute(blocks: vector, paper: f64, top: f64, bottom: f64, line: f64) -> vector {
let area = linefit_capacity(paper, top, bottom, line);
if len(area) == 0 || at(area, 1) < 1.0 {
return [];
}
let pages = pagebreaks_pack(blocks, at(area, 1));
if len(pages) == 0 {
return [];
}
[at(pages, 0), at(pages, 1), at(pages, 2), at(area, 1)]
}
// Preflight fixed-line document pagination with indivisible paragraphs.
// Returns [pages, lines used on final page, unused line slots, printable lines per page]. Blocks are positive paragraph line counts. The host measures text and renders the resulting pages.
pub fn lapwing_paginate(blocks: vector, paper: f64, top: f64, bottom: f64, line: f64) -> vector {
if !lapwing_counts(blocks) { return []; }
if !(paper > 0.0 && paper - paper == 0.0) { return []; }
if !(top >= 0.0 && top - top == 0.0) { return []; }
if !(bottom >= 0.0 && bottom - bottom == 0.0) { return []; }
if !(line > 0.0 && line - line == 0.0) { return []; }
let result = lapwing_compute(blocks, paper, top, bottom, line);
if !lapwing_finite(result) { return []; }
result
}
fn main() {
let blocks = [4, 6, 3];
let paper = 120.0;
let top = 10.0;
let bottom = 10.0;
let line = 10.0;
let result = lapwing_paginate(blocks, paper, top, bottom, line);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
2
3
7
10
Practice
Change blocks = [], paper = 40.0, top = 0.0, bottom = 0.0. Predict the result, then run the program.
Hint
Returns [pages, lines used on final page, unused line slots, printable lines per page]. Blocks are positive paragraph line counts. The host measures text and renders the resulting pages.
Solution
The result vector is [0, 0, 0, 4]. Compare its fields with the return layout in the API section.
Find
let blocks = [4, 6, 3];
Replace with
let blocks = [];
Find
let paper = 120.0;
Replace with
let paper = 40.0;
Find
let top = 10.0;
Replace with
let top = 0.0;
Find
let bottom = 10.0;
Replace with
let bottom = 0.0;
Output after the change
0
0
0
4
Workflow recipes
Hoopoe · Check a thumbnail buffer before allocation
Plan a thumbnail and check the decoded pixel buffer against a byte budget.
Check a thumbnail buffer before allocation
Encoded file size gives a poor estimate of decoded thumbnail memory. Account for output dimensions and scanline padding before allocating. A 400×200 image fits into 100×50 pixels. Three channels and four-byte alignment require 15,000 bytes, above the given budget.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [output width, output height, aligned stride, bytes, fits budget]. Includes one output buffer with one byte per channel. Decoder and encoder overhead are outside this estimate. Invalid input returns an empty vector.
Argument
Accepted input
width
positive exact integer
height
positive exact integer
box_w
positive exact integer
box_h
positive exact integer
channels
positive exact integer
align
positive exact integer
memory
nonnegative exact integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Hoopoe 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-hoopoe/tree/v0.1.0
fn aspectfit_min2(a: f64, b: f64) -> f64 {
if a < b {
return a;
}
b
}
fn aspectfit_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn aspectfit_floorpos(value: f64) -> f64 {
value - value % 1.0
}
fn aspectfit_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn aspectfit_compute(width: f64, height: f64, box_w: f64, box_h: f64, upscale: f64) -> vector {
if upscale > 1.0 {
return [];
}
let mut scale = aspectfit_min2(box_w / width, box_h / height);
if upscale == 0.0 {
scale = aspectfit_min2(scale, 1.0);
}
[aspectfit_max2(1.0, aspectfit_min2(box_w, aspectfit_floorpos(width * scale))), aspectfit_max2(1.0, aspectfit_min2(box_h, aspectfit_floorpos(height * scale))), scale]
}
// Fit an image inside a box while preserving aspect ratio.
// Returns [integer output width, height, scale]. Downward rounding and a one-pixel minimum preserve a nonempty raster. Set upscale to 0 to keep small images at native size.
pub fn aspectfit_contain(width: f64, height: f64, box_w: f64, box_h: f64, upscale: f64) -> vector {
if !(width >= 1.0 && width <= 9007199254740991.0 && width % 1.0 == 0.0) { return []; }
if !(height >= 1.0 && height <= 9007199254740991.0 && height % 1.0 == 0.0) { return []; }
if !(box_w >= 1.0 && box_w <= 9007199254740991.0 && box_w % 1.0 == 0.0) { return []; }
if !(box_h >= 1.0 && box_h <= 9007199254740991.0 && box_h % 1.0 == 0.0) { return []; }
if !(upscale >= 0.0 && upscale <= 9007199254740991.0 && upscale % 1.0 == 0.0) { return []; }
let result = aspectfit_compute(width, height, box_w, box_h, upscale);
if !aspectfit_finite(result) { return []; }
result
}
fn rasterbytes_ceilpos(value: f64) -> f64 {
let rest = value % 1.0;
if rest > 0.0 {
return value - rest + 1.0;
}
value
}
fn rasterbytes_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn rasterbytes_compute(width: f64, height: f64, channels: f64, alignment: f64) -> vector {
let raw = width * channels;
let stride = rasterbytes_ceilpos(raw / alignment) * alignment;
let bytes = stride * height;
if bytes > 9007199254740991.0 {
return [];
}
[raw, stride, bytes]
}
// Estimate uncompressed raster storage with aligned scanlines.
// Returns [bytes per unpadded row, aligned stride, total bytes]. Each channel takes one byte. Counts must stay in the exact integer range.
pub fn rasterbytes_storage(width: f64, height: f64, channels: f64, alignment: f64) -> vector {
if !(width >= 1.0 && width <= 9007199254740991.0 && width % 1.0 == 0.0) { return []; }
if !(height >= 1.0 && height <= 9007199254740991.0 && height % 1.0 == 0.0) { return []; }
if !(channels >= 1.0 && channels <= 9007199254740991.0 && channels % 1.0 == 0.0) { return []; }
if !(alignment >= 1.0 && alignment <= 9007199254740991.0 && alignment % 1.0 == 0.0) { return []; }
let result = rasterbytes_compute(width, height, channels, alignment);
if !rasterbytes_finite(result) { return []; }
result
}
fn hoopoe_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn hoopoe_compute(width: f64, height: f64, box_w: f64, box_h: f64, channels: f64, align: f64, memory: f64) -> vector {
let fit = aspectfit_contain(width, height, box_w, box_h, 0.0);
if len(fit) == 0 {
return [];
}
let cost = rasterbytes_storage(at(fit, 0), at(fit, 1), channels, align);
if len(cost) == 0 {
return [];
}
let mut ok = 0;
if at(cost, 2) <= memory {
ok = 1;
}
[at(fit, 0), at(fit, 1), at(cost, 1), at(cost, 2), ok]
}
// Plan a thumbnail and check the decoded pixel buffer against a byte budget.
// Returns [output width, output height, aligned stride, bytes, fits budget]. Includes one output buffer with one byte per channel. Decoder and encoder overhead are outside this estimate.
pub fn hoopoe_thumbnail(width: f64, height: f64, box_w: f64, box_h: f64, channels: f64, align: f64, memory: f64) -> vector {
if !(width >= 1.0 && width <= 9007199254740991.0 && width % 1.0 == 0.0) { return []; }
if !(height >= 1.0 && height <= 9007199254740991.0 && height % 1.0 == 0.0) { return []; }
if !(box_w >= 1.0 && box_w <= 9007199254740991.0 && box_w % 1.0 == 0.0) { return []; }
if !(box_h >= 1.0 && box_h <= 9007199254740991.0 && box_h % 1.0 == 0.0) { return []; }
if !(channels >= 1.0 && channels <= 9007199254740991.0 && channels % 1.0 == 0.0) { return []; }
if !(align >= 1.0 && align <= 9007199254740991.0 && align % 1.0 == 0.0) { return []; }
if !(memory >= 0.0 && memory <= 9007199254740991.0 && memory % 1.0 == 0.0) { return []; }
let result = hoopoe_compute(width, height, box_w, box_h, channels, align, memory);
if !hoopoe_finite(result) { return []; }
result
}
fn main() {
let width = 400.0;
let height = 200.0;
let box_w = 100.0;
let box_h = 100.0;
let channels = 3.0;
let align = 4.0;
let memory = 14000.0;
let result = hoopoe_thumbnail(width, height, box_w, box_h, channels, align, memory);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
100
50
300
15000
0
Practice
Change width = 3.0, height = 2.0, box_w = 10.0, box_h = 10.0, memory = 24.0. Predict the result, then run the program.
Hint
Returns [output width, output height, aligned stride, bytes, fits budget]. Includes one output buffer with one byte per channel. Decoder and encoder overhead are outside this estimate.
Solution
The result vector is [3, 2, 12, 24, 1]. Compare its fields with the return layout in the API section.
Find
let width = 400.0;
Replace with
let width = 3.0;
Find
let height = 200.0;
Replace with
let height = 2.0;
Find
let box_w = 100.0;
Replace with
let box_w = 10.0;
Find
let box_h = 100.0;
Replace with
let box_h = 10.0;
Find
let memory = 14000.0;
Replace with
let memory = 24.0;
Output after the change
3
2
12
24
1
Workflow recipes
Spoonbill · Detect overlapping captions in a rational time base
Preflight caption cue timings against an explicit overlap policy.
Detect overlapping captions in a rational time base
Two cues touching at one endpoint are consecutive; two cues occupying the same frame overlap. Apply a policy using exact tick boundaries. At 30 ticks per second the track spans two seconds. The second cue begins before the first one finishes.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [accepted, overlapping cue count, first overlap index, cue-track span in seconds]. Some subtitle tracks allow overlaps; the caller chooses the policy. Invalid input returns an empty vector.
Argument
Accepted input
starts
Vector of: nonnegative exact integer
ends
Vector of: nonnegative exact integer
numerator
positive exact integer
denominator
positive exact integer
allow_overlap
nonnegative exact integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Spoonbill 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-spoonbill/tree/v0.1.0
fn timebase_floorpos(value: f64) -> f64 {
value - value % 1.0
}
fn timebase_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn timebase_compute(tick: f64, numerator: f64, denominator: f64) -> vector {
let seconds = (tick / denominator) * numerator;
let whole = timebase_floorpos(seconds);
[seconds, whole, seconds - whole]
}
// Convert a nonnegative frame tick to seconds using a rational time base.
// Returns [seconds, whole seconds, fractional remainder]. numerator/denominator is seconds per tick.
pub fn timebase_frame(tick: f64, numerator: f64, denominator: f64) -> vector {
if !(tick >= 0.0 && tick <= 9007199254740991.0 && tick % 1.0 == 0.0) { return []; }
if !(numerator >= 1.0 && numerator <= 9007199254740991.0 && numerator % 1.0 == 0.0) { return []; }
if !(denominator >= 1.0 && denominator <= 9007199254740991.0 && denominator % 1.0 == 0.0) { return []; }
let result = timebase_compute(tick, numerator, denominator);
if !timebase_finite(result) { return []; }
result
}
fn cueoverlap_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn cueoverlap_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn cueoverlap_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn cueoverlap_compute(starts: vector, ends: vector) -> vector {
if len(starts) != len(ends) {
return [];
}
if len(starts) == 0 {
return [0, -1, 0];
}
let mut furthest = at(starts, 0);
let mut count = 0;
let mut first = -1;
let mut i = 0;
while i < len(starts) {
let a = at(starts, i);
let b = at(ends, i);
if b <= a || (i > 0 && a < at(starts, i - 1)) {
return [];
}
if a < furthest {
if first < 0 {
first = i;
}
count += 1;
}
furthest = cueoverlap_max2(furthest, b);
i += 1;
}
[count, first, furthest - at(starts, 0)]
}
// Audit a sorted list of half-open subtitle cue intervals.
// Returns [cues that start before a previous cue has ended, first overlapping cue index, total span in ticks]. Rejects nonpositive durations and unsorted starts.
pub fn cueoverlap_trace(starts: vector, ends: vector) -> vector {
if !cueoverlap_counts(starts) { return []; }
if !cueoverlap_counts(ends) { return []; }
let result = cueoverlap_compute(starts, ends);
if !cueoverlap_finite(result) { return []; }
result
}
fn spoonbill_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn spoonbill_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn spoonbill_compute(starts: vector, ends: vector, numerator: f64, denominator: f64, allow_overlap: f64) -> vector {
if allow_overlap > 1.0 {
return [];
}
let cues = cueoverlap_trace(starts, ends);
if len(cues) == 0 {
return [];
}
let duration = timebase_frame(at(cues, 2), numerator, denominator);
if len(duration) == 0 {
return [];
}
let mut ok = 0;
if allow_overlap == 1.0 || at(cues, 0) == 0.0 {
ok = 1;
}
[ok, at(cues, 0), at(cues, 1), at(duration, 0)]
}
// Preflight caption cue timings against an explicit overlap policy.
// Returns [accepted, overlapping cue count, first overlap index, cue-track span in seconds]. Some subtitle tracks allow overlaps; the caller chooses the policy.
pub fn spoonbill_captions(starts: vector, ends: vector, numerator: f64, denominator: f64, allow_overlap: f64) -> vector {
if !spoonbill_counts(starts) { return []; }
if !spoonbill_counts(ends) { return []; }
if !(numerator >= 1.0 && numerator <= 9007199254740991.0 && numerator % 1.0 == 0.0) { return []; }
if !(denominator >= 1.0 && denominator <= 9007199254740991.0 && denominator % 1.0 == 0.0) { return []; }
if !(allow_overlap >= 0.0 && allow_overlap <= 9007199254740991.0 && allow_overlap % 1.0 == 0.0) { return []; }
let result = spoonbill_compute(starts, ends, numerator, denominator, allow_overlap);
if !spoonbill_finite(result) { return []; }
result
}
fn main() {
let starts = [0, 20];
let ends = [30, 60];
let numerator = 1.0;
let denominator = 30.0;
let allow_overlap = 0.0;
let result = spoonbill_captions(starts, ends, numerator, denominator, allow_overlap);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
0
1
1
2
Practice
Change allow_overlap = 1.0. Predict the result, then run the program.
Hint
Returns [accepted, overlapping cue count, first overlap index, cue-track span in seconds]. Some subtitle tracks allow overlaps; the caller chooses the policy.
Solution
The result vector is [1, 1, 1, 2]. Compare its fields with the return layout in the API section.
Find
let allow_overlap = 0.0;
Replace with
let allow_overlap = 1.0;
Output after the change
1
1
1
2
Workflow recipes
Raven · Budget a log buffer during an error burst
Budget a bounded log buffer while preserving higher-severity events first.
Budget a log buffer during an error burst
A burst of low-severity messages can consume all available slots. Quantify how much high-severity evidence a bounded buffer would retain. Three records cross the importance threshold, but the buffer has two slots. One high-severity record must be dropped.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [important retained, ordinary retained, dropped, high-severity drops]. Use the plan to allocate slots in a host logger. Invalid input returns an empty vector.
Argument
Accepted input
severity
Vector of: nonnegative exact integer
threshold
nonnegative exact integer
capacity
nonnegative exact integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Raven 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-raven/tree/v0.1.0
fn eventlevels_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn eventlevels_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn eventlevels_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn eventlevels_compute(severity: vector, threshold: f64) -> vector {
if threshold > 24.0 {
return [];
}
let mut count = 0;
let mut first = -1;
let mut peak = -1.0;
let mut i = 0;
while i < len(severity) {
let level = at(severity, i);
if level > 24.0 {
return [];
}
peak = eventlevels_max2(peak, level);
if level >= threshold {
if first < 0 {
first = i;
}
count += 1;
}
i += 1;
}
[count, peak, first]
}
// Count log records at or above an OpenTelemetry severity number.
// Returns [qualifying records, greatest severity, first qualifying index]. Valid severity numbers are 0–24, with 0 unspecified. Empty streams use -1 for the maximum.
pub fn eventlevels_count(severity: vector, threshold: f64) -> vector {
if !eventlevels_counts(severity) { return []; }
if !(threshold >= 0.0 && threshold <= 9007199254740991.0 && threshold % 1.0 == 0.0) { return []; }
let result = eventlevels_compute(severity, threshold);
if !eventlevels_finite(result) { return []; }
result
}
fn samplequota_min2(a: f64, b: f64) -> f64 {
if a < b {
return a;
}
b
}
fn samplequota_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn samplequota_compute(important: f64, ordinary: f64, capacity: f64) -> vector {
if important + ordinary > 9007199254740991.0 {
return [];
}
let first = samplequota_min2(important, capacity);
let rest = samplequota_min2(ordinary, capacity - first);
[first, rest, important + ordinary - first - rest]
}
// Allocate a bounded log buffer with higher priority for important records.
// Returns [important retained, ordinary retained, dropped]. This computes counts for a host that selects individual records in arrival order.
pub fn samplequota_plan(important: f64, ordinary: f64, capacity: f64) -> vector {
if !(important >= 0.0 && important <= 9007199254740991.0 && important % 1.0 == 0.0) { return []; }
if !(ordinary >= 0.0 && ordinary <= 9007199254740991.0 && ordinary % 1.0 == 0.0) { return []; }
if !(capacity >= 0.0 && capacity <= 9007199254740991.0 && capacity % 1.0 == 0.0) { return []; }
let result = samplequota_compute(important, ordinary, capacity);
if !samplequota_finite(result) { return []; }
result
}
fn raven_num(value: i64) -> f64 {
at([value], 0)
}
fn raven_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn raven_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn raven_compute(severity: vector, threshold: f64, capacity: f64) -> vector {
let levels = eventlevels_count(severity, threshold);
if len(levels) == 0 {
return [];
}
let important = at(levels, 0);
let slots = samplequota_plan(important, raven_num(len(severity)) - important, capacity);
if len(slots) == 0 {
return [];
}
[at(slots, 0), at(slots, 1), at(slots, 2), important - at(slots, 0)]
}
// Budget a bounded log buffer while preserving higher-severity events first.
// Returns [important retained, ordinary retained, dropped, high-severity drops]. Use the plan to allocate slots in a host logger.
pub fn raven_buffer(severity: vector, threshold: f64, capacity: f64) -> vector {
if !raven_counts(severity) { return []; }
if !(threshold >= 0.0 && threshold <= 9007199254740991.0 && threshold % 1.0 == 0.0) { return []; }
if !(capacity >= 0.0 && capacity <= 9007199254740991.0 && capacity % 1.0 == 0.0) { return []; }
let result = raven_compute(severity, threshold, capacity);
if !raven_finite(result) { return []; }
result
}
fn main() {
let severity = [9, 17, 9, 21, 21];
let threshold = 17.0;
let capacity = 2.0;
let result = raven_buffer(severity, threshold, capacity);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
2
0
3
1
Practice
Change severity = [9, 17, 9]. Predict the result, then run the program.
Hint
Returns [important retained, ordinary retained, dropped, high-severity drops]. Use the plan to allocate slots in a host logger.
Solution
The result vector is [1, 1, 1, 0]. Compare its fields with the return layout in the API section.
Find
let severity = [9, 17, 9, 21, 21];
Replace with
let severity = [9, 17, 9];
Output after the change
1
1
1
0
Workflow recipes
Robin · Convert a civil date into comparable day numbers
Convert a validated civil date into an ordinal, weekday and comparable day number.
Convert a civil date into comparable day numbers
Month lengths and century leap rules affect both date validation and weekday calculations. Resolve both from the same Gregorian day number. January 1, 1970 has day number 719163 and Monday-zero weekday 3. Century years follow the full Gregorian leap rule.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [day number with 0001-01-01 = 1, Monday-zero weekday, day-of-year, days in month]. This is a calendar computation independent of machine locale. Invalid input returns an empty vector.
Argument
Accepted input
year
positive exact integer
month
positive exact integer
day
positive exact integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Robin 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-robin/tree/v0.1.0
fn gregorianday_num(value: i64) -> f64 {
at([value], 0)
}
fn gregorianday_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn gregorianday_compute(year: f64, month: f64, day: f64) -> vector {
if year > 9999.0 || month > 12.0 {
return [];
}
let mut leap = 0.0;
if year % 4.0 == 0.0 && (year % 100.0 != 0.0 || year % 400.0 == 0.0) {
leap = 1.0;
}
let months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
let mut i = 0;
let mut ordinal = day;
while gregorianday_num(i) + 1.0 < month {
ordinal += at(months, i);
if i == 1 {
ordinal += leap;
}
i += 1;
}
let mut limit = at(months, i);
if i == 1 {
limit += leap;
}
if day > limit {
return [];
}
[ordinal, leap, limit]
}
// Validate a proleptic Gregorian date and calculate its day-of-year.
// Returns [ordinal starting at 1, leap-year flag, days in month]. Supported years are 1–9999.
pub fn gregorianday_ordinal(year: f64, month: f64, day: f64) -> vector {
if !(year >= 1.0 && year <= 9007199254740991.0 && year % 1.0 == 0.0) { return []; }
if !(month >= 1.0 && month <= 9007199254740991.0 && month % 1.0 == 0.0) { return []; }
if !(day >= 1.0 && day <= 9007199254740991.0 && day % 1.0 == 0.0) { return []; }
let result = gregorianday_compute(year, month, day);
if !gregorianday_finite(result) { return []; }
result
}
fn yearorigin_floorpos(value: f64) -> f64 {
value - value % 1.0
}
fn yearorigin_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn yearorigin_compute(year: f64) -> vector {
if year > 9999.0 {
return [];
}
let y = year - 1.0;
let days = y * 365.0 + yearorigin_floorpos(y / 4.0) - yearorigin_floorpos(y / 100.0) + yearorigin_floorpos(y / 400.0);
[days, days % 7.0]
}
// Count Gregorian days before January 1 of a year.
// Returns [days before year, weekday of January 1]. Monday is zero; year 1 begins on Monday. Supported years are 1–9999.
pub fn yearorigin_offset(year: f64) -> vector {
if !(year >= 1.0 && year <= 9007199254740991.0 && year % 1.0 == 0.0) { return []; }
let result = yearorigin_compute(year);
if !yearorigin_finite(result) { return []; }
result
}
fn robin_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn robin_compute(year: f64, month: f64, day: f64) -> vector {
let date = gregorianday_ordinal(year, month, day);
let origin = yearorigin_offset(year);
if len(date) == 0 || len(origin) == 0 {
return [];
}
let index = at(origin, 0) + at(date, 0);
[index, (index - 1.0) % 7.0, at(date, 0), at(date, 2)]
}
// Convert a validated civil date into an ordinal, weekday and comparable day number.
// Returns [day number with 0001-01-01 = 1, Monday-zero weekday, day-of-year, days in month]. This is a calendar computation independent of machine locale.
pub fn robin_date(year: f64, month: f64, day: f64) -> vector {
if !(year >= 1.0 && year <= 9007199254740991.0 && year % 1.0 == 0.0) { return []; }
if !(month >= 1.0 && month <= 9007199254740991.0 && month % 1.0 == 0.0) { return []; }
if !(day >= 1.0 && day <= 9007199254740991.0 && day % 1.0 == 0.0) { return []; }
let result = robin_compute(year, month, day);
if !robin_finite(result) { return []; }
result
}
fn main() {
let year = 1970.0;
let month = 1.0;
let day = 1.0;
let result = robin_date(year, month, day);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
719163
3
1
31
Practice
Change year = 1.0. Predict the result, then run the program.
Hint
Returns [day number with 0001-01-01 = 1, Monday-zero weekday, day-of-year, days in month]. This is a calendar computation independent of machine locale.
Solution
The result vector is [1, 0, 1, 31]. Compare its fields with the return layout in the API section.
Find
let year = 1970.0;
Replace with
let year = 1.0;
Output after the change
1
0
1
31
Workflow recipes
Starling · Size a resource pool from overlapping bookings
Estimate resource capacity and actual occupied time from a booking schedule.
Size a resource pool from overlapping bookings
Summing all booking durations double-counts overlap. Measure occupied time separately from peak resource demand. Three bookings cover seven ticks and reach two simultaneous users. A pool of one is short by one resource.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [covered ticks, peak simultaneous bookings, earliest peak, capacity shortfall]. Starts must be sorted; adjacent bookings can share a resource. Invalid input returns an empty vector.
Argument
Accepted input
starts
Vector of: exact signed integer
ends
Vector of: exact signed integer
capacity
positive exact integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Starling 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-starling/tree/v0.1.0
fn intervalunion_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn intervalunion_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn intervalunion_integers(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= -9007199254740991.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn intervalunion_compute(starts: vector, ends: vector) -> vector {
if len(starts) != len(ends) {
return [];
}
if len(starts) == 0 {
return [0, 0, 0];
}
let mut end = at(starts, 0);
let mut length = 0.0;
let mut components = 0;
let mut i = 0;
while i < len(starts) {
let a = at(starts, i);
let b = at(ends, i);
if b <= a || (i > 0 && a < at(starts, i - 1)) {
return [];
}
if i == 0 || a > end {
components += 1;
}
length += intervalunion_max2(0.0, b - intervalunion_max2(a, end));
end = intervalunion_max2(end, b);
i += 1;
}
[length, components, end - at(starts, 0)]
}
// Measure union length and coverage components of sorted half-open intervals.
// Returns [covered ticks, connected components, enclosing span]. Touching intervals are merged. Empty input has zero span.
pub fn intervalunion_measure(starts: vector, ends: vector) -> vector {
if !intervalunion_integers(starts) { return []; }
if !intervalunion_integers(ends) { return []; }
let result = intervalunion_compute(starts, ends);
if !intervalunion_finite(result) { return []; }
result
}
fn peakslots_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn peakslots_integers(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= -9007199254740991.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn peakslots_compute(starts: vector, ends: vector) -> vector {
if len(starts) != len(ends) {
return [];
}
let mut best = 0;
let mut when = 0.0;
let mut i = 0;
while i < len(starts) {
if at(ends, i) <= at(starts, i) {
return [];
}
let t = at(starts, i);
let mut count = 0;
let mut j = 0;
while j < len(starts) {
if at(starts, j) <= t && t < at(ends, j) {
count += 1;
}
j += 1;
}
if count > best || (count == best && t < when) {
best = count;
when = t;
}
i += 1;
}
[best, when]
}
// Find peak simultaneous occupancy of half-open intervals.
// Returns [peak active intervals, earliest tick at that peak]. Empty input returns [0,0]. Counts exactly at starts, where occupancy can increase; short batches use quadratic time.
pub fn peakslots_overlap(starts: vector, ends: vector) -> vector {
if !peakslots_integers(starts) { return []; }
if !peakslots_integers(ends) { return []; }
let result = peakslots_compute(starts, ends);
if !peakslots_finite(result) { return []; }
result
}
fn starling_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn starling_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn starling_integers(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= -9007199254740991.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn starling_compute(starts: vector, ends: vector, capacity: f64) -> vector {
let union = intervalunion_measure(starts, ends);
let peak = peakslots_overlap(starts, ends);
if len(union) == 0 || len(peak) == 0 {
return [];
}
[at(union, 0), at(peak, 0), at(peak, 1), starling_max2(0.0, at(peak, 0) - capacity)]
}
// Estimate resource capacity and actual occupied time from a booking schedule.
// Returns [covered ticks, peak simultaneous bookings, earliest peak, capacity shortfall]. Starts must be sorted; adjacent bookings can share a resource.
pub fn starling_capacity(starts: vector, ends: vector, capacity: f64) -> vector {
if !starling_integers(starts) { return []; }
if !starling_integers(ends) { return []; }
if !(capacity >= 1.0 && capacity <= 9007199254740991.0 && capacity % 1.0 == 0.0) { return []; }
let result = starling_compute(starts, ends, capacity);
if !starling_finite(result) { return []; }
result
}
fn main() {
let starts = [0, 2, 4];
let ends = [4, 5, 7];
let capacity = 1.0;
let result = starling_capacity(starts, ends, capacity);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
7
2
2
1
Practice
Change starts = [1, 3], ends = [3, 5]. Predict the result, then run the program.
Hint
Returns [covered ticks, peak simultaneous bookings, earliest peak, capacity shortfall]. Starts must be sorted; adjacent bookings can share a resource.
Solution
The result vector is [4, 1, 1, 0]. Compare its fields with the return layout in the API section.
Find
let starts = [0, 2, 4];
Replace with
let starts = [1, 3];
Find
let ends = [4, 5, 7];
Replace with
let ends = [3, 5];
Output after the change
4
1
1
0
Workflow recipes
Blackbird · Resolve both occurrences of an ambiguous wall time
Resolve a wall-clock timestamp at a known gap or fold without guessing its offset.
Resolve both occurrences of an ambiguous wall time
One wall time can occur twice during a fall-back transition and disappear entirely during a forward jump. Expose the number of valid UTC candidates. After the offset moves back, local tick 11000 has two UTC candidates. Fold 1 selects the later occurrence.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [candidate count, selected UTC, selected offset]. For a gap the latter two values are zero. Fold 0 chooses the earlier occurrence and fold 1 the later. Supply transition data from a trusted timezone database. Invalid input returns an empty vector.
Argument
Accepted input
local
exact signed integer
transition
exact signed integer
before
exact signed integer
after
exact signed integer
fold
nonnegative exact integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Blackbird 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-blackbird/tree/v0.1.0
fn civiloffset_absolute(value: f64) -> f64 {
if value < 0.0 {
return - value;
}
value
}
fn civiloffset_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn civiloffset_compute(local: f64, offset: f64) -> vector {
if civiloffset_absolute(offset) >= 86400.0 {
return [];
}
let utc = local - offset;
if civiloffset_absolute(utc) > 9007199254740991.0 {
return [];
}
[utc, offset]
}
// Convert a local tick to a candidate UTC tick for a supplied offset.
// Returns [candidate UTC, offset]. Offsets use seconds and must lie strictly within ±24 hours. Local ticks use the same epoch and unit.
pub fn civiloffset_candidate(local: f64, offset: f64) -> vector {
if !(local >= -9007199254740991.0 && local <= 9007199254740991.0 && local % 1.0 == 0.0) { return []; }
if !(offset >= -9007199254740991.0 && offset <= 9007199254740991.0 && offset % 1.0 == 0.0) { return []; }
let result = civiloffset_compute(local, offset);
if !civiloffset_finite(result) { return []; }
result
}
fn clockfold_absolute(value: f64) -> f64 {
if value < 0.0 {
return - value;
}
value
}
fn clockfold_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn clockfold_compute(local: f64, transition: f64, before: f64, after: f64) -> vector {
if clockfold_absolute(before) >= 86400.0 || clockfold_absolute(after) >= 86400.0 {
return [];
}
let old = local - before;
let next = local - after;
if clockfold_absolute(old) > 9007199254740991.0 || clockfold_absolute(next) > 9007199254740991.0 {
return [];
}
let a = old < transition;
let b = next >= transition;
if a && b {
return [2, old, next];
}
if a {
return [1, old, old];
}
if b {
return [1, next, next];
}
[0, 0, 0]
}
// Classify a local time around one supplied offset transition.
// Returns [number of valid UTC candidates, earliest candidate, latest candidate]. A forward gap yields [0,0,0]; a backward fold yields two candidates.
pub fn clockfold_classify(local: f64, transition: f64, before: f64, after: f64) -> vector {
if !(local >= -9007199254740991.0 && local <= 9007199254740991.0 && local % 1.0 == 0.0) { return []; }
if !(transition >= -9007199254740991.0 && transition <= 9007199254740991.0 && transition % 1.0 == 0.0) { return []; }
if !(before >= -9007199254740991.0 && before <= 9007199254740991.0 && before % 1.0 == 0.0) { return []; }
if !(after >= -9007199254740991.0 && after <= 9007199254740991.0 && after % 1.0 == 0.0) { return []; }
let result = clockfold_compute(local, transition, before, after);
if !clockfold_finite(result) { return []; }
result
}
fn blackbird_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn blackbird_compute(local: f64, transition: f64, before: f64, after: f64, fold: f64) -> vector {
if fold > 1.0 {
return [];
}
let c = clockfold_classify(local, transition, before, after);
if len(c) == 0 {
return [];
}
if at(c, 0) == 0.0 {
return [0, 0, 0];
}
let mut utc = at(c, 1);
if fold == 1.0 {
utc = at(c, 2);
}
let offset = local - utc;
let point = civiloffset_candidate(local, offset);
if len(point) == 0 {
return [];
}
[at(c, 0), at(point, 0), at(point, 1)]
}
// Resolve a wall-clock timestamp at a known gap or fold without guessing its offset.
// Returns [candidate count, selected UTC, selected offset]. For a gap the latter two values are zero. Fold 0 chooses the earlier occurrence and fold 1 the later. Supply transition data from a trusted timezone database.
pub fn blackbird_resolve(local: f64, transition: f64, before: f64, after: f64, fold: f64) -> vector {
if !(local >= -9007199254740991.0 && local <= 9007199254740991.0 && local % 1.0 == 0.0) { return []; }
if !(transition >= -9007199254740991.0 && transition <= 9007199254740991.0 && transition % 1.0 == 0.0) { return []; }
if !(before >= -9007199254740991.0 && before <= 9007199254740991.0 && before % 1.0 == 0.0) { return []; }
if !(after >= -9007199254740991.0 && after <= 9007199254740991.0 && after % 1.0 == 0.0) { return []; }
if !(fold >= 0.0 && fold <= 9007199254740991.0 && fold % 1.0 == 0.0) { return []; }
let result = blackbird_compute(local, transition, before, after, fold);
if !blackbird_finite(result) { return []; }
result
}
fn main() {
let local = 11000.0;
let transition = 10000.0;
let before = 3600.0;
let after = 0.0;
let fold = 1.0;
let result = blackbird_resolve(local, transition, before, after, fold);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
2
11000
0
Practice
Change fold = 0.0. Predict the result, then run the program.
Hint
Returns [candidate count, selected UTC, selected offset]. For a gap the latter two values are zero. Fold 0 chooses the earlier occurrence and fold 1 the later. Supply transition data from a trusted timezone database.
Solution
The result vector is [2, 7400, 3600]. Compare its fields with the return layout in the API section.
Find
let fold = 1.0;
Replace with
let fold = 0.0;
Output after the change
2
7400
3600
Workflow recipes
Towhee · Locate the first actionable source-style violation
Combine indentation and line-width diagnostics for a measured source file.
Locate the first actionable source-style violation
A line can have acceptable length but invalid indentation. Preserve both counts and show the earliest actionable row. The second line exceeds its width limit and the third makes an illegal indentation jump. The first problem is zero-based row 1.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [clean, indentation violations, overlong rows, first problem row]. Supply aligned nonblank physical lines and their display widths. Invalid input returns an empty vector.
Argument
Accepted input
indent
Vector of: nonnegative exact integer
widths
Vector of: nonnegative exact integer
step
positive exact integer
limit
positive exact integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Towhee 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-towhee/tree/v0.1.0
fn indentsteps_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn indentsteps_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn indentsteps_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn indentsteps_compute(indent: vector, step: f64) -> vector {
let mut errors = 0;
let mut first = -1;
let mut deepest = 0.0;
let mut prev = 0.0;
let mut i = 0;
while i < len(indent) {
let col = at(indent, i);
if (i == 0 && col != 0.0) || col % step != 0.0 || col > prev + step {
if first < 0 {
first = i;
}
errors += 1;
}
deepest = indentsteps_max2(deepest, col);
prev = col;
i += 1;
}
[errors, first, deepest]
}
// Audit fixed-step indentation measured on nonblank source lines.
// Returns [off-grid or illegal jump count, first offending row, deepest column]. The first nonblank row starts at zero and one line can increase by at most one indent step.
pub fn indentsteps_audit(indent: vector, step: f64) -> vector {
if !indentsteps_counts(indent) { return []; }
if !(step >= 1.0 && step <= 9007199254740991.0 && step % 1.0 == 0.0) { return []; }
let result = indentsteps_compute(indent, step);
if !indentsteps_finite(result) { return []; }
result
}
fn linewidth_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn linewidth_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn linewidth_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn linewidth_compute(widths: vector, limit: f64) -> vector {
let mut count = 0;
let mut first = -1;
let mut excess = 0.0;
let mut i = 0;
while i < len(widths) {
let gap = at(widths, i) - limit;
if gap > 0.0 {
if first < 0 {
first = i;
}
count += 1;
excess = linewidth_max2(excess, gap);
}
i += 1;
}
[count, first, excess]
}
// Find overlong source lines from measured display columns.
// Returns [overlong rows, first overlong row, largest excess]. The host selects a Unicode display-width convention and supplies widths including indentation.
pub fn linewidth_audit(widths: vector, limit: f64) -> vector {
if !linewidth_counts(widths) { return []; }
if !(limit >= 1.0 && limit <= 9007199254740991.0 && limit % 1.0 == 0.0) { return []; }
let result = linewidth_compute(widths, limit);
if !linewidth_finite(result) { return []; }
result
}
fn towhee_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn towhee_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn towhee_compute(indent: vector, widths: vector, step: f64, limit: f64) -> vector {
if len(indent) != len(widths) {
return [];
}
let mut i = 0;
while i < len(indent) {
if at(indent, i) > at(widths, i) {
return [];
}
i += 1;
}
let levels = indentsteps_audit(indent, step);
let lines = linewidth_audit(widths, limit);
if len(levels) == 0 || len(lines) == 0 {
return [];
}
let mut first = at(levels, 1);
if first < 0.0 || (at(lines, 1) >= 0.0 && at(lines, 1) < first) {
first = at(lines, 1);
}
let mut clean = 0;
if first < 0.0 {
clean = 1;
}
[clean, at(levels, 0), at(lines, 0), first]
}
// Combine indentation and line-width diagnostics for a measured source file.
// Returns [clean, indentation violations, overlong rows, first problem row]. Supply aligned nonblank physical lines and their display widths.
pub fn towhee_lint(indent: vector, widths: vector, step: f64, limit: f64) -> vector {
if !towhee_counts(indent) { return []; }
if !towhee_counts(widths) { return []; }
if !(step >= 1.0 && step <= 9007199254740991.0 && step % 1.0 == 0.0) { return []; }
if !(limit >= 1.0 && limit <= 9007199254740991.0 && limit % 1.0 == 0.0) { return []; }
let result = towhee_compute(indent, widths, step, limit);
if !towhee_finite(result) { return []; }
result
}
fn main() {
let indent = [0, 4, 12];
let widths = [60, 88, 70];
let step = 4.0;
let limit = 80.0;
let result = towhee_lint(indent, widths, step, limit);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
0
1
1
1
Practice
Change indent = [0, 4], widths = [8, 12]. Predict the result, then run the program.
Hint
Returns [clean, indentation violations, overlong rows, first problem row]. Supply aligned nonblank physical lines and their display widths.
Solution
The result vector is [1, 0, 0, -1]. Compare its fields with the return layout in the API section.
Find
let indent = [0, 4, 12];
Replace with
let indent = [0, 4];
Find
let widths = [60, 88, 70];
Replace with
let widths = [8, 12];
Output after the change
1
0
0
-1
Workflow recipes
Bowerbird · Check a proposed dependency upgrade numerically
Decide whether a proposed numeric-core dependency upgrade fits a declared version range.
Check a proposed dependency upgrade numerically
String sorting places 1.10 before 1.2. Check numeric ordering and the consumer's upper bound separately. Version 1.10.0 follows 1.2.9 and fits the interval below 2.0.0. The first changed component is minor.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [allowed upgrade, candidate versus installed, major/minor/patch index changed, within range]. Equal versions are allowed. This release handles numeric cores and explicit bounds. Invalid input returns an empty vector.
Argument
Accepted input
installed
Vector of: nonnegative exact integer
candidate
Vector of: nonnegative exact integer
lower
Vector of: nonnegative exact integer
upper
Vector of: nonnegative exact integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Bowerbird 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-bowerbird/tree/v0.1.0
fn semvercore_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn semvercore_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn semvercore_compute(left: vector, right: vector) -> vector {
if len(left) != 3 || len(right) != 3 {
return [];
}
let mut i = 0;
while i < 3 {
if at(left, i) < at(right, i) {
return [-1, i];
}
if at(left, i) > at(right, i) {
return [1, i];
}
i += 1;
}
[0, -1]
}
// Compare two numeric semantic-version cores lexicographically.
// Both inputs are [major, minor, patch]. Returns [ordering (-1,0,1), first differing component or -1]. Prerelease identifiers and build metadata are outside this core.
pub fn semvercore_compare(left: vector, right: vector) -> vector {
if !semvercore_counts(left) { return []; }
if !semvercore_counts(right) { return []; }
let result = semvercore_compute(left, right);
if !semvercore_finite(result) { return []; }
result
}
fn versionband_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn versionband_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn versionband_compute(version: vector, lower: vector, upper: vector) -> vector {
if len(version) != 3 || len(lower) != 3 || len(upper) != 3 {
return [];
}
let mut bounds = 0;
let mut lo = 0;
let mut hi = 0;
let mut i = 0;
while i < 3 {
let v = at(version, i);
let a = at(lower, i);
let b = at(upper, i);
if bounds == 0 {
if a < b {
bounds = -1;
}
if a > b {
bounds = 1;
}
}
if lo == 0 {
if v < a {
lo = -1;
}
if v > a {
lo = 1;
}
}
if hi == 0 {
if v < b {
hi = -1;
}
if v > b {
hi = 1;
}
}
i += 1;
}
if bounds != -1 {
return [];
}
if lo < 0 {
return [0, 1, 0];
}
if hi >= 0 {
return [0, 0, 1];
}
[1, 0, 0]
}
// Check membership of a numeric-version core in a half-open dependency interval.
// Returns [inside, below lower, at or above upper]. All versions have three integer components and lower must precede upper.
pub fn versionband_contains(version: vector, lower: vector, upper: vector) -> vector {
if !versionband_counts(version) { return []; }
if !versionband_counts(lower) { return []; }
if !versionband_counts(upper) { return []; }
let result = versionband_compute(version, lower, upper);
if !versionband_finite(result) { return []; }
result
}
fn bowerbird_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn bowerbird_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn bowerbird_compute(installed: vector, candidate: vector, lower: vector, upper: vector) -> vector {
let diff = semvercore_compare(candidate, installed);
let allowed = versionband_contains(candidate, lower, upper);
if len(diff) == 0 || len(allowed) == 0 {
return [];
}
let mut ok = 0;
if at(diff, 0) >= 0.0 && at(allowed, 0) == 1.0 {
ok = 1;
}
[ok, at(diff, 0), at(diff, 1), at(allowed, 0)]
}
// Decide whether a proposed numeric-core dependency upgrade fits a declared version range.
// Returns [allowed upgrade, candidate versus installed, major/minor/patch index changed, within range]. Equal versions are allowed. This release handles numeric cores and explicit bounds.
pub fn bowerbird_upgrade(installed: vector, candidate: vector, lower: vector, upper: vector) -> vector {
if !bowerbird_counts(installed) { return []; }
if !bowerbird_counts(candidate) { return []; }
if !bowerbird_counts(lower) { return []; }
if !bowerbird_counts(upper) { return []; }
let result = bowerbird_compute(installed, candidate, lower, upper);
if !bowerbird_finite(result) { return []; }
result
}
fn main() {
let installed = [1, 2, 9];
let candidate = [1, 10, 0];
let lower = [1, 0, 0];
let upper = [2, 0, 0];
let result = bowerbird_upgrade(installed, candidate, lower, upper);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
1
1
1
1
Practice
Change candidate = [1, 1, 0]. Predict the result, then run the program.
Hint
Returns [allowed upgrade, candidate versus installed, major/minor/patch index changed, within range]. Equal versions are allowed. This release handles numeric cores and explicit bounds.
Solution
The result vector is [0, -1, 1, 1]. Compare its fields with the return layout in the API section.
Find
let candidate = [1, 10, 0];
Replace with
let candidate = [1, 1, 0];
Output after the change
0
-1
1
1
Workflow recipes
Albatross · Estimate a build's critical-path lower bound
Estimate a build forest's scheduling lower bound from dependencies and worker capacity.
Estimate a build's critical-path lower bound
Adding workers cannot shorten a serial dependency chain. Compare total work with the longest dependency path before sizing a build pool. The four stages take eleven units of serial work. A dependency chain takes eight, so two workers cannot finish sooner than eight.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [critical path, total work, lower bound with given workers, deepest stage count]. The capacity bound assumes divisible worker time; actual nonpreemptive schedules can take longer. Invalid input returns an empty vector.
Argument
Accepted input
parents
Vector of: exact signed integer
durations
Vector of: nonnegative finite number
workers
positive exact integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Albatross 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-albatross/tree/v0.1.0
fn dagorder_num(value: i64) -> f64 {
at([value], 0)
}
fn dagorder_slot(key: f64, size: i64) -> i64 {
let mut lo = 0;
let mut hi = size;
while lo < hi {
let mid = lo + (hi - lo) / 2;
if at([mid], 0) < key {
lo = mid + 1;
} else {
hi = mid;
}
}
lo
}
fn dagorder_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn dagorder_integers(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= -9007199254740991.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn dagorder_compute(parents: vector) -> vector {
let mut roots = 0;
let mut deepest = 0;
let mut leaf = -1;
let mut i = 0;
while i < len(parents) {
let parent = at(parents, i);
if parent < -1.0 || parent >= dagorder_num(i) {
return [];
}
if parent == -1.0 {
roots += 1;
}
let mut steps = 1;
let mut next = parent;
while next >= 0.0 {
let idx = dagorder_slot(next, i);
next = at(parents, idx);
steps += 1;
}
if steps > deepest {
deepest = steps;
leaf = i;
}
i += 1;
}
[roots, deepest, leaf]
}
// Validate indexed dependencies in an ordered build forest.
// Each stage names one earlier parent or -1 for a root. Returns [root count, maximum chain length in stages, first stage with that depth]. Empty forests have zero depth.
pub fn dagorder_forest(parents: vector) -> vector {
if !dagorder_integers(parents) { return []; }
let result = dagorder_compute(parents);
if !dagorder_finite(result) { return []; }
result
}
fn runduration_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn runduration_num(value: i64) -> f64 {
at([value], 0)
}
fn runduration_slot(key: f64, size: i64) -> i64 {
let mut lo = 0;
let mut hi = size;
while lo < hi {
let mid = lo + (hi - lo) / 2;
if at([mid], 0) < key {
lo = mid + 1;
} else {
hi = mid;
}
}
lo
}
fn runduration_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn runduration_integers(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= -9007199254740991.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn runduration_magnitudes(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn runduration_compute(parents: vector, durations: vector) -> vector {
if len(parents) != len(durations) {
return [];
}
let mut best = -1.0;
let mut leaf = -1;
let mut i = 0;
while i < len(parents) {
let nextparent = at(parents, i);
if nextparent < -1.0 || nextparent >= runduration_num(i) {
return [];
}
let mut cost = at(durations, i);
let mut next = nextparent;
while next >= 0.0 {
let idx = runduration_slot(next, i);
cost += at(durations, idx);
next = at(parents, idx);
}
if cost > best {
best = cost;
leaf = i;
}
i += 1;
}
[runduration_max2(best, 0.0), leaf, sum(durations)]
}
// Find the critical-path time in a forest of dependent tasks.
// Returns [longest path duration, first endpoint at that duration, total sequential work]. Each input row depends on one previous row or -1. Durations share a unit.
pub fn runduration_path(parents: vector, durations: vector) -> vector {
if !runduration_integers(parents) { return []; }
if !runduration_magnitudes(durations) { return []; }
let result = runduration_compute(parents, durations);
if !runduration_finite(result) { return []; }
result
}
fn albatross_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn albatross_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn albatross_integers(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= -9007199254740991.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn albatross_magnitudes(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn albatross_compute(parents: vector, durations: vector, workers: f64) -> vector {
let shape = dagorder_forest(parents);
let timing = runduration_path(parents, durations);
if len(shape) == 0 || len(timing) == 0 {
return [];
}
[at(timing, 0), at(timing, 2), albatross_max2(at(timing, 0), at(timing, 2) / workers), at(shape, 1)]
}
// Estimate a build forest's scheduling lower bound from dependencies and worker capacity.
// Returns [critical path, total work, lower bound with given workers, deepest stage count]. The capacity bound assumes divisible worker time; actual nonpreemptive schedules can take longer.
pub fn albatross_schedule(parents: vector, durations: vector, workers: f64) -> vector {
if !albatross_integers(parents) { return []; }
if !albatross_magnitudes(durations) { return []; }
if !(workers >= 1.0 && workers <= 9007199254740991.0 && workers % 1.0 == 0.0) { return []; }
let result = albatross_compute(parents, durations, workers);
if !albatross_finite(result) { return []; }
result
}
fn main() {
let parents = [-1, 0, 0, 2];
let durations = [1, 3, 2, 5];
let workers = 2.0;
let result = albatross_schedule(parents, durations, workers);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
8
11
8
3
Practice
Change parents = [-1, -1, -1], durations = [5, 5, 5], workers = 1.0. Predict the result, then run the program.
Hint
Returns [critical path, total work, lower bound with given workers, deepest stage count]. The capacity bound assumes divisible worker time; actual nonpreemptive schedules can take longer.
Solution
The result vector is [5, 15, 15, 1]. Compare its fields with the return layout in the API section.
Find
let parents = [-1, 0, 0, 2];
Replace with
let parents = [-1, -1, -1];
Find
let durations = [1, 3, 2, 5];
Replace with
let durations = [5, 5, 5];
Find
let workers = 2.0;
Replace with
let workers = 1.0;
Output after the change
5
15
15
1
Workflow recipes
Chaffinch · Reconcile two sorted snapshots with repeated keys
Reconcile sorted collection snapshots without materializing their union.
Reconcile two sorted snapshots with repeated keys
A duplicate row should not look like a newly added key. Compare distinct sets and report repeated occurrences separately. The new snapshot adds key 3, removes key 1 and retains 2 and 4. The repeated 2 contributes one duplicate occurrence.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [added unique keys, removed unique keys, retained keys, duplicate occurrences in the new snapshot]. Inputs are sorted, allowing forward-only scans. Invalid input returns an empty vector.
Argument
Accepted input
old
Vector of: exact signed integer
fresh
Vector of: exact signed integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Chaffinch 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-chaffinch/tree/v0.1.0
fn sortruns_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn sortruns_integers(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= -9007199254740991.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn sortruns_compute(values: vector) -> vector {
if len(values) == 0 {
return [0, 0, 0];
}
let mut kinds = 0;
let mut run = 0;
let mut best = 0;
let mut key = at(values, 0);
let mut i = 0;
while i < len(values) {
let current = at(values, i);
if i > 0 && current < at(values, i - 1) {
return [];
}
if i == 0 || current != at(values, i - 1) {
kinds += 1;
run = 0;
}
run += 1;
if run > best {
best = run;
key = current;
}
i += 1;
}
[kinds, best, key]
}
// Summarize equal-value runs in a nondecreasing integer stream.
// Returns [distinct values, longest run length, first key with that run]. Empty input returns [0,0,0]. Rejects descending keys.
pub fn sortruns_profile(values: vector) -> vector {
if !sortruns_integers(values) { return []; }
let result = sortruns_compute(values);
if !sortruns_finite(result) { return []; }
result
}
fn mergecounts_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn mergecounts_integers(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= -9007199254740991.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn mergecounts_compute(left: vector, right: vector) -> vector {
let mut k = 1;
while k < len(left) {
if at(left, k) < at(left, k - 1) {
return [];
}
k += 1;
}
k = 1;
while k < len(right) {
if at(right, k) < at(right, k - 1) {
return [];
}
k += 1;
}
let mut a = 0;
let mut b = 0;
let mut shared = 0;
let mut only_a = 0;
let mut only_b = 0;
while a < len(left) || b < len(right) {
let mut key = 0.0;
if b == len(right) || (a < len(left) && at(left, a) < at(right, b)) {
key = at(left, a);
only_a += 1;
} else {
if a == len(left) || at(right, b) < at(left, a) {
key = at(right, b);
only_b += 1;
} else {
key = at(left, a);
shared += 1;
}
}
while a < len(left) && at(left, a) == key {
a += 1;
}
while b < len(right) && at(right, b) == key {
b += 1;
}
}
[shared, only_a, only_b]
}
// Count unique keys shared or exclusive to two sorted streams.
// Returns [shared, left-only, right-only]. Repeats within a stream count once. Both streams must be nondecreasing; the merge uses two forward cursors.
pub fn mergecounts_sets(left: vector, right: vector) -> vector {
if !mergecounts_integers(left) { return []; }
if !mergecounts_integers(right) { return []; }
let result = mergecounts_compute(left, right);
if !mergecounts_finite(result) { return []; }
result
}
fn chaffinch_num(value: i64) -> f64 {
at([value], 0)
}
fn chaffinch_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn chaffinch_integers(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= -9007199254740991.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn chaffinch_compute(old: vector, fresh: vector) -> vector {
let previous = sortruns_profile(old);
let current = sortruns_profile(fresh);
let merged = mergecounts_sets(old, fresh);
if len(previous) == 0 || len(current) == 0 || len(merged) == 0 {
return [];
}
[at(merged, 2), at(merged, 1), at(merged, 0), chaffinch_num(len(fresh)) - at(current, 0)]
}
// Reconcile sorted collection snapshots without materializing their union.
// Returns [added unique keys, removed unique keys, retained keys, duplicate occurrences in the new snapshot]. Inputs are sorted, allowing forward-only scans.
pub fn chaffinch_reconcile(old: vector, fresh: vector) -> vector {
if !chaffinch_integers(old) { return []; }
if !chaffinch_integers(fresh) { return []; }
let result = chaffinch_compute(old, fresh);
if !chaffinch_finite(result) { return []; }
result
}
fn main() {
let old = [1, 1, 2, 4];
let fresh = [2, 2, 3, 4];
let result = chaffinch_reconcile(old, fresh);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
1
1
2
1
Practice
Change old = [], fresh = [9, 9]. Predict the result, then run the program.
Hint
Returns [added unique keys, removed unique keys, retained keys, duplicate occurrences in the new snapshot]. Inputs are sorted, allowing forward-only scans.
Solution
The result vector is [1, 0, 0, 1]. Compare its fields with the return layout in the API section.
Find
let old = [1, 1, 2, 4];
Replace with
let old = [];
Find
let fresh = [2, 2, 3, 4];
Replace with
let fresh = [9, 9];
Output after the change
1
0
0
1
Workflow recipes
Pelican · Compare merged reads with aligned per-request reads
Compare per-request aligned I/O with coalesced unaligned reads for a sorted trace.
Compare merged reads with aligned per-request reads
Merging requests saves seeks but can read unused gap bytes. Report each cost explicitly before changing a storage access pattern. The example's two merged ranges fetch ten bytes including a one-byte gap. Independent eight-byte-aligned reads would fetch 24.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [independent aligned bytes, coalesced read count, coalesced bytes, bridge-gap bytes]. Values describe two explicitly defined read strategies. Invalid input returns an empty vector.
Argument
Accepted input
starts
Vector of: nonnegative exact integer
lengths
Vector of: positive exact integer
gap
nonnegative exact integer
block
positive exact integer
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Pelican 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-pelican/tree/v0.1.0
fn blockspan_ceilpos(value: f64) -> f64 {
let rest = value % 1.0;
if rest > 0.0 {
return value - rest + 1.0;
}
value
}
fn blockspan_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn blockspan_compute(offset: f64, length: f64, block: f64) -> vector {
if length == 0.0 {
return [offset, 0, 0];
}
let stop = offset + length;
if stop > 9007199254740991.0 {
return [];
}
let first = offset - offset % block;
let tail = blockspan_ceilpos(stop / block) * block;
if tail > 9007199254740991.0 {
return [];
}
[first, tail - first, offset - first]
}
// Expand a byte request to whole storage blocks.
// Returns [aligned start, bytes to read, requested start within read]. A zero-length request incurs zero reads. Counts must remain exactly representable.
pub fn blockspan_align(offset: f64, length: f64, block: f64) -> vector {
if !(offset >= 0.0 && offset <= 9007199254740991.0 && offset % 1.0 == 0.0) { return []; }
if !(length >= 0.0 && length <= 9007199254740991.0 && length % 1.0 == 0.0) { return []; }
if !(block >= 1.0 && block <= 9007199254740991.0 && block % 1.0 == 0.0) { return []; }
let result = blockspan_compute(offset, length, block);
if !blockspan_finite(result) { return []; }
result
}
fn coalesceio_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn coalesceio_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn coalesceio_positive_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 1.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn coalesceio_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn coalesceio_compute(starts: vector, lengths: vector, gap: f64) -> vector {
if len(starts) != len(lengths) {
return [];
}
let mut end = 0.0;
let mut fetched = 0.0;
let mut extra = 0.0;
let mut reads = 0;
let mut i = 0;
while i < len(starts) {
let a = at(starts, i);
let b = a + at(lengths, i);
if b > 9007199254740991.0 || (i > 0 && a < at(starts, i - 1)) {
return [];
}
if i == 0 || a - end > gap {
reads += 1;
fetched += b - a;
end = b;
} else {
extra += coalesceio_max2(0.0, a - end);
fetched += coalesceio_max2(0.0, b - end);
end = coalesceio_max2(end, b);
}
i += 1;
}
[reads, fetched, extra]
}
// Count merged reads and extra gap bytes for sorted byte requests.
// Returns [merged reads, fetched bytes, extra bytes spanning gaps]. Overlapping bytes are counted once. Positive request lengths are required.
pub fn coalesceio_plan(starts: vector, lengths: vector, gap: f64) -> vector {
if !coalesceio_counts(starts) { return []; }
if !coalesceio_positive_counts(lengths) { return []; }
if !(gap >= 0.0 && gap <= 9007199254740991.0 && gap % 1.0 == 0.0) { return []; }
let result = coalesceio_compute(starts, lengths, gap);
if !coalesceio_finite(result) { return []; }
result
}
fn pelican_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn pelican_positive_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 1.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn pelican_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn pelican_compute(starts: vector, lengths: vector, gap: f64, block: f64) -> vector {
let merged = coalesceio_plan(starts, lengths, gap);
if len(merged) == 0 {
return [];
}
let mut total = 0.0;
let mut i = 0;
while i < len(starts) {
let span = blockspan_align(at(starts, i), at(lengths, i), block);
if len(span) == 0 {
return [];
}
total += at(span, 1);
if total > 9007199254740991.0 {
return [];
}
i += 1;
}
[total, at(merged, 0), at(merged, 1), at(merged, 2)]
}
// Compare per-request aligned I/O with coalesced unaligned reads for a sorted trace.
// Returns [independent aligned bytes, coalesced read count, coalesced bytes, bridge-gap bytes]. Values describe two explicitly defined read strategies.
pub fn pelican_reads(starts: vector, lengths: vector, gap: f64, block: f64) -> vector {
if !pelican_counts(starts) { return []; }
if !pelican_positive_counts(lengths) { return []; }
if !(gap >= 0.0 && gap <= 9007199254740991.0 && gap % 1.0 == 0.0) { return []; }
if !(block >= 1.0 && block <= 9007199254740991.0 && block % 1.0 == 0.0) { return []; }
let result = pelican_compute(starts, lengths, gap, block);
if !pelican_finite(result) { return []; }
result
}
fn main() {
let starts = [0, 5, 20];
let lengths = [4, 3, 2];
let gap = 1.0;
let block = 8.0;
let result = pelican_reads(starts, lengths, gap, block);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
24
2
10
1
Practice
Change starts = [], lengths = [], gap = 0.0, block = 4.0. Predict the result, then run the program.
Hint
Returns [independent aligned bytes, coalesced read count, coalesced bytes, bridge-gap bytes]. Values describe two explicitly defined read strategies.
Solution
The result vector is [0, 0, 0, 0]. Compare its fields with the return layout in the API section.
Find
let starts = [0, 5, 20];
Replace with
let starts = [];
Find
let lengths = [4, 3, 2];
Replace with
let lengths = [];
Find
let gap = 1.0;
Replace with
let gap = 0.0;
Find
let block = 8.0;
Replace with
let block = 4.0;
Output after the change
0
0
0
0
Workflow recipes
Nightingale · Bound a percentile from histogram counts
Bound a percentile from histogram counts without inventing a within-bin value.
Bound a percentile from histogram counts
Histogram counts identify the bucket containing a percentile, not its exact location. Return the interval before deciding whether a threshold was breached. The median is the fourth observation and lies in the 10–30 bucket. A threshold of 20 lies inside that bucket, so the classification stays unresolved.
Install Blyx 0.2.1 and a Rust toolchain with a host linker, then run the versioned project. Each positional argument is a number or a comma-separated numerical vector. The CLI accepts up to 16 entries per vector. The imported module accepts longer inputs.
Returns [lower bound, upper bound, rank, classification]. Classification is -1 when the whole interval is below threshold, 1 when entirely at or above, and 0 when the bins cannot decide. The upper-bound comparison is deliberately conservative. Invalid input returns an empty vector.
Argument
Accepted input
counts
Vector of: nonnegative exact integer
edges
Vector of: finite number
probability
probability in [0,1]
threshold
finite number
Use the libraries independently
The framework vendors the same library source published in these two repositories. Each module has its own package page, input contract and regression suite.
// Nightingale 0.1.0 · MIT OR Apache-2.0
// https://github.com/Rahulchaube1/blyx-nightingale/tree/v0.1.0
fn histquantile_max2(a: f64, b: f64) -> f64 {
if a > b {
return a;
}
b
}
fn histquantile_ceilpos(value: f64) -> f64 {
let rest = value % 1.0;
if rest > 0.0 {
return value - rest + 1.0;
}
value
}
fn histquantile_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn histquantile_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn histquantile_compute(counts: vector, probability: f64) -> vector {
let total = sum(counts);
if total <= 0.0 || total > 9007199254740991.0 {
return [];
}
let rank = histquantile_max2(1.0, histquantile_ceilpos(total * probability));
let mut seen = 0.0;
let mut i = 0;
while i < len(counts) {
seen += at(counts, i);
if seen >= rank {
return [i, rank, total];
}
i += 1;
}
[]
}
// Locate a nearest-rank quantile in noncumulative histogram counts.
// Returns [bucket index, one-based rank, total observations]. At probability zero select the first occupied bucket. Empty histograms are invalid.
pub fn histquantile_bucket(counts: vector, probability: f64) -> vector {
if !histquantile_counts(counts) { return []; }
if !(probability >= 0.0 && probability <= 1.0) { return []; }
let result = histquantile_compute(counts, probability);
if !histquantile_finite(result) { return []; }
result
}
fn rankband_num(value: i64) -> f64 {
at([value], 0)
}
fn rankband_slot(key: f64, size: i64) -> i64 {
let mut lo = 0;
let mut hi = size;
while lo < hi {
let mid = lo + (hi - lo) / 2;
if at([mid], 0) < key {
lo = mid + 1;
} else {
hi = mid;
}
}
lo
}
fn rankband_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn rankband_compute(edges: vector, index: f64) -> vector {
if len(edges) < 2 || index >= rankband_num(len(edges) - 1) {
return [];
}
let mut i = 1;
while i < len(edges) {
if at(edges, i) <= at(edges, i - 1) {
return [];
}
i += 1;
}
let j = rankband_slot(index, len(edges));
let a = at(edges, j);
let b = at(edges, j + 1);
[a, b, b - a]
}
// Look up the finite interval represented by a histogram bin.
// Edges must be strictly increasing. Returns [lower edge, upper edge, span]. Bins are half-open except the last, which may include its upper edge.
pub fn rankband_interval(edges: vector, index: f64) -> vector {
if !rankband_finite(edges) { return []; }
if !(index >= 0.0 && index <= 9007199254740991.0 && index % 1.0 == 0.0) { return []; }
let result = rankband_compute(edges, index);
if !rankband_finite(result) { return []; }
result
}
fn nightingale_finite(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value - value == 0.0) {
return false;
}
i += 1;
}
true
}
fn nightingale_counts(values: vector) -> bool {
let mut i = 0;
while i < len(values) {
let value = at(values, i);
if !(value >= 0.0 && value <= 9007199254740991.0 && value % 1.0 == 0.0) {
return false;
}
i += 1;
}
true
}
fn nightingale_compute(counts: vector, edges: vector, probability: f64, threshold: f64) -> vector {
if len(edges) != len(counts) + 1 {
return [];
}
let rank = histquantile_bucket(counts, probability);
if len(rank) == 0 {
return [];
}
let band = rankband_interval(edges, at(rank, 0));
if len(band) == 0 {
return [];
}
let mut decision = 0;
if at(band, 1) < threshold {
decision = -1;
}
if at(band, 0) >= threshold {
decision = 1;
}
[at(band, 0), at(band, 1), at(rank, 1), decision]
}
// Bound a percentile from histogram counts without inventing a within-bin value.
// Returns [lower bound, upper bound, rank, classification]. Classification is -1 when the whole interval is below threshold, 1 when entirely at or above, and 0 when the bins cannot decide. The upper-bound comparison is deliberately conservative.
pub fn nightingale_quantile(counts: vector, edges: vector, probability: f64, threshold: f64) -> vector {
if !nightingale_counts(counts) { return []; }
if !nightingale_finite(edges) { return []; }
if !(probability >= 0.0 && probability <= 1.0) { return []; }
if !(threshold - threshold == 0.0) { return []; }
let result = nightingale_compute(counts, edges, probability, threshold);
if !nightingale_finite(result) { return []; }
result
}
fn main() {
let counts = [2, 6];
let edges = [0, 10, 30];
let probability = 0.5;
let threshold = 20.0;
let result = nightingale_quantile(counts, edges, probability, threshold);
if len(result) == 0 { println!("invalid"); return; }
let mut i = 0;
while i < len(result) {
println!(at(result, i));
i += 1;
}
}
Expected output
10
30
4
0
Practice
Change probability = 0.25. Predict the result, then run the program.
Hint
Returns [lower bound, upper bound, rank, classification]. Classification is -1 when the whole interval is below threshold, 1 when entirely at or above, and 0 when the bins cannot decide. The upper-bound comparison is deliberately conservative.
Solution
The result vector is [0, 10, 2, -1]. Compare its fields with the return layout in the API section.
Find
let probability = 0.5;
Replace with
let probability = 0.25;
Output after the change
0
10
2
-1
Local toolchain
Install and verify Blyx
Choose a binary or package manager, locate the executable, and verify the exact compiler version.
Choose how to run the course
Every tutorial with an editor can run in the browser. A local installation lets you save source files and invoke the command-line tool blyxc. Building a native executable also requires rustc and a host linker on the machine doing the build.
Download a release archive
Choose the Windows x86-64 ZIP, Linux x86-64 tarball, or Apple Silicon macOS tarball from the download page. Compare its SHA-256 digest with the entry for the same filename in SHA256SUMS. Extract the archive and add the directory containing blyxc to PATH. In PowerShell you can run .\blyxc.exe directly from the extracted directory.
Install with Homebrew
On Apple Silicon macOS or x86-64 Linux, the project tap installs the published compiler binary and checks the archive checksum.
brew install rahulchaube1/blyx/blyx
Install on Windows with Scoop
On Windows x64, add the project bucket once from PowerShell, then install the compiler and check its version. Scoop checks the release archive against the SHA-256 in the manifest. You can also install the native AI commands with scoop install blyx/linearfit blyx/residualwatch blyx/modelgate.
With Rust, Cargo and a host linker installed, build the compiler from crates.io. The version flag selects the same release as this course. Cargo normally places the result in the bin directory under your Cargo home.
cargo install --locked --version 0.2.1 blyxc
Check your installation
Open a fresh terminal after a PATH change. The version command should print blyxc 0.2.1. If the shell cannot find it, check the directory from which the executable runs directly and make sure that directory appears on PATH.
blyxc --version
Practice
Confirm which compiler your terminal will use if you have both a downloaded binary and a Cargo installation.
Hint
Use Get-Command blyxc in PowerShell or command -v blyxc in a POSIX shell.
Solution
The path should point to the installation you intended. Run that path with --version to verify it before continuing.
Local toolchain
Create a project on disk
Move a program from the browser into a project, check the file and run it from a terminal.
Create a workspace
Choose a parent directory where you want to keep your work. This command creates a fresh directory named hello. Blyx refuses to create the project if that directory already exists, which helps protect existing work.
blyxc new hello
Find the entry point
The generated project contains Blyx.toml and src/main.blyx. The manifest records the project name, version and edition. The released CLI takes an explicit source file. Open hello/src/main.blyx in a text editor and find fn main().
Check, run and edit
From the same parent directory, run these commands in order. check parses the source. run executes it. The starter prints Hello, Blyx! Replace its print call with a calculation, save the file and run it again.
blyxc check hello/src/main.blyx
blyxc run hello/src/main.blyx
Keep paths consistent
If you change directory into hello, write src/main.blyx in subsequent commands. A file-not-found message is often a working-directory issue. The formatter rewrites the named file with normalized line endings.
blyxc fmt hello/src/main.blyx
Add a package to a native project
Clone a tagged Blyx library beside your entry file and import its public functions with use. The native runner and native build follow these local paths. The “Evaluate models with Blyx packages” chapter builds a working example. A Git submodule or a recorded commit keeps the dependency reproducible.
Practice
Make the starter print 21. Run a syntax check first and then execute the saved file.
Hint
In main, multiply 3 by 7 inside println!.
Solution
Use println!(3 * 7); and save. A successful check reports that the file parsed. The run command prints 21.
Local toolchain
Develop in VS Code
Run an unsaved editor buffer, read a parser diagnostic and move the same program to the CLI.
Open a Blyx file
Install the desktop extension with ID RahulChaube.blyx-language. Open or create a file ending in .blyx. For an untitled buffer, select Blyx as its language. The editor highlighting helps you see strings, keywords and comments.
Run the active buffer
Use the play button in the editor title bar or choose Blyx: Run File in the Command Palette. The Blyx output channel shows the output for the current text, including unsaved edits. Paste the first tutorial program and change the string to confirm which version is running.
Read a diagnostic
Remove the closing brace of main and look in the Problems panel. A parser diagnostic reports where parsing ran into trouble. Restore the brace, wait for the parser to update and run again. Runtime failures, such as a zero integer divisor, appear when the program executes.
Use a local extension file
For an offline installation, download blyx-language-1.2.3.vsix from the editor release and choose Install from VSIX in the Extensions view. The extension uses a bundled WebAssembly interpreter. Save the source to disk before running a CLI command against that file.
Practice
Change a string without saving. Compare an editor run with a terminal run before and after saving.
Hint
The editor reads the buffer. The terminal reads the file on disk.
Solution
Before saving, the editor can print the new string while the CLI prints the old one. Save and run both again to compare the same source.
Local toolchain
Debug and recover from errors
Locate a syntax error, diagnose a runtime failure, and guard an operation using short-circuit evaluation.
Identify the failing stage
Check the file path first. A syntax error occurs while reading the program structure. A runtime error occurs while executing a valid expression with particular values. An error from a native build can point to a type mismatch or a missing Rust toolchain.
Observation
Likely cause
First action
A parser line and column
Missing punctuation or an unfinished expression
Inspect that token and the preceding statement.
index … out of bounds
The index fell outside the vector
Check 0 <= i and i < len(v) before at.
dot requires vectors of equal length
The inputs contain different numbers of observations
Compare both lengths.
step limit exceeded
The budget ran out
Trace the loop condition and its updates.
Reproduce the smallest failure
Save fn main() { println!(1 / 0); } as divide.blyx. A syntax check succeeds because the expression is well formed. Running it reports an integer division error and exits with code 4. Replace the zero with 2 and rerun. Whole-number division now prints 0.
Put a guard before division
The example reads count != 0 && total / count > 3. With a zero count the first comparison is false, so evaluation skips the division. Reversing the operands would evaluate the division before discovering the zero.
Limit a test run
A runaway loop can repeatedly evaluate valid code. Use a small positive budget while investigating it. The released interpreter also enforces a separate call-depth limit. Increasing the budget only helps after you have confirmed that the computation progresses.
Make the second call use a nonzero count whose integer quotient is exactly three.
Hint
Keep total at 12 and choose a count that divides it evenly.
Solution
The quotient 12 / 4 is 3. The strict > 3 comparison returns false, and the zero-count case also returns false.
Find
above_limit(12, 2)
Replace with
above_limit(12, 4)
Output after the change
false
false
Local toolchain
Build a native executable
Compile a typed Blyx program and compare the executable with the interpreter on the same input.
Start with a known result
Run the project source through the interpreter and keep a small expected output. When trying a native build for the first time, use the generated hello project or the capstone. Both have simple results that you can check by eye.
Build for your host
Install a Rust compiler and host linker. From inside your Blyx project, run the command below. The native backend translates supported Blyx syntax to Rust and invokes rustc to produce an optimized executable for the build machine.
blyxc build src/main.blyx
Choose the output location
An explicit output name makes scripts easier to read. On Linux or macOS, run the executable using a relative path. Use a separate output path from the source file.
blyxc build src/main.blyx -o hello
./hello
Build on Windows
In PowerShell, use an .exe suffix and the current-directory prefix. The resulting executable runs independently of blyxc and rustc on a compatible machine.
Give numeric operands matching types and add explicit return types to functions that return values. The interpreter can promote mixed integer/float operations that a native build rejects. Check the executable's output using the same ordinary and boundary inputs you used for the interpreted run.
Build a program with imports
Native builds resolve local use paths and built-in host modules. The native runner builds the program and runs it in one step. Put program arguments after --. Use a normal build to keep an executable for repeated runs.
blyxc native-run src/main.blyx
Practice
Build the capstone source as a native executable, run it and compare the complete output with the chapter’s expected output.
Hint
Save the complete capstone program to src/main.blyx first.
Solution
The four readings sum to 123.5, two exceed 30, and the empty call prints no readings. Those three lines should agree across both execution paths.
Language reference
Syntax, types and operators
Look up the executable forms, operator order and value types used in Blyx 0.2.1.
Read the shape of a program
A runnable source file declares top-level functions, including a parameterless main. A function body is a brace-delimited block of statements and an optional final expression. A semicolon ends a let declaration, return statement or expression statement. A final expression without one supplies the block’s value.
Read names, literals and comments
Choose a name such as sensor_count. Start with a letter or underscore and use letters, digits or underscores after it. Names are case-sensitive. The lexer reads 10, 0b1010, 0o12 and 0xA as the same integer. Use underscores to group long numbers and e for a decimal exponent. A line comment begins with //. A block comment begins with /* and ends with */. Block comments may nest.
Value types
Use explicit scalar types for native function parameters and results. Vector elements are numeric. A unit-valued block completes without returning a useful value.
Type
Example
Use
i64
-12, 0, 42
Checked integer arithmetic, counts and indices
f64
2.5, 1e-2
Measurements, division with fractions and vector elements
bool
true, false
Conditions and logical combinations
str
"Blyx"
Text, labels and messages. The native subset also recognizes String.
vector
[2.0, 3.0]
An immutable sequence of numeric elements
unit (or omit the return annotation)
fn show() { println!(1); }
A function called for its effect
Operator order
The rows are ordered from tightest binding to loosest among the operators used by the released interpreter here. Parentheses override the default order. Keep comparisons separate and join their boolean results with && or ||.
Operators
Meaning
Example
! and unary -
Boolean negation and numeric negation
!ready, -x
* / %
Multiply, divide, remainder
7 / 2 yields 3
+ -
Add, subtract
2 + 3 * 4 yields 14
< <= > >=
Order comparisons
t >= 30.0
== !=
Equality and inequality
count != 0
&&
Short-circuit logical AND
ready && valid
||
Short-circuit logical OR
low || high
= += -= *= /= %=
Assign to a mutable binding
count += 1
Declarations and control flow
let binds, let mut permits updates and fn introduces a function. if selects a branch, while checks before each pass, and loop repeats unconditionally. break leaves the nearest loop, continue begins its next iteration, and return exits the current function. Nested braces introduce a scope.
Literal and boundary behavior
The signed integer range is −9,223,372,036,854,775,808 through 9,223,372,036,854,775,807. Integer overflow and division by zero fail in the interpreter. f64 has finite precision and follows IEEE floating-point arithmetic. Many decimal fractions have only approximate binary representations. For native examples, use decimal literals consistently when a fractional result matters.
Text and escape sequences
Write strings in double quotes. Inside a string, \n starts a new line, \t inserts a tab, \" inserts a quote, and \\ inserts a backslash. Strings may contain Unicode text. Use several print! calls to combine text with values. The interpreter also reads a single-quoted character as one character of text. Use double-quoted text in code you plan to build natively.
Use a branch as a value
The classify function below uses if and else to produce a result. Both branch blocks end in string expressions and have the same result type. show returns unit and exists to print the result. The explicit -> unit annotation may be omitted there. Function parameters and any native return values use the types in the table above.
Worked program
fn classify(n: i64) -> str {
if n % 2 == 0 { "even" } else { "odd" }
}
fn show() -> unit {
/* The three literals represent the same count. */
println!(0b1010 == 0xA && 0o12 == 10);
println!(1_000 + 5);
println!(2.5e1);
print!("label\t");
println!(classify(10));
}
fn main() {
show();
}
Expected output
true
1005
25
label even
Practice
Change the classifier call to use the integer eleven in hexadecimal. Predict the final line and check whether the other lines change.
Hint
In hexadecimal, the digits after 9 are A, B, C, D, E and F. Eleven divided by two leaves a remainder of one.
Solution
0xB is eleven. classify chooses the odd branch, and the earlier calculations still use the original literals.
Find
classify(10)
Replace with
classify(0xB)
Output after the change
true
1005
25
label odd
Language reference
Built-in functions and output
Look up every vector built-in and both output macros, including their inputs, results and boundary cases.
Vector operations
All four functions receive vectors by value in Blyx source. The interpreter shares immutable element storage across calls. An index is an i64; an element, sum or dot product is an f64.
Call
Result
Example
len(vector)
i64 count, zero for an empty vector
len([4.0, 9.0]) → 2
at(vector, i64)
The element at a zero-based index
at([4.0, 9.0], 1) → 9
sum(vector)
Sum of the elements
sum([4.0, 9.0]) → 13
dot(vector, vector)
Sum of products at matching indices
dot([1.0, 2.0], [4.0, 9.0]) → 22
Preconditions
at fails on a negative index, on index len(v), and on any access to an empty vector. dot fails if lengths differ, even when one side is empty. The sum of an empty vector and the dot product of two empty vectors are numerically zero. Check lengths before indexing or computing an average.
Output macros
print!() emits no text. println!() emits a newline. With a single expression, print!(value) displays its value, and println!(value) follows it with a newline. Use consecutive calls to combine text and numbers. Braces inside an output string are literal characters.
Cost of the operations
Reading the length or one element requires no scan. sum and dot visit the elements and their work grows with vector length. The interpreter charges its execution budget for these reductions. Holding the sum in a binding avoids recomputing it in every loop iteration.
Practice
Calculate dot([2.0, -1.0], [3.0, 4.0]) by hand. What happens if you remove the 4.0 from the second vector?
Hint
Multiply the corresponding entries before summing.
Solution
2 × 3 + (−1 × 4) is 2. After removing an entry the lengths differ, and the runtime reports an error.
Language reference
Command-line reference
Look up CLI forms, output files, execution budgets and exit codes.
Command forms
Pass the entry file to each command. Native builds and native-run also load its local imports. Quote any path containing spaces as required by your shell.
Command
Effect
blyxc --version or -V
Print the installed compiler version.
blyxc help, --help or -h
Show the available commands.
blyxc new NAME
Create a new directory with Blyx.toml and src/main.blyx.
blyxc check FILE
Parse the file and report syntax diagnostics.
blyxc run FILE [--max-steps N]
Interpret main with an optional positive step budget.
blyxc build FILE [-o PATH]
Build a native executable, optionally at PATH.
blyxc native-run FILE [-- ARGS...]
Build the native project, run it and forward the program arguments.
blyxc fmt FILE
Rewrite the file with normalized line endings.
Interpret the exit status
Capture the exit status immediately following the command. In PowerShell read $LASTEXITCODE. In a POSIX shell read $?. Scripts can use the status to decide whether to proceed. The exit codes below describe blyxc itself.
Code
Meaning
0
Command completed successfully.
1
Examples include a missing file, parser error or failed build.
2
Examples include an unknown command, a missing argument or an invalid run budget.
4
The interpreter reached a runtime failure, such as integer division by zero.
Find the output file
With no -o option a native build puts the executable beside the source, using the platform executable extension. Pass an explicit output name when a project has several programs or when a script needs to invoke a known path.
Separate execution budgets
--max-steps controls a CLI interpreter run. The browser and the VS Code worker also enforce source, output and time limits. A native executable has ordinary process and system limits. These modes can differ for a very long or deeply recursive computation.
Practice
Choose the commands for a script that first checks the syntax of main.blyx, then runs it with a budget of 500 steps.
Hint
Check the exit status before starting the second command.
Solution
Use blyxc check main.blyx, followed on success by blyxc run main.blyx --max-steps 500. A parser success does not guarantee that execution will finish within the budget.
Language reference
What Blyx 0.2.1 can run
Choose an execution mode and identify features that are still being developed.
Choose an execution mode
Use the CLI interpreter or browser for immediate feedback. Use a native build to distribute a supported typed program to a compatible host. The editor and playground run the interpreter compiled to WebAssembly.
Mode
Inputs and requirements
Limits to account for
Browser or desktop extension
A complete source buffer with fn main()
256 KiB source, 64 KiB output and an eight-second worker deadline.
CLI interpreter
A .blyx file and the blyxc executable
Default one million evaluation steps and at most 64 simultaneous calls.
Native build
A supported typed program, rustc and a host linker
The generated program runs with system resources; interpreter step and call budgets do not apply.
Supported execution
The teaching examples use functions, local bindings, scalar arithmetic, loops, recursion, numeric vectors and print macros. Native programs can import local .blyx modules and read command-line arguments or UTF-8 files through the host library. Use native-run or build for multi-file applications.
Features under development
The package registry and its dependency resolver are prototypes. The published source libraries use versioned Git checkouts. The browser and CLI interpreter execute a single source buffer. GPU kernels, a general tensor runtime, asynchronous tasks and actor scheduling remain development work.
Interpret a benchmark
Measure the same workload, input size and output across the implementations you compare. Separate startup costs from computational work when they answer different questions. The project’s published Fibonacci benchmark includes startup and reports its machine, raw samples and methodology.
Practice
Decide how to deliver a small numeric utility to a colleague who has no compiler installed. What do you need on each machine?
Hint
Distinguish the machine doing the build from the machine running the result.
Solution
On a suitable build host use blyxc, rustc and a linker to build the typed source. Deliver the executable for your colleague’s compatible OS and architecture. Try a small known input on the destination machine.