0

I probably just don't understand Lisp scoping, but I'm struggling to understand what's going on in this tic-tac-toe game, which I've stubbed down to demonstrate the problem:

(defun tic-tac-toe ()
  (let ((board '((- - -) (- - -) (- - -))))
    (draw-board board)
    (format t "~%")
    (make-move board)
    (draw-board board)))

(defun draw-board (board)
  (dolist (row board)
    (apply #'format (cons t (cons "~A ~A ~A~%" row)))))

(defun make-move (board)
  (setf (caar board) 'x))

The tic-tac-toe function is intended to be the main entry point, and each time I run it the game should start from scratch. However, look what happens when I run it in CLISP:

[2]> (tic-tac-toe)
- - -
- - -
- - -

X - -
- - -
- - -
NIL
[3]> (tic-tac-toe)
X - -
- - -
- - -

X - -
- - -
- - -
NIL

The first time, the board starts out blank (all dashes), but after that the board always starts out with the old values left over in it. How is this happening? Shouldn't the let re-initialize the board each time?

Rainer Joswig
  • 136,269
  • 10
  • 221
  • 346
Josiah Keller
  • 3,635
  • 3
  • 23
  • 35
  • you modify the code. Your board is a literal list. It's undefined what happens when you try it. Imagine the code to be in read-only memory. What you want is either not to modify the board in make-move or to create a new board in tic-tac-toe. As it is now, in the function tic-tac-toe you always use the same literal list, a list which is embedded in your code. – Rainer Joswig Mar 10 '17 at 04:11
  • "create a new board" I guess I thought that's what I was doing. What should I be doing instead? – Josiah Keller Mar 10 '17 at 04:12
  • create a new board: the function LIST makes a new list. COPY-LIST creates a new list. COPY-TREE makes new nested lists, CONS creates new cons cells. – Rainer Joswig Mar 10 '17 at 04:14
  • @RainerJoswig Makes sense, thank you. – Josiah Keller Mar 10 '17 at 04:23
  • http://stackoverflow.com/questions/8962909/why-does-this-function-return-a-different-value-every-time http://stackoverflow.com/questions/40335429/lisp-function-affecting-other-function – Rainer Joswig Mar 10 '17 at 10:14
  • Also see [unexpected persistence of data](http://stackoverflow.com/questions/18790192/unexpected-persistence-of-data). – Joshua Taylor Mar 14 '17 at 15:14

0 Answers0