WHEN Language Quick Reference

Language Fundamentals

Program Structure

# Variable declarations
counter = 0
items = ["a", "b", "c"]

# Function definitions
def process_item(item):
    return item.upper()

# Block definitions
de worker(10):
    # Executes exactly 10 times
    print(f"Working: {worker.current_iteration}")

fo background():
    # Runs forever until stopped
    print("Background task")
    sleep(1)

os utility():
    # Runs once when called
    print("One-shot execution")

# Required main block
main:
    # Program entry point
    worker.start()
    background.start()
    utility()

    when worker.status == "COMPLETED":
        exit()

Data Types

# Numbers
integer = 42
decimal = 3.14

# Strings
text = "Hello"
fstring = f"Value: {integer}"

# Booleans
flag = True
condition = False

# Collections
list_data = [1, 2, 3]
tuple_data = (1, 2, 3)
dict_data = {"key": "value"}
set_data = {1, 2, 3}

# None
empty = None

Control Flow

Conditional Execution

when condition:
    # Execute when true

when not condition:
    # Execute when false

when x > 10 and y < 5:
    # Multiple conditions

when item in collection:
    # Membership testing

Ternary Operator

result = value_if_true when condition else value_if_false
status = "pass" when score >= 70 else "fail"

Block Types Quick Reference

Type Syntax Execution Use Case
Main main: Continuous loop Program orchestration
Forever fo name(): Until stopped Background tasks
Declarative de name(N): Exactly N times Fixed iterations
One-shot os name(): Once when called Utility functions
Parallel FO parallel fo name(): Forever in thread CPU-intensive work
Parallel DE parallel de name(N): N times in thread Batch processing

Block Control Operations

# Starting blocks
block_name.start()

# Stopping blocks
block_name.stop()

# State management
block_name.save()           # Save current state
block_name.savestop()       # Save and stop
block_name.startsave()      # Start from saved state
block_name.discard()        # Remove saved state

# Block properties
block_name.current_iteration    # Current iteration count
block_name.status              # "RUNNING", "STOPPED", "COMPLETED"
block_name.iterations          # Total iterations (DE blocks)
block_name.has_saved_state     # Boolean

Essential Patterns

Recursive Processing with OS Blocks

items = ["a", "b", "c", "d"]
index = 0

os process_all():
    when index < len(items):
        print(f"Processing: {items[index]}")
        index = index + 1
        process_all()  # Recursive call

main:
    process_all()

Dynamic Iteration with DE Blocks

data = [1, 2, 3, 4, 5]
data_count = len(data)

de process_data(data_count):
    item = data[process_data.current_iteration]
    print(f"Item {process_data.current_iteration}: {item}")

main:
    process_data.start()

Producer-Consumer Pattern

queue = []
producer_done = False

parallel fo producer():
    queue.append("item")
    sleep(1)
    when len(queue) >= 10:
        producer_done = True
        break

parallel fo consumer():
    when len(queue) > 0:
        item = queue.pop(0)
        print(f"Consumed: {item}")

    when producer_done and len(queue) == 0:
        break

Checkpoint System

progress = 0

de long_task(100):
    progress = progress + 1

    # Save every 10 steps
    when progress % 10 == 0:
        long_task.save()

    # Handle errors
    when error_occurred:
        long_task.savestop()
        fix_error()
        long_task.startsave()

Built-in Functions Reference

I/O

  • print(*values) - Output to console
  • input(prompt) - Read user input
  • open(file, mode) - Open file

Type Conversion

  • int(value) - Convert to integer
  • float(value) - Convert to float
  • str(value) - Convert to string
  • bool(value) - Convert to boolean

Collections

  • len(collection) - Get length
  • list(iterable) - Create list
  • tuple(iterable) - Create tuple
  • dict(pairs) - Create dictionary
  • set(iterable) - Create set

Math

  • abs(x) - Absolute value
  • min(iterable) - Minimum value
  • max(iterable) - Maximum value
  • sum(iterable) - Sum values
  • round(x, digits) - Round number

Utilities

  • range(start, stop, step) - Number sequence
  • enumerate(iterable) - Index-value pairs
  • zip(*iterables) - Combine iterables
  • sorted(iterable) - Sort collection
  • reversed(sequence) - Reverse sequence

WHEN-Specific

  • sleep(seconds) - Pause execution
  • exit() - Terminate program
  • safe_call(func, *args) - Safe function call

Error Handling Patterns

Conditional Error Handling

result = risky_operation()

when result["success"]:
    data = result["data"]
    process_data(data)

when not result["success"]:
    error = result["error"]
    print(f"Error: {error}")
    handle_error()

Safe Operations

result = safe_call(potentially_failing_function, arg1, arg2)

when is_success(result):
    value = get_result(result)
    print(f"Success: {value}")

when not is_success(result):
    error = get_error(result)
    print(f"Failed: {error}")

Module System

Importing

# Python modules
import os
import math
from datetime import datetime

# WHEN modules
import my_module
from game_engine import Player, create_sprite

# Usage
my_module.my_function()
my_module.my_block.start()

Common Idioms

List Processing

# Process each item
items = ["a", "b", "c"]
item_count = len(items)

de process_each(item_count):
    item = items[process_each.current_iteration]
    result = process_item(item)
    print(f"Processed: {item} -> {result}")

State Machines

state = "idle"

fo state_machine():
    when state == "idle":
        when trigger_condition:
            state = "active"

    when state == "active":
        do_work()
        when work_complete:
            state = "done"

    when state == "done":
        cleanup()
        state = "idle"

Event Loops

events = []
running = True

fo event_processor():
    when running and len(events) > 0:
        event = events.pop(0)
        handle_event(event)

fo event_generator():
    when running:
        new_event = check_for_events()
        when new_event:
            events.append(new_event)
        sleep(0.01)

Performance Tips

  1. Use appropriate block types:
    • DE blocks for known iteration counts
    • OS blocks for recursive operations
    • Parallel blocks for CPU-intensive work
  2. Avoid tight loops:
    fo busy_wait():
        when condition:
            break
        sleep(0.01)  # Add small delay
  3. Batch operations:
    de batch_processor(total_items):
        # Process multiple items per iteration
        start_idx = batch_processor.current_iteration * batch_size
        end_idx = min(start_idx + batch_size, total_items)
        process_batch(items[start_idx:end_idx])
  4. Use parallel blocks for independence:
    parallel de cpu_work(num_tasks):
        # CPU-intensive work in separate thread
        result = expensive_calculation(cpu_work.current_iteration)
        results.append(result)

Debugging

Debug Output

debug = True

when debug:
    print(f"[DEBUG] Variable state: {variable}")
    print(f"[DEBUG] Block status: {block.status}")

Block Monitoring

fo debug_monitor():
    print(f"Active blocks: {len(running_blocks)}")
    print(f"Memory usage: {get_memory_info()}")
    sleep(5)

Error Logging

error_log = []

when error_occurred:
    error_log.append({
        "time": datetime.now(),
        "error": error_message,
        "context": current_state
    })

This quick reference covers the most commonly used features and patterns in WHEN programming. For detailed explanations and more examples, refer to the full documentation sections.