UnifyWeaver

Book 5: Python Target

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.

Prerequisites

Required:

Recommended:

Technical:

What You’ll Learn

By completing this book, you will be able to:

Chapters

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)

Key Concepts

Two Evaluation Modes

Mode Best For Mechanism
Procedural Arithmetic, shallow recursion Generator functions
Generator Transitive closure, graphs Fixpoint iteration

Recursion Handling

Pattern Optimization Space
Tail recursion While loops O(1)
Linear recursion Memoization O(n)
Mutual recursion Shared dispatcher O(n)

Semantic Runtime

The Python target includes an embedded runtime for AI capabilities:

Quick Example

% 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

What’s Next?

After completing Book 5, continue to:

License

This educational content is licensed under CC BY 4.0. Code examples are dual-licensed under MIT OR Apache-2.0.