I have a list in Prolog like this:

Puzzle = [ A1, A2, A3,
           B1, B2, B3,
           C1, C2, C3 ].

And I want every variable in the list to be a number in the range of 1 to 9. Currently I'm doing this like so:

between(1,9, A1),
between(1,9, A2),
% ...
between(1,9, C3).

Even though this works, it's already pretty ugly even for the only 9 numbers I have so far. However I will have to expand my list to contain at least 81 numbers at first (A1 till I9), and even 405 in the end.

I would rather not 'write' 405 lines of code just to limit the range of the numbers in the list, but since I'm new to Prolog, I don't know how I can improve this.

  • \$\begingroup\$ Before moving on, I would strongly advise you to actually try to learn the language. What you are asking here is very basic and fundamental to using the language. \$\endgroup\$ – Jeff Mercado Apr 26 '13 at 14:35

Once you will have to hardcode your list to include all the variables from A1 to I9. Then you can iterate through it:

foreach(X, Your_list) do between(1, 9, X).

In SWI-Prolog you can simply do:

?- numlist(1,9,Puzzle).
Puzzle = [1, 2, 3, 4, 5, 6, 7, 8, 9].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.