Examples
The best way to internalize Varphi's syntax and semantics is by reading and writing code. This section presents three fundamental programs that progress from simple state machines to multi-tape algorithms.
Binary Incrementer (Single Tape)
This machine takes a binary number (e.g., 1011) on the tape and adds 1 to it (resulting in 1100).
Logic
Scan Right: We start at the beginning (left) of the number. We must traverse to the far right end to find the Least Significant Bit (LSB).
Scan Left (Carry): Once we hit a
BLANKat the end, we move one step left and enter the "carry" state.If we see a
1, change it to0and keep moving left (carry over).If we see a
0, change it to1and stop (carry consumed).If we see a
BLANK(overflow), write1and stop.
Code
// Step 1: Move to the far right of the string
// If we see 0 or 1, keep moving RIGHT.
start (0) start (0) (RIGHT)
start (1) start (1) (RIGHT)
// When we hit a BLANK, we've passed the number.
// Move LEFT back onto the last digit and switch to 'carry' mode.
start (BLANK) carry (BLANK) (LEFT)
// Step 2: Perform the addition
// Case A: Found a '1'. Flip to '0' and keep carrying left.
carry (1) carry (0) (LEFT)
// Case B: Found a '0'. Flip to '1'. No more carry needed. Halt.
carry (0) halt (1) (STAY)
// Case C: Found a BLANK. This means we overflowed (e.g. 11 + 1 = 100).
// Write the final '1' and Halt.
carry (BLANK) halt (1) (STAY)Equality Tester (Multi-Tape)
This program compares two strings on two separate tapes to see if they are identical. It demonstrates the power of Varphi's variable support. We define a specific rule for "match" and a generic rule for "mismatch," relying on the compiler to pick the right one.
Logic
Match: If Tape 1 has
$xand Tape 2 has$x(the same symbol), move both heads right.Mismatch: If Tape 1 has
$xand Tape 2 has$y(implicitly different), the strings are not equal. Reject.End: If both tapes hit
BLANKat the same time, the strings were equal. Accept.
Code
Palindrome Detector (Multi-Tape)
This machine determines if a string is a palindrome (reads the same forwards and backwards). We use a two-tape approach: copy the input to the second tape, then compare them in opposite directions to make sure the string reads the same in reverse order.
Logic
Copy: Copy the input from Tape 1 to Tape 2. Both heads end up at the far right.
Rewind Head 1: Move the head on Tape 1 back to the start of the string. Keep the head on Tape 2 at the end of the string.
Converge: Move Head 1
RIGHT(forward) and Head 2LEFT(backward). If the symbols match at every step, it is a palindrome.
Code
Last updated
Was this helpful?

