Re: standard function to change element at list position ?
- From: Jan Wielemaker <jan@xxxxxxxxxxxxxxxxxxx>
- Date: 30 Jun 2006 07:37:46 GMT
On 2006-06-29, Bill Spight <bspight@xxxxxxxxxxxx> wrote:
On Thu, 29 Jun 2006 18:36:28 +0100, none wrote:
Hello,
thanks for your comment.
I am using the list to represent a game board - board([[],[],[]]).
At some point I need to move a piece so the values of the two positions
change. I would use a term like value(Line, Column, Value). but that
would mean a lot of terms. Is it better?
You might try something like this. Make the board a 2D array. A 3x3 board
would look like this.
board(row(A,B,C),
row(D,E,F),
row(G,H,I))
This is a lot better. Please note: [A,B,C] is the same as .(A, .(B, .(C,
[]))). As a rule of thumb, anything with fixed length should not be
represented as a list. Note tho get the field at position (X, Y) you
simply need arg/3 twice, getting the result in constant time.
In addition, you can let each of the points, A - I, be an incomplete
list. Let '-' represent an empty point and 'k' and 'j' represent pieces.
The center point, E, might be
['-','k','-','j','-'|Es].
The list represents the history of point E. E started off empty, then it
was occupied by 'k', then it was empty again, then occupied by 'j', and
now it is empty. Suppose that 'k' moves back there. Then E will look like
this.
['-','k','-','j','-','k'|EEs].
It's a bit of a bother to find out the current state of the board and to
make a move, but you do not create a new board each time you make a play,
so you save space.
Quite a few modern Prolog systems have mutable terms these days.
setarg/3 is popular, but some Prolog systems use different primitives.
Check the manual. Using setarg, setting the point (X,Y) is simply
set_board(Board, X, Y, Value) :-
arg(Y, Board, Row),
setarg(X, Row, Value).
Backtracking restores the old value. Like assert/retract, do not overuse
setarg/3. In most cases it leads to hard to understand and maintain
programs. In some cases however its a life-saver.
Cheers --- Jan
.
- References:
- standard function to change element at list position ?
- From: none
- Re: standard function to change element at list position ?
- From: Jan Wielemaker
- Re: standard function to change element at list position ?
- From: none
- Re: standard function to change element at list position ?
- From: Bill Spight
- standard function to change element at list position ?
- Prev by Date: Re: standard function to change element at list position ?
- Next by Date: Re: SWI-Prolog get_single_char
- Previous by thread: Re: standard function to change element at list position ?
- Next by thread: SWI-Prolog get_single_char
- Index(es):