Tactical Patterns

Execution Gallery

12 battle-tested examples covering everything from basics to advanced patterns. Copy, adapt, and execute.

BasicsRecursionAlgorithmsAsyncGeneratorsPatternsBidirectionalPracticalREPL

Hello World

Basics

Your first Keikaku program - simple output and variables.

KEIKAKU Protocol
1# Hello World in Keikaku
2declare("Hello, World!")
3
4# Variables
5name := "Keikaku"
6version := 1.0
7
8declare("Welcome to", name, "v" + text(version))

FizzBuzz

Basics

Classic interview problem solved with Keikaku control flow.

KEIKAKU Protocol
1# FizzBuzz - the programming classic
2cycle 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)

Fibonacci Sequence

Recursion

Recursive and iterative implementations with memoization.

KEIKAKU Protocol
1# Recursive Fibonacci
2protocol fib_recursive(n):
3 foresee n <= 1:
4 yield n
5 otherwise:
6 yield fib_recursive(n - 1) + fib_recursive(n - 2)
7
8# Iterator-based Fibonacci (more efficient)
9sequence fibonacci():
10 a := 0
11 b := 1
12 cycle while true:
13 yield a
14 temp := a + b
15 a = b
16 b = temp
17
18# Get first 15 Fibonacci numbers
19gen := fibonacci()
20cycle from 0 to 15 as _:
21 declare(proceed(gen))

Prime Number Sieve

Algorithms

Sieve of Eratosthenes implemented as a lazy generator.

KEIKAKU Protocol
1# Prime number generator using sieve approach
2sequence primes():
3 yield 2
4
5 candidates := [3]
6
7 cycle while true:
8 n := candidates[0]
9 is_prime := true
10
11 cycle through candidates as p:
12 foresee n % p == 0:
13 is_prime = false
14 terminate
15
16 foresee is_prime:
17 push(candidates, n)
18 yield n
19
20 # Move to next odd number
21 candidates[0] = candidates[0] + 2
22
23# Generate first 20 primes
24gen := primes()
25cycle from 0 to 20 as _:
26 declare(proceed(gen))

Concurrent Tasks

Async

Launch multiple async tasks and collect their results.

KEIKAKU Protocol
1# Simulate async API calls
2async protocol fetch_user(id):
3 declare("Fetching user", id, "...")
4 sleep(200)
5 yield {"id": id, "name": "User " + text(id)}
6
7async 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 ]
14
15# Run concurrent fetches
16async 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"] := posts
24 yield user
25
26gen := load_profile(42)
27profile := proceed(gen)
28declare("Profile:", profile)

Lazy Data Pipeline

Generators

Process large datasets efficiently with chained generators.

KEIKAKU Protocol
1# Simulated large dataset
2data := span(10000)
3
4# Build lazy transformation pipeline
5# Each stage only processes values on-demand
6stage1 := (x * 2 for x through data)
7stage2 := (x + 10 for x through stage1)
8filtered := (x for x through stage2 where x % 100 == 0)
9
10# Only compute what we need
11count := 0
12cycle through filtered as val:
13 declare("Value:", val)
14 count = count + 1
15 foresee count >= 10:
16 declare("Stopping after 10 results")
17 terminate

HTTP Server Simulation

Practical

Request handling pattern with routing and middleware.

KEIKAKU Protocol
1# Request handler protocol
2protocol handle_request(method, path, body):
3 declare("[" + method + "]", path)
4
5 # Routing
6 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 body
15 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"}
22
23# Test requests
24declare(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))

State Machine

Patterns

Traffic light controller using generators for state management.

KEIKAKU Protocol
1# State machine as a generator
2sequence traffic_light():
3 states := ["🔴 RED", "🟢 GREEN", "🟡 YELLOW"]
4 durations := [3000, 4000, 1000] # ms
5 index := 0
6
7 cycle while true:
8 current_state := states[index]
9 current_duration := durations[index]
10
11 yield {
12 "state": current_state,
13 "duration": current_duration
14 }
15
16 sleep(current_duration)
17 index = (index + 1) % 3
18
19# Simulate traffic light
20light := traffic_light()
21cycle from 0 to 6 as _:
22 status := proceed(light)
23 declare("Light:", status["state"])

Chat Echo Bot

Bidirectional

Bidirectional generator for interactive communication.

KEIKAKU Protocol
1# Echo bot using bidirectional communication
2sequence 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 terminate
11
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)
23
24bot := chat_bot()
25declare(proceed(bot)) # Hello message
26declare(transmit(bot, "hello there")) # Echo
27declare(transmit(bot, "help")) # Help
28declare(transmit(bot, "joke")) # Joke
29declare(transmit(bot, "quit")) # Goodbye

JSON Config Parser

Practical

Read and validate configuration files with error handling.

KEIKAKU Protocol
1# Config loader with validation
2protocol load_config(filepath):
3 attempt:
4 content := decipher(filepath)
5 config := decode_json(content)
6
7 # Validate required fields
8 required := ["host", "port", "database"]
9 cycle through required as field:
10 foresee config[field] == nil:
11 yield {"error": "Missing field: " + field}
12
13 # Validate types
14 foresee classify(config["port"]) != "int":
15 yield {"error": "Port must be integer"}
16
17 declare("Config loaded successfully")
18 yield config
19
20 recover as error:
21 declare("Failed to load config:", error)
22 yield {"error": text(error)}
23
24# Usage
25config := load_config("config.json")
26foresee config["error"]:
27 declare("Error:", config["error"])
28otherwise:
29 declare("Host:", config["host"])
30 declare("Port:", config["port"])

Rate Limiter

Patterns

Token bucket algorithm for API rate limiting.

KEIKAKU Protocol
1# Token bucket rate limiter
2sequence rate_limiter(rate, max_tokens):
3 tokens := max_tokens
4 last_time := timestamp()
5
6 cycle while true:
7 request := receive()
8 now := timestamp()
9
10 # Refill tokens based on time passed
11 elapsed := now - last_time
12 refill := elapsed * rate
13 tokens = min(max_tokens, tokens + refill)
14 last_time = now
15
16 foresee tokens >= 1:
17 tokens = tokens - 1
18 yield {"allowed": true, "remaining": tokens}
19 otherwise:
20 yield {"allowed": false, "retry_after": (1 - tokens) / rate}
21
22# Test: 2 requests per second, max 5 burst
23limiter := rate_limiter(2, 5)
24proceed(limiter)
25
26cycle 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)

Mini Calculator

REPL

Interactive calculator with expression evaluation.

KEIKAKU Protocol
1# Simple interactive calculator
2protocol 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 terminate
12
13 # Parse simple expression: num op num
14 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)
42
43calculate()

Want to see more? Check out the examples in the repository.

View on GitHub →