Grounding is one of the weirdest concepts in Prolog and the ones that occassionally comes back to haunt me.

Since Prolog is for Nerds³ I decided to translate it to Engineer½ (like myself) language.


When you declare a list in Prolog it comes with strings attached (sometimes literally):

?- length(AwesomeList, 3).
AwesomeList = [_, _, _].

Too much? Not enough? Who can say! According to Prolog it might be what you wanted!

Let's say I want to produce some shape in the two-dimensional list. I don't care about whatever might be the noise, the background. It can be transparent - I only care for the shape itself.

And so Prolog does keep values, but they're exactly like that - transparent, abstract - they are exactly what you asked them to be, even if it's nothing. Those values are called Free Variables but there are also other names, too.

You could imagine above AwesomeList like this:

It's not uncommon to see lists like [_1234, _9999, _7777].

Those numbers mean that this is still a Free Variable but it might not be the same value, or might definitelly be different values.


What if you want to be more precise? How can you say that you want something to exist inside?

That's simple. You just provide another fact to Prolog. For example, by saying that magic_box is a member of our AwesomeList:

?- length(AwesomeList, 3), member(magic_box, AwesomeList).
AwesomeList = [magic_box, _, _] ;
AwesomeList = [_, magic_box, _] ;
AwesomeList = [_, _, magic_box].

And as we can see, it doesn't matter what exists in those other elements in list. Those are 3 only possible answers upon infinite ones.


Process of assigning concrete value is called binding, unification or grounding. I like the last term best, but it's up to you to choose your favorite one.

Grounding doesn't have to happen and the neat thing about Prolog is that it can be deferred till later, which allows coding that feels like magic. 1

A very simple example would be:

?- length(AwesomeList, 3), A = 1, nextto(A, 2, AwesomeList).
AwesomeList = [1, 2, _],
A = 1 ;
AwesomeList = [_, 1, 2],
A = 1 ;

Which you can visualize as:

It's fun to describe different set of constraints for grounding to happen. Pitfalls? We have plenty of those, and I'll show in future entries.

What's left to say? Have fun grounding in Prolog!


1

Note that Prolog IS NOT MAGIC. It can be nondeterministic sometimes, but it's definitely not magic.

Well, unless you mean that in sense that "any sufficently advanced technology is indistinguishable from magic" magic.
Then yes. Prolog is magic.