Execution Gallery
12 battle-tested examples covering everything from basics to advanced patterns. Copy, adapt, and execute.
Your first Keikaku program - simple output and variables.
1# Hello World in Keikaku2declare("Hello, World!")34# Variables5name := "Keikaku"6version := 1.078declare("Welcome to", name, "v" + text(version))Classic interview problem solved with Keikaku control flow.
1# FizzBuzz - the programming classic2cycle from 1 to 101 as n:3 foresee n % 15 == 0:4 declare("FizzBuzz")5 alternate n % 3 == 0:6 declare("Fizz")7 alternate n % 5 == 0:8 declare("Buzz")9 otherwise:10 declare(n)Recursive and iterative implementations with memoization.
1# Recursive Fibonacci2protocol fib_recursive(n):3 foresee n <= 1:4 yield n5 otherwise:6 yield fib_recursive(n - 1) + fib_recursive(n - 2)78# Iterator-based Fibonacci (more efficient)9sequence fibonacci():10 a := 011 b := 112 cycle while true:13 yield a14 temp := a + b15 a = b16 b = temp1718# Get first 15 Fibonacci numbers19gen := fibonacci()20cycle from 0 to 15 as _:21 declare(proceed(gen))Sieve of Eratosthenes implemented as a lazy generator.
1# Prime number generator using sieve approach2sequence primes():3 yield 24 5 candidates := [3]6 7 cycle while true:8 n := candidates[0]9 is_prime := true10 11 cycle through candidates as p:12 foresee n % p == 0:13 is_prime = false14 terminate15 16 foresee is_prime:17 push(candidates, n)18 yield n19 20 # Move to next odd number21 candidates[0] = candidates[0] + 22223# Generate first 20 primes24gen := primes()25cycle from 0 to 20 as _:26 declare(proceed(gen))Launch multiple async tasks and collect their results.
1# Simulate async API calls2async protocol fetch_user(id):3 declare("Fetching user", id, "...")4 sleep(200)5 yield {"id": id, "name": "User " + text(id)}67async protocol fetch_posts(user_id):8 declare("Fetching posts for", user_id, "...")9 sleep(150)10 yield [11 {"title": "Post 1"},12 {"title": "Post 2"}13 ]1415# Run concurrent fetches16async protocol load_profile(id):17 user_gen := fetch_user(id)18 posts_gen := fetch_posts(id)19 20 user := proceed(user_gen)21 posts := proceed(posts_gen)22 23 user["posts"] := posts24 yield user2526gen := load_profile(42)27profile := proceed(gen)28declare("Profile:", profile)Process large datasets efficiently with chained generators.
1# Simulated large dataset2data := span(10000)34# Build lazy transformation pipeline5# Each stage only processes values on-demand6stage1 := (x * 2 for x through data)7stage2 := (x + 10 for x through stage1)8filtered := (x for x through stage2 where x % 100 == 0)910# Only compute what we need11count := 012cycle through filtered as val:13 declare("Value:", val)14 count = count + 115 foresee count >= 10:16 declare("Stopping after 10 results")17 terminateRequest handling pattern with routing and middleware.
1# Request handler protocol2protocol handle_request(method, path, body):3 declare("[" + method + "]", path)4 5 # Routing6 foresee path == "/" and method == "GET":7 yield {"status": 200, "body": "Welcome!"}8 9 alternate path == "/api/users" and method == "GET":10 users := [{"id": 1}, {"id": 2}]11 yield {"status": 200, "body": users}12 13 alternate path == "/api/users" and method == "POST":14 # Validate body15 foresee body == nil:16 yield {"status": 400, "body": "Body required"}17 otherwise:18 yield {"status": 201, "body": "Created"}19 20 otherwise:21 yield {"status": 404, "body": "Not Found"}2223# Test requests24declare(handle_request("GET", "/", nil))25declare(handle_request("GET", "/api/users", nil))26declare(handle_request("POST", "/api/users", {"name": "Test"}))27declare(handle_request("GET", "/unknown", nil))Traffic light controller using generators for state management.
1# State machine as a generator2sequence traffic_light():3 states := ["🔴 RED", "🟢 GREEN", "🟡 YELLOW"]4 durations := [3000, 4000, 1000] # ms5 index := 06 7 cycle while true:8 current_state := states[index]9 current_duration := durations[index]10 11 yield {12 "state": current_state,13 "duration": current_duration14 }15 16 sleep(current_duration)17 index = (index + 1) % 31819# Simulate traffic light20light := traffic_light()21cycle from 0 to 6 as _:22 status := proceed(light)23 declare("Light:", status["state"])Bidirectional generator for interactive communication.
1# Echo bot using bidirectional communication2sequence chat_bot():3 declare("Bot: Hello! Send me messages.")4 5 cycle while true:6 message := receive()7 8 foresee message == "quit":9 yield "Bot: Goodbye!"10 terminate11 12 alternate message == "help":13 yield "Bot: Commands - 'quit', 'time', 'joke'"14 15 alternate message == "time":16 yield "Bot: Current timestamp: " + text(timestamp())17 18 alternate message == "joke":19 yield "Bot: Why do programmers prefer dark mode? Light attracts bugs! 🐛"20 21 otherwise:22 yield "Bot: You said: " + text(message)2324bot := chat_bot()25declare(proceed(bot)) # Hello message26declare(transmit(bot, "hello there")) # Echo27declare(transmit(bot, "help")) # Help28declare(transmit(bot, "joke")) # Joke29declare(transmit(bot, "quit")) # GoodbyeRead and validate configuration files with error handling.
1# Config loader with validation2protocol load_config(filepath):3 attempt:4 content := decipher(filepath)5 config := decode_json(content)6 7 # Validate required fields8 required := ["host", "port", "database"]9 cycle through required as field:10 foresee config[field] == nil:11 yield {"error": "Missing field: " + field}12 13 # Validate types14 foresee classify(config["port"]) != "int":15 yield {"error": "Port must be integer"}16 17 declare("Config loaded successfully")18 yield config19 20 recover as error:21 declare("Failed to load config:", error)22 yield {"error": text(error)}2324# Usage25config := load_config("config.json")26foresee config["error"]:27 declare("Error:", config["error"])28otherwise:29 declare("Host:", config["host"])30 declare("Port:", config["port"])Token bucket algorithm for API rate limiting.
1# Token bucket rate limiter2sequence rate_limiter(rate, max_tokens):3 tokens := max_tokens4 last_time := timestamp()5 6 cycle while true:7 request := receive()8 now := timestamp()9 10 # Refill tokens based on time passed11 elapsed := now - last_time12 refill := elapsed * rate13 tokens = min(max_tokens, tokens + refill)14 last_time = now15 16 foresee tokens >= 1:17 tokens = tokens - 118 yield {"allowed": true, "remaining": tokens}19 otherwise:20 yield {"allowed": false, "retry_after": (1 - tokens) / rate}2122# Test: 2 requests per second, max 5 burst23limiter := rate_limiter(2, 5)24proceed(limiter)2526cycle from 0 to 10 as i:27 result := transmit(limiter, "request")28 foresee result["allowed"]:29 declare("Request", i, "allowed. Remaining:", result["remaining"])30 otherwise:31 declare("Request", i, "denied. Retry after:", result["retry_after"])32 sleep(300)Interactive calculator with expression evaluation.
1# Simple interactive calculator2protocol calculate():3 declare("Mini Calculator (type 'exit' to quit)")4 declare("Supported: +, -, *, /, ^")5 6 cycle while true:7 input := inquire("calc> ")8 9 foresee input == "exit":10 declare("Goodbye!")11 terminate12 13 # Parse simple expression: num op num14 parts := split(input, " ")15 16 attempt:17 foresee measure(parts) != 3:18 declare("Format: <number> <op> <number>")19 otherwise:20 a := decimal(parts[0])21 op := parts[1]22 b := decimal(parts[2])23 24 foresee op == "+":25 declare("=", a + b)26 alternate op == "-":27 declare("=", a - b)28 alternate op == "*":29 declare("=", a * b)30 alternate op == "/":31 foresee b == 0:32 declare("Error: Division by zero")33 otherwise:34 declare("=", a / b)35 alternate op == "^":36 declare("=", power(a, b))37 otherwise:38 declare("Unknown operator:", op)39 40 recover as e:41 declare("Error:", e)4243calculate()Want to see more? Check out the examples in the repository.
View on GitHub →