8

I'm beginner in SWI-Prolog (but have some experience in Borland Prolog), and I've faced with a strange behavior for the following test code:

test(10).
test(1).

It is expected for query ?-test(A) to get 2 solutions, something like A = 10; A = 1. However, only A = 10 is produced. I don't use the cut here. Maybe backtracking is off by default in SWI-Prolog?

Thanks in advance

Guy Coder
  • 24,501
  • 8
  • 71
  • 136
Spectorsky
  • 608
  • 4
  • 23
  • 3
    when `A=10` returned pres `;` to get another solutions and so on... – coder Jun 04 '17 at 13:24
  • Coder, many thanks for reply, and sorry for stupid question. I didn't expect that it is necessary to press Spacebar or semicolon after each solution, and I pressed Return. – Spectorsky Jun 04 '17 at 13:31

2 Answers2

11

Sorry, the answer is very simple (see SWI-Prolog doc):

The user can type the semi-colon (;) or spacebar, if (s)he wants another solution. Use the return key if you do not want to see the more answers. Prolog completes the output with a full stop (.) if the user uses the return key or Prolog knows there are no more answers. If Prolog cannot find (more) answers, it writes false.

Spectorsky
  • 608
  • 4
  • 23
  • 1
    The manual is a great source of information for how the basic aspects of SWI Prolog works. – lurker Jun 04 '17 at 17:44
  • 1
    When should you "type the semi-colon"? After entering a query like `?-pred(X).` I must press enter to get the solution, which also brings me to a new line where I can only enter after `?-` as if another query. – user289661 Oct 30 '18 at 20:56
  • user289661, type semicolon after getting solution, f you want to get other solutions. If you don't need more solutions, press enter. – Spectorsky Nov 03 '18 at 23:15
3

bagof/3 is probably what you're looking for.

?- bagof(X, test(X), Xs).

where Xs is a list of all matching results.
Know that anonymous variables don't work how you might expect with bagof. In the following example:

test(1,odd).
test(2,even).
test(3,odd).
test(4,even).

bagof(X, test(X,_), Xs) will only give values of X where the second term is uniform; in this case only the even numbers. If you want to return all matching value you need to do something like

?- bagof(X, A^test(X,A), Xs).
Jordan C.M.
  • 31
  • 1
  • 3
  • Jordan C.M., thanks for reply. There is also `findall`, thanks. I sought a way to see multiple solution from console, but your info is useful, thansk again. – Spectorsky Dec 03 '19 at 08:18