No loops? No assignment? How?!

Welcome to Learn Prolog. Get ready, because Prolog breaks the rules you know.

  • There are no for loops and no while loops.
  • There are variables, but you can't assign a new value to them.
  • There are no return values.
  • And you will not often write an if.

Wait. Then how can anyone write a program at all?!

That is the mystery this tutorial solves, one small step at a time. If you write JavaScript or TypeScript, you already know enough to start. Welcome to a new world of programming!

Start chapter 1

First, a surprise

The two lines of join below join two lists. Press Run. The first question is the usual one, so press Done. The second question asks backwards. Which two lists make this one? Press Next answer again and again.

You never wrote how to split a list. You only said what joining means, and you got the splitting for free.

A puzzle solver with no loop

Paint three houses in a row, so that all three have different colors. Don't write how to search. Just write what a good answer looks like, and let Prolog find all of them.

You can edit the text in every box and run it right in the page. Nothing is sent to a server. Can you add a fourth color and see what happens?

Mysteries you will solve

The mystery Where you solve it
How do you choose without writing if? Chapter 3, Rules
How do you repeat without a loop? Chapter 4, Recursion
What good is a variable that you can't assign to? Chapter 5, Terms and unification
How can one rule work backwards? Chapter 6, Lists
Who does all the searching? Chapter 8, Searching by backtracking

Where your journey ends

You will not stop at small examples. You will build two real programs.

Conway's Game of Life. Cells live and die by a few simple rules, and shapes start to move. You will write those rules in Prolog almost as they are written in English.

 . # .          . . .
 . . #    =>    # . #
 # # #          . # #
 . . .          . # .

A Markdown to HTML converter. It reads headings, paragraphs, lists, and emphasis. You will write the grammar of Markdown, and Prolog reads the text with it. It has no loops and no string indexes.

# Hello             <h1>Hello</h1>
I *love* it.   =>   <p>I <em>love</em> it.</p>

Ready? The first step takes only a few minutes.

Start the adventure

Contents

How Prolog thinks

  1. Introduction
  2. Facts and queries
  3. Rules
  4. Recursion
  5. Terms and unification
  6. Lists
  7. Arithmetic

Search and control

  1. Searching by backtracking
  2. Negation and cut
  3. Collecting solutions

Goal 1. The Game of Life

  1. The board
  2. The rules
  3. Running and drawing

Text and grammar rules

  1. Grammar rules
  2. Text as characters

Goal 2. Markdown to HTML

  1. The document as a term
  2. Reading blocks
  3. Reading inside a line
  4. Writing HTML

Appendix

An unhandled error has occurred. Reload 🗙