Some newbie questions (e.g. how to get at most N solutions, what is template? what is @, :, +, - in arguments)

"Those who cannot learn from history are doomed to repeat it.“
by George Santayana

The SWI-Prolog Manual was originally written as a manual so one should read the first part. With it now being accessible as a web site and being able to link directly to topics, many don’t know about and read the introduction.

This document is a reference manual . That means that it documents the system, but it does not explain the basics of the Prolog language and it leaves many details of the syntax, semantics and built-in primitives undefined where SWI-Prolog follows the standards. This manual is intended for people that are familiar with Prolog. For those not familiar with Prolog, we recommend to start with a Prolog textbook such as Bratko, 1986, Sterling & Shapiro, 1986 or Clocksin & Melish, 1987. For more advanced Prolog usage we recommend O’Keefe, 1990.

In other words reading the manual first is like jumping into the deep end of the pool and not knowing how to swim.

Instead try, Learn Prolog Now! and check out Useful Prolog references.


  1. Is my approach above correct? i.e. using cut at the end of query to get at most N solutions.

If you are trying to group the results based on a count then findnsols/4 is what I would use.

In the example below see how it groups the answers by the count.

Click triangle to expand
Welcome to SWI-Prolog (threaded, 64 bits, version 8.5.0)

?- [user].
|: test(1,1).
|: test(1,2).
|: test(2,1).
|: test(2,2).
|: 
% user://1 compiled 0.00 sec, 4 clauses
true.

?- test(X,Y).
X = Y, Y = 1 ;
X = 1,
Y = 2 ;
X = 2,
Y = 1 ;
X = Y, Y = 2.

?- findnsols(2, [X, Y], test(X, Y), Xs).
Xs = [[1, 1], [1, 2]] ;
Xs = [[2, 1], [2, 2]].

What is normally done is to use Goal to access/filter the data (think SQL rows) then use Template to select the parts you want to keep (think SQL fields).

I can’t recall personally ever using findnsols/4 for a real problem. I know there are real use cases for when to use it but your example explanation doesn’t give me enough details to give relevant feedback. Also if a cut (!) is not your friend then be very careful using them, they might do what you don’t expect.


  1. What exactly Template is?

Something created to confuse new people? :thinking: Just like C++ was created to make life harder for those who use C.

Seriously, the way to think of predicates that use Template is to think of the Goal you want to run first, then use the Template to extract the data you want to collect as an item, then put all of the items into the Bag/List/Set as a list/set.

The way I learned about them was looking at lots of examples.


  1. What’s the meaning of + , - , : , @ at the predicate declares in the document?

See: Type, mode and determinism declaration headers

Yes I know I gave you a link to the manual but you asked about a topic not noted in many other places. :slightly_smiling_face: