Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prolog fill a list automatically with variables in loop

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
like image 823
viktor Avatar asked Jan 20 '23 14:01

viktor


1 Answers

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.

like image 59
mgiuca Avatar answered Jan 30 '23 04:01

mgiuca