Page 1 of 1

Help for building a board

Posted: Thu Nov 10, 2011 5:36 am
by aedsferrao
Hi!

It's my first time in LispForum and i have a question. I'am suposse to do a board to a game (game y) and when i give
> (setf tab1 (do-board 4))
((* * *)
(* * * * * *)
(* * * * * * * * *)
(* * * * * * * * * * * *))

and now my code is

(defun do-board (x)

(defun board2 (i list1 list2)
(if (zerop i)
(append (list1 list2))
list1))
(if (zerop x)
(list '(* * *))
(board 2 x list1 list2)))

(defun append (list1 list2)
(if (null list1)
list2
(cons (first list1) (append (rest list1) list2))))

I hope you understand and help me please.

Thank you

Re: Help for building a board

Posted: Thu Nov 10, 2011 8:14 am
by Konfusius

Code: Select all

(defun do-board (n)
  (loop for i from 1 to n
        collect (loop repeat i
                      append '(* * *))))

Re: Help for building a board

Posted: Thu Nov 10, 2011 10:16 am
by gugamilare
Wait, you need to be careful here. This is not going to work because it modifies literal data. You have to construct the list in running time:

Code: Select all

(defun do-board (n)
  (loop for i from 1 to n
        collect (loop repeat i
                      append (list '* '* '*))))
or

Code: Select all

(defun do-board (n)
  (loop for i from 1 to n
        collect (loop repeat i
                      append (copy-list '(* * *)))))

Re: Help for building a board

Posted: Fri Nov 11, 2011 3:28 am
by Konfusius
gugamilare wrote:This is not going to work because it modifies literal data.
This might be true but it shouldn't. It's almost never a good idea to operate destructively on a list structure except maybe for avoiding excessive consing while building it. Its good practice to assume that you cannot operate on a list structure destructively unless the documentation of the function returning it does explicitly state it returns fresh conses. Otherwise you couldn't use liteal lists at all.

By rewriting do-board to return a fresh structure you actually recommend to write code around a bad programming style which is a very bad idea imo. If the OP plans to operate on the board destructively he'd be better off with arrays. But since this wasn't the OP's question I didn't recommend it. And if he runs into trouble with his "list board" then it's actually a good thing because he has to learn not to operate on lists destructively anyway.

Re: Help for building a board

Posted: Fri Nov 11, 2011 3:26 pm
by aedsferrao
Thank you for everything. It's working now. My problem is that is my first time programming in Lisp and in my school they don't teach this right and now we must do the game Y in common lisp and i'm a little confused.

by the way you know any quick guide to learn common list?

Re: Help for building a board

Posted: Fri Nov 11, 2011 11:14 pm
by Konfusius