No loops? No assignment? How?!
Welcome to Learn Prolog. Get ready, because Prolog breaks the rules you know.
- There are no
forloops and nowhileloops. - 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!
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.
Contents
How Prolog thinks
Search and control
Goal 1. The Game of Life
Text and grammar rules
Goal 2. Markdown to HTML
Appendix