iTranslated by AI
How to Run Prolog in Jupyter Notebook
1. Introduction
The Prolog execution environment is quite inconvenient, isn't it? Because:
- You have to reload the file every time you edit the source code.
- You have to type the same queries again every time you re-run them.
It is very troublesome. There was even a tragedy like this in the past:
Now, assuming my intended audience, you have likely encountered Jupyter Notebooks. Without being too pedantic, you can think of it as an interactive Python execution environment. Yes, it would be convenient if Prolog ran in a Jupyter Notebook, wouldn't it?
2. Environment Setup
We will use the Dev Container feature in Visual Studio Code. If you don't know what that is, look it up! I don't think it's that difficult. The configuration file devcontainer.json for the Dev Container looks like this:
{
"name": "Prolog Jupyter",
"image": "mcr.microsoft.com/devcontainers/python:1-3.12-bullseye",
"postCreateCommand": "sudo apt-get update && sudo apt-get install -y swi-prolog && pip install --upgrade pip && pip3 install --user jupyter prolog_kernel && python -m prolog_kernel.install",
"customizations": {
"vscode": {
"extensions": [
"ms-python.python",
"ms-toolsai.jupyter",
"rebornix.prolog"
]
}
}
}
However, since some of you may not know how to use Dev Containers, I will briefly explain the installation procedure.
First, to use Prolog in a Jupyter Notebook, you need a Jupyter kernel to execute Prolog interactively. Here, we will use the kernel developed in the following repository called Herculog:
To run this, you need the following:
- Python
- Jupyter
- SWI Prolog
So, let's install them in order.
First is Python. You can use any method you like. Using the Python preset if you use Dev Container is easy. It also comes with Git pre-installed, which is convenient.
Next is SWI Prolog. You can install it by running the following command:
sudo apt-get install -y swi-prolog
Next, download the Python packages. You should run the following command:
pip3 install jupyter prolog_kernel
Finally, install the kernel for Prolog:
python -m prolog_kernel.install
Since the kernel doesn't seem to be recognized immediately after installation, you need to reload the Visual Studio Code window once. Select Prolog from the kernel selection menu in the top right of the screen. Everything should be ready now.
3. Execution Example
I tried running it as a test:

In the SWI Prolog shell, you would use . to continue processing. A major difference is that in Jupyter Notebooks, since you cannot provide interactive input during execution, you use a syntax like ?- retry. instead. By the way, if you do not want to continue, it seems you use ?- cut.. For more detailed information:
The source code used to verify the operation this time is here:
Discussion