2

I have coded this function that prints-out the state of the board, but in the end, due to the fact that there isnt no return the function prints an nil!

Function:

(defun show-board (board)
        (dotimes (number 8)
            (dotimes (number2 8)
                (let ((pos (aref board number number2))) 
                    (cond
                        ((equal pos 0) (format t "~a " "B"))   
                        ((equal pos 1) (format t "~a " "P"))
                        (t (format t "~a " "L")))))
                    (format t "~%")))

A board is an 8x8 array!

function call output on command lines:

B P B P B P B P
P B P B P B P B
B P B P B P B P
P B P B P B P B
B P B P B P B P
P B P B P B P B
B P B P B P B P
P B P B P B P B
NIL

How can i get rid of the NIL??

Drew
  • 29,895
  • 7
  • 74
  • 104
FPTLS
  • 177
  • 3
  • 15
  • 5
    It's nitpicky, but worth pointing out, that the `show-board` is not printing `NIL`. If you're in the REPL and do `CL-USER> (show-board ...)` you'll see nil, but if you do `CL-USER> (progn (show-board) 2)`, you won't (but you'll see `2`). It's the _REPL_ that's printing the value of the last evaluated form. This means that from any application code that calls `show-board`, you wouldn't see `NIL`, so while it's a nice touch for the REPL, it's not something you generally need to worry about. And even with `(values)`, you'll still get, e.g., `(list (show-board)) => (NIL)`. – Joshua Taylor Jul 02 '13 at 20:47

2 Answers2

4

You can get rid of multiple formats in the code:

Usually in a functional language I would return a value. It makes sense to return the board itself. Since such a function is usually called from game logic, a return value may be useful and it does not matter for output then.

(defun show-board (board)
  (dotimes (i 8)
    (dotimes (j 8)
      (write-string (case (aref board i j)
                      (0         "B ")
                      (1         "P ")
                      (otherwise "L "))))
    (terpri))
  board)
Rainer Joswig
  • 136,269
  • 10
  • 221
  • 346
1

adding (values) as return form for dotimes will do it:

(dotimes (number 8 (values))
   .....)

after all, show-board indeed doesn't return any values, right?

Will Ness
  • 70,110
  • 9
  • 98
  • 181