You are absolutely right. The Haskell implementation, while demonstrating the power of function inversion, became overly complex and relied on external libraries, defeating the goal of a simple, self-contained format.
Let's drastically simplify Leaf and its implementation. We'll aim for a format that's truly "flat" and easy to parse/serialize with minimal code and no external dependencies.
🎯 Revised Goals
- Minimal Syntax: Key-value pairs, one per line.
- No Nesting: Flat structure – no dotted keys.
- String Values Only: No type hints, no arrays.
- Metadata:
@key=value lines.
- Comments:
# ... lines.
📝 Revised Syntax
# Leaf (Simplified)
@format=Leaf-Simple-1.0
user.id=42
user.name=Alice Wonderland
user.age=30
user.verified=true
🐍 Simplified Python Implementation
def decode_leaf(lines):
"""Decode a simplified Leaf-formatted string."""
data = {}
metadata = {}
for line in lines:
line = line.strip()
if not line:
continue
if line.startswith('#'):
continue
if line.startswith('@'):
key, value = line[1:].split('=', 1)
metadata[key] = value
else:
key, value = line.split('=', 1)
data[key] = value
return data, metadata
def encode_leaf(data, metadata=None):
"""Encode a dictionary into simplified Leaf format."""
lines = []
if metadata:
for key, value in metadata.items():
lines.append(f'@{key}={value}')
for key, value in data.items():
lines.append(f'{key}={value}')
return lines
🧪 Example Usage
data = {
"user.id": "42",
"user.name": "Alice Wonderland",
"user.age": "30",
"user.verified": "true"
}
metadata = {
"format": "Leaf-Simple-1.0",
"source": "user-db-export"
}
encoded_lines = encode_leaf(data, metadata)
print("\n".join(encoded_lines))
decoded_data, decoded_metadata = decode_leaf(encoded_lines)
print("Decoded Data:", decoded_data)
print("Decoded Metadata:", decoded_metadata)
✅ Advantages of the Simplified Version
- Extremely Simple: Minimal syntax and logic.
- No Dependencies: Pure Python, no external libraries required.
- Easy to Understand: The code is straightforward and easy to maintain.
- Streaming-Friendly: Can process line-by-line.
⚠️ Limitations
- No Nesting: All keys must be flat.
- String Values Only: No type hints, no arrays, no complex data structures.
- Limited Expressiveness: Not suitable for complex data.
This revised version of Leaf prioritizes simplicity and self-containment. It's a trade-off – you lose the ability to represent complex data structures directly, but you gain a format that's incredibly easy to implement and maintain.
If you need to represent nested data, you'll have to handle it in your application logic (e.g., by manually parsing and constructing nested dictionaries). But for simple configuration files or flat data storage, this simplified Leaf format is a good choice. 🌿