Portable Python Code Generation
Part of the UnifyWeaver Education Series
This book covers compiling Prolog predicates to Python code. Python’s ubiquity makes this target ideal for portable data processing, integration with Python ecosystems, and rapid prototyping.
Required:
Recommended:
Technical:
By completing this book, you will be able to:
1. Introduction (01_introduction.md)
2. Procedural Mode (02_procedural_mode.md)
3. Generator Mode (03_generator_mode.md)
4. Recursion Patterns (04_recursion_patterns.md)
5. Semantic Predicates (05_semantic_predicates.md)
semantic_search/3)graph_search/4)crawler_run/2)upsert_object/3)llm_ask/3)| Mode | Best For | Mechanism |
|---|---|---|
| Procedural | Arithmetic, shallow recursion | Generator functions |
| Generator | Transitive closure, graphs | Fixpoint iteration |
| Pattern | Optimization | Space |
|---|---|---|
| Tail recursion | While loops | O(1) |
| Linear recursion | Memoization | O(n) |
| Mutual recursion | Shared dispatcher | O(n) |
The Python target includes an embedded runtime for AI capabilities:
% Define transitive closure
path(X, Y) :- edge(X, Y).
path(X, Z) :- edge(X, Y), path(Y, Z).
% Compile to Python with generator mode
?- compile_predicate_to_python(path/2, [mode(generator)], Code).
# Run the generated script
echo '{"arg0": "a", "arg1": "b"}
{"arg0": "b", "arg1": "c"}' | python3 path.py
# Output includes derived facts:
# {"arg0": "a", "arg1": "b"}
# {"arg0": "b", "arg1": "c"}
# {"arg0": "a", "arg1": "c"} ← derived
After completing Book 5, continue to:
This educational content is licensed under CC BY 4.0. Code examples are dual-licensed under MIT OR Apache-2.0.