Update tech_docs/pseudocode.md

This commit is contained in:
2025-08-06 16:01:56 -05:00
parent 3281e01f02
commit cced7234d4

View File

@@ -1,3 +1,213 @@
# **Precision Pseudocode Engineering Guide**
*A Systems Approach to Algorithm Design Without Ambiguity*
---
## **1. Core Principles of Precision Pseudocode**
**Objective**: Create executable-like instructions that balance human readability with technical rigor.
### **Non-Negotiable Rules**
1. **Atomic Operations**: Each line must perform exactly one logical action.
2. **Type-Aware**: Variables must have explicit types (even if imaginary).
3. **Bounded Contexts**: Scope all operations within defined boundaries.
4. **Deterministic Outputs**: Same inputs → same outputs, always.
---
## **2. Pseudocode Object Model**
*(All pseudocode components are objects with literals.)*
| Object | Required Literals | Example |
|-----------------|--------------------------------|----------------------------------|
| `Variable` | `name`, `type`, `value` | `counter: Int = 0` |
| `Function` | `name`, `params`, `return_type`| `def sqrt(x: Float) → Float` |
| `Loop` | `iterator`, `range`, `exit_cond` | `for i in 0..<n: ` |
| `Conditional` | `condition`, `scope` | `if x > threshold: ` |
---
## **3. Constraint-Driven Syntax**
### **A. Variable Declarations**
```python
# BAD: Ambiguous
set x to 10
# GOOD: Type-bound
x: Int = 10 # Explicit 32-bit signed integer
```
**Constraint Enforcement**:
- Reject untyped variables.
- Use IEEE standard type names (`Float64`, `UInt8`).
### **B. Function Definitions**
```python
# BAD: Unbounded behavior
function process_data(input):
# GOOD: Precise contracts
function process_data(input: List[Float]) → Boolean:
"""Returns True if normalization succeeds."""
```
**Constraints**:
- Parameter/return types required.
- Single-responsibility principle (one function = one transformation).
### **C. Control Flow**
```python
# BAD: Unbounded loop
repeat until done:
# GOOD: Explicit exit conditions
while iterations < max_iterations and error > tolerance:
```
**Constraints**:
- All loops must have:
- A defined iterator (`i`, `index`)
- A hard exit condition (`i < n`, `error < 1e-6`)
---
## **4. Precision Patterns**
### **Pattern 1: Mathematical Operations**
```python
# BAD: Implicit casting
result = a / b
# GOOD: Type-aware
result: Float = Float(a) / Float(b) # Force floating-point division
```
### **Pattern 2: Error Handling**
```python
# BAD: Silent failures
file = open("data.txt")
# GOOD: Bounded recovery
try:
file: File = open("data.txt", mode="r")
except FileNotFoundError:
log_error("Missing file")
return False
```
### **Pattern 3: Data Transformations**
```python
# BAD: Ambiguous filtering
filter invalid entries
# GOOD: Literal-based
valid_entries: List[Data] = [
entry for entry in dataset
if entry.timestamp >= min_date and entry.value is not None
]
```
---
## **5. Validation Checklist**
Before finalizing pseudocode, verify:
1. [ ] **All variables have explicit types**.
2. [ ] **All loops and conditionals have exit conditions**.
3. [ ] **Functions define input/output contracts**.
4. [ ] **No implicit type conversions exist**.
5. [ ] **Error cases are bounded and handled**.
---
## **6. Example: Robust Search Algorithm**
```python
function binary_search(arr: List[Int], target: Int) → Int:
"""Returns index of target in sorted array, or -1 if not found."""
left: Int = 0
right: Int = len(arr) - 1
while left <= right:
mid: Int = left + (right - left) // 2 # Prevent overflow
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1 # Explicit failure signal
```
**Key Precision Techniques Applied**:
- Type annotations (`Int`, `List[Int]`).
- Overflow-safe midpoint calculation.
- Hard exit condition (`left <= right`).
- Deterministic return values (no `None`).
---
## **7. Anti-Patterns to Eliminate**
| Ambiguity | Precision Fix |
|---------------------|--------------------------------|
| "Handle errors" | `try/except` with logged cases |
| "Process data" | `function normalize(data: List[Float]) Bool` |
| "Repeat until done" | `while iterations < max_iter:` |
---
## **8. Tooling for Enforcement**
1. **Linters**: Custom rules to flag:
- Untyped variables.
- Unbounded loops.
2. **Templates**:
```python
# Function template
function [name]([param: Type]) → ReturnType:
"""[One-sentence purpose]"""
[Preconditions]
[Bounded operations]
[Postconditions]
```
---
## **9. Final Output**
**Input Chaos**:
*"Find the largest number in a list, but sometimes the list has bad data."*
**Precision Pseudocode**:
```python
function find_max_valid(values: List[Optional[Float]]) → Float:
"""Returns the maximum non-null value in a list.
Raises ValueError if no valid values exist."""
max_val: Float = -inf
valid_count: Int = 0
for value in values:
if value is not None:
valid_count += 1
if value > max_val:
max_val = value
if valid_count == 0:
raise ValueError("No valid values in input")
return max_val
```
**Why This Works**:
- Handles `null`/`None` explicitly.
- Uses IEEE float standards (`-inf` as initializer).
- Fails loudly with a descriptive error.
---
### **Summary**
> "Precision pseudocode isnt code—its **constrained thought engineering**.
> Define the literals, enforce the boundaries, and the logic will write itself."
**Next Step**: Apply this template to your domain by replacing:
- `List[Int]` → Your data structures
- `Float` → Your measurement units
- `try/except` → Your error recovery protocols
---
pseudocode examples pseudocode examples
Pseudocode is a simple way of expressing programming logic in plain language. It's a valuable tool to outline algorithms, aiding in understanding and problem-solving without using specific programming language syntax. Pseudocode is a simple way of expressing programming logic in plain language. It's a valuable tool to outline algorithms, aiding in understanding and problem-solving without using specific programming language syntax.
Why Use Pseudocode? Why Use Pseudocode?