4

how to fill a list automatically with variables?

like

for(i=1;i<=9,i++){
    addtoanylist(X_i);
}

so that the result is like L=[X1,X2,X3,X4,X5,X6,X7,X8,X9]. ?

its because i want to build up a proper size of a list for my sudokusolver.

i get the size here:

sudoku_size_check(L) :-
    len(L,N),
    member(N,[4,9,16,25]), %check if its 4x4,9x9..
    write('Listlength: '),
    write(N),nl,
    range(1,N,RangeList), %generate [1,2,3,4] in 4x4, [1..9] in 9x9..
    write('Possible numbers: '),
    write(RangeList), % in 4x4 its like [1,2,3,4]
    nl,
    retract(sudoku_settings(_,_)),
    assert(sudoku_settings(N,RangeList)). %write stats into global variable
gsamaras
  • 71,951
  • 46
  • 188
  • 305
viktor
  • 51
  • 3

1 Answers1

9

You can fill up a list with free variables by applying the "length" predicate in reverse:

length(L, 9).

This results in L = [_G320, _G323, _G326, _G329, _G332, _G335, _G338, _G341, _G344] -- a list of nine free variables which may be bound at a later time.

This is unusual for a predicate called "length", but if you read it declaratively, "length(L, 9)" says: "L is any list of length 9." That's exactly what you want -- a list of 9 free variables fits the most general case of that definition.

mgiuca
  • 20,958
  • 7
  • 54
  • 70
  • 1
    Glad it helped. Can you please tick the checkmark to indicate that this is a valid solution? – mgiuca Jun 05 '11 at 09:58
  • @mgiuca i know it makes no functional difference, but for readability sake, do you know if there's a way to change the naming scheme of the free variables to something like X1,X2.... – yurib Mar 30 '14 at 17:39
  • No, I don't think so. Those names are internal to the compiler so different compilers will generate different names. There may be a setting in a compiler that lets you change it but there isn't a way to do it in the language itself. – mgiuca Mar 30 '14 at 21:34