-2
(defun tictactoe3d ()
'(
 ((NIL NIL NIL) (NIL NIL NIL) (NIL NIL NIL))
 ((NIL NIL NIL) (NIL NIL NIL) (NIL NIL NIL))
 ((NIL NIL NIL) (NIL NIL NIL) (NIL NIL NIL))
))

I need a function that will add a X or a O in the place of a NIL and I need that function to ask the user where he wants to put it. The board game is a tic tac toe 3D (3 boards intead of 1, 27 positions instead of 9). The first line is level 1 (and it is basically the same as having one tic tac toe with 9 positions). How can I add an element to a list like this. I know I have to verify if a position is nil.

Joao Costa
  • 21
  • 2
  • Possible duplicate of [In common-lisp, how do I modify part of a list parameter from within a function without changing the original list?](http://stackoverflow.com/questions/1484335/in-common-lisp-how-do-i-modify-part-of-a-list-parameter-from-within-a-function) – planetmaker Nov 23 '15 at 14:10
  • 2
    really, did you just type here without going through *any* google foo before? – planetmaker Nov 23 '15 at 14:11

1 Answers1

7

The list you return is a constant. You must not mutate constants because it has undefined consequences. If you want to use purely functional data-structures, you can define operations that return modified copies of your board.

You are using a list where I think you should really be using an array: after all, a board is really a fixed-size grid. Here is how you allocate it:

(make-array '(3 3 3) :initial-element nil)

=> #3A(((nil nil nil) (nil nil nil) (nil nil nil))
       ((nil nil nil) (nil nil nil) (nil nil nil))
       ((nil nil nil) (nil nil nil) (nil nil nil)))

Then, you use aref and (setf aref):

(setf (aref board z y x) value)
coredump
  • 37,664
  • 5
  • 43
  • 77
  • " If you want to use purely functional data-structures, you can make modified copies of your board after each operation." Eh, I guess you mean making copies before applying the modifying operations (to these copies). – Daniel Jour Nov 23 '15 at 15:17
  • @DanielJour, Yes, the result is a modified copy (typically, with some data being shared). I edited with the hope that it sounds better. – coredump Nov 23 '15 at 15:22
  • Yes, that's much better :) – Daniel Jour Nov 23 '15 at 15:35