Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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.

share|improve this question
    
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. –  Jeff Mercado Apr 26 '13 at 14:35

2 Answers 2

up vote 1 down vote accepted

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).
share|improve this answer

In SWI-Prolog you can simply do:

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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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