message = "Hello, WHEN World!"
main:
print(message)
exit()
counter = 0
de count_to_ten(10):
counter = counter + 1
print(f"Count: {counter}")
sleep(0.5)
main:
when counter == 0:
count_to_ten.start()
when counter >= 10:
print("Counting complete!")
exit()
name = ""
age = 0
greeting_done = False
main:
when name == "":
name = input("What's your name? ")
when name != "" and age == 0:
age_input = input("How old are you? ")
age = int(age_input)
when name != "" and age > 0 and not greeting_done:
print(f"Hello {name}, you are {age} years old!")
greeting_done = True
when greeting_done:
exit()
temperature = 0
weather = ""
main:
temperature = 25
weather = "sunny"
when temperature > 30:
print("It's hot today!")
when temperature <= 30 and temperature > 20:
print("Nice weather!")
when temperature <= 20:
print("A bit cool today")
when weather == "sunny":
print("Great day for outdoor activities!")
exit()
state = "idle"
task_progress = 0
fo state_machine():
when state == "idle":
print("System idle, waiting for task...")
when task_progress == 0:
state = "starting"
when state == "starting":
print("Starting task...")
task_progress = 1
state = "working"
when state == "working":
task_progress = task_progress + 1
print(f"Working... {task_progress}/10")
when task_progress >= 10:
state = "complete"
when state == "complete":
print("Task completed!")
state = "idle"
task_progress = 0
break
sleep(1)
main:
state_machine.start()
items = ["apple", "banana", "cherry", "date", "elderberry"]
current_index = 0
processed_count = 0
os process_item():
when current_index < len(items):
item = items[current_index]
print(f"Processing: {item}")
current_index = current_index + 1
processed_count = processed_count + 1
# Recursive call for next item
process_item()
main:
print("Processing items using recursive OS block:")
process_item()
print(f"Processed {processed_count} items total")
exit()
data = [10, 20, 30]
data_size = len(data)
results = []
de process_data(data_size):
item = data[process_data.current_iteration]
result = item * 2
results.append(result)
print(f"Processed: {item} -> {result}")
main:
when len(results) == 0:
print("Processing initial data...")
process_data.start()
when len(results) == data_size and len(data) == 3:
# Add more data dynamically
data.extend([40, 50])
data_size = len(data)
print("Added more data, processing...")
process_data.start()
when len(results) == data_size:
print(f"All done! Results: {results}")
exit()
import os
filename = "data.txt"
lines = []
current_line = 0
processing_done = False
def read_file_safely(filename):
when os.path.exists(filename):
with open(filename, 'r') as f:
return f.readlines()
return []
de process_line(len(lines)):
when len(lines) > 0:
line = lines[process_line.current_iteration].strip()
print(f"Line {process_line.current_iteration + 1}: {line}")
when process_line.current_iteration + 1 == len(lines):
processing_done = True
main:
when len(lines) == 0:
lines = read_file_safely(filename)
when len(lines) > 0:
print(f"Found {len(lines)} lines to process")
process_line.start()
when len(lines) == 0:
print("No file found or file is empty")
processing_done = True
when processing_done:
print("File processing complete")
exit()
import random
# Game state
player_health = 100
enemy_health = 50
game_over = False
turn = "player"
fo game_loop():
when not game_over:
when turn == "player":
damage = random.randint(10, 20)
enemy_health = enemy_health - damage
print(f"Player attacks for {damage} damage! Enemy health: {enemy_health}")
turn = "enemy"
when turn == "enemy" and enemy_health > 0:
damage = random.randint(5, 15)
player_health = player_health - damage
print(f"Enemy attacks for {damage} damage! Player health: {player_health}")
turn = "player"
when player_health <= 0:
print("Game Over! Player defeated!")
game_over = True
when enemy_health <= 0:
print("Victory! Enemy defeated!")
game_over = True
sleep(1)
when game_over:
break
main:
print("=== Simple Combat Game ===")
game_loop.start()
when game_over:
print("Thanks for playing!")
exit()
frame = 0
animation_chars = ["|", "/", "-", "\\"]
animation_running = True
fo spinner():
char_index = frame % len(animation_chars)
char = animation_chars[char_index]
print(f"\rLoading {char}", end="")
frame = frame + 1
when frame >= 20:
animation_running = False
break
sleep(0.1)
main:
spinner.start()
when not animation_running:
print("\nLoading complete!")
exit()
import math
results = []
workers_done = 0
total_workers = 3
def fibonacci(n):
when n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
parallel fo worker_1():
result = fibonacci(30)
results.append(f"Worker 1: fib(30) = {result}")
workers_done = workers_done + 1
parallel fo worker_2():
result = math.factorial(15)
results.append(f"Worker 2: 15! = {result}")
workers_done = workers_done + 1
parallel fo worker_3():
total = sum(range(1000000))
results.append(f"Worker 3: sum(0..999999) = {total}")
workers_done = workers_done + 1
main:
when workers_done == 0:
print("Starting parallel computation...")
worker_1.start()
worker_2.start()
worker_3.start()
when workers_done == total_workers:
print("All workers complete!")
for result in results:
print(result)
exit()
# Show progress
when workers_done > 0 and workers_done < total_workers:
print(f"Progress: {workers_done}/{total_workers} workers done")
sleep(1)
import random
buffer = []
max_buffer_size = 5
items_produced = 0
items_consumed = 0
production_complete = False
parallel fo producer():
when items_produced < 20 and len(buffer) < max_buffer_size:
item = f"item_{items_produced}"
buffer.append(item)
items_produced = items_produced + 1
print(f"Produced: {item} (buffer size: {len(buffer)})")
sleep(random.uniform(0.1, 0.3))
when items_produced >= 20:
production_complete = True
print("Production complete!")
break
parallel fo consumer():
when len(buffer) > 0:
item = buffer.pop(0)
items_consumed = items_consumed + 1
print(f"Consumed: {item} (total consumed: {items_consumed})")
sleep(random.uniform(0.2, 0.4))
when production_complete and len(buffer) == 0:
print("All items consumed!")
break
main:
when items_produced == 0:
print("Starting producer-consumer demo...")
producer.start()
consumer.start()
when production_complete and len(buffer) == 0:
print(f"Demo complete! Produced: {items_produced}, Consumed: {items_consumed}")
exit()
import os
filename = "data.txt"
backup_filename = "backup.txt"
operation_success = False
error_message = ""
def safe_file_operation(filename):
when os.path.exists(filename):
when os.path.isfile(filename):
try:
with open(filename, 'r') as f:
content = f.read()
return {"success": True, "data": content, "error": None}
except Exception as e:
return {"success": False, "data": None, "error": str(e)}
return {"success": False, "data": None, "error": "Path is not a file"}
return {"success": False, "data": None, "error": "File does not exist"}
main:
# Try primary file
result = safe_file_operation(filename)
when result["success"]:
print(f"Successfully read {filename}")
print(f"Content: {result['data'][:100]}...") # First 100 chars
operation_success = True
when not result["success"]:
error_message = result["error"]
print(f"Failed to read {filename}: {error_message}")
# Try backup file
backup_result = safe_file_operation(backup_filename)
when backup_result["success"]:
print(f"Successfully read backup file")
operation_success = True
when not backup_result["success"]:
print(f"Backup file also failed: {backup_result['error']}")
print("All file operations failed")
when operation_success:
print("File operation completed successfully")
exit()
progress = 0
checkpoint_interval = 5
error_simulation = False
de long_task(20):
progress = progress + 1
print(f"Working... step {progress}/20")
# Create checkpoint every 5 steps
when progress % checkpoint_interval == 0:
print(f"*** CHECKPOINT at step {progress} ***")
long_task.save()
# Simulate error at step 12
when progress == 12:
error_simulation = True
print("*** ERROR OCCURRED! ***")
long_task.savestop() # Save and stop
# Simulate recovery
print("*** RECOVERING FROM CHECKPOINT ***")
error_simulation = False
long_task.startsave() # Resume from last save
# Task completion
when progress >= 20:
print("*** TASK COMPLETED ***")
long_task.discard() # Clean up save state
sleep(0.5)
main:
when progress == 0:
print("Starting long task with checkpoint system...")
long_task.start()
when progress >= 20:
print("All work completed successfully!")
exit()
debug_enabled = True
operation_count = 0
error_count = 0
fo debug_monitor():
when debug_enabled:
print(f"[DEBUG] Operations: {operation_count}, Errors: {error_count}")
print(f"[DEBUG] Memory usage: {get_memory_usage()}")
sleep(2)
fo main_operation():
operation_count = operation_count + 1
# Simulate occasional errors
when operation_count % 7 == 0:
error_count = error_count + 1
print(f"[ERROR] Simulated error in operation {operation_count}")
when operation_count % 7 != 0:
print(f"[INFO] Operation {operation_count} completed successfully")
sleep(1)
when operation_count >= 20:
break
def get_memory_usage():
# Placeholder for actual memory monitoring
return f"{operation_count * 1.5:.1f}MB"
main:
when debug_enabled:
debug_monitor.start()
main_operation.start()
when operation_count >= 20:
print("Operations complete")
debug_monitor.stop()
exit()
These examples demonstrate the core patterns and capabilities of WHEN language programming:
when
statementsEach example can be run independently and modified to explore different aspects of the language.