2. Facts and queries
In this chapter, you describe the dependencies of a web app as facts, and ask questions about them.
Facts
The simplest clause is a fact. This fact says that my_app depends on react.
depends(my_app, react).dependsis the name of the relation. Prolog calls it a predicate.my_appandreactare the arguments. Here they are atoms, constant names. An atom starts with a lowercase letter.- The fact ends with a period.
The order of the arguments has a meaning that you decide. Here the first argument is the package that depends on the second one. Prolog itself doesn't know what depends means. It only knows that this fact is true.
We write the predicate as depends/2, which means "depends with 2 arguments". depends/2 and depends/3 are different predicates.
Queries
A query asks whether something is true. Press Run.
The first query shows true. It means that the query follows from the facts. Prolog then offers to look for another answer, because it hasn't checked all the facts yet. Press Next answer, and it says false., because there are no more. You can also press Done right away.
The second query is false., because no fact says that my_app depends on lodash. Prolog knows only what you told it. Anything else is false.
Variables
A name that starts with an uppercase letter or _ is a variable. A query with a variable asks which values make it true.
The first answer is Package = react. Press Next answer to get Package = vite. Press it once more, and Prolog says false., because there are no more answers.
Prolog tries the facts from top to bottom. For each fact that matches the query, it gives one answer.
Ask in any direction
The facts don't say which argument is the input. You can put the variable anywhere, or use two variables.
In JavaScript, you would need one function to find the dependencies of a package, and another function to find the packages that depend on it. In Prolog, the same facts answer both questions. This is one of the most important ideas in Prolog, and you will see it again and again.
"And" in a query
A comma in a query means "and". This query asks for a package that my_app depends on and that depends on esbuild.
The variable X must have the same value in both parts. Prolog first tries X = react, but depends(react, esbuild) is not true. So it goes back and tries X = vite, and that works. Going back to try another value is called backtracking. Chapter 8 is all about it.
The anonymous variable
When you don't care about a value, use _. This query asks whether vite depends on anything, without showing what.
Each _ is a new variable, and Prolog doesn't show its value. The same is true for a variable whose name starts with _, such as _Package. Later chapters use such names for values that you don't need to see.
Try it
Use the box below.
- Add a fact that says
reactdepends onloose_envify. - Write a query that lists everything
reactdepends on. - Write a query that finds the packages that the dependencies of
my_appdepend on. Use a comma.