This meta-question is inspired by this challenge, which basically asks to count from 1 to N. However this is a question that bothers me in a lot of challenges which have those “iterative”/“print all X such that” kind of outputs.
So keeping as an example this challenge of counting from 1 to N, a possible solution in Prolog is to write a predicate which will unify a variable with an integer. Then, Prolog's backtracking mechanism makes it so that we can ask all possible values that make this predicate true.
For instance in this example, I could write a predicate a(N,I)
which unifies I
with an integer between 1 and N
. Calling it would give this result:
?- a(5,I).
I = 1
However now instead of terminating, Prolog's REPL halts: if I type ;
(logical or), it will give me a second answer:
I = 2
I can keep doing this until it finds no more solution:
I = 3 ;
I = 4 ;
I = 5
And now it has terminated.
Is this a fair way of returning/printing outputs? Note that it is possible to fill a list with all those unifications and return that list using findall
, but this is obviously longer.
This question also applies for languages that work on Prolog (e.g. Brachylog) or that have a similar mechanism in their REPL (e.g. ?)