Subject: Re: Style question
From: rpw3@rpw3.org (Rob Warnock)
Date: Sat, 03 Dec 2005 07:48:11 -0600
Newsgroups: comp.lang.lisp
Message-ID: <H_WdnX7LMJeGPwzeRVn-rQ@speakeasy.net>
micromoog <micromoog@gmail.com> wrote:
+---------------
| I'm in the early stages of learning Lisp, and I've just written my
| first program that actually does something (trivial though it is).
| Is my style appropriate for all of the things I'm doing here?
+---------------

Others have commented on your parens & indentation, so I'll just say this:

1. On most platforms you'll need to do a FORCE-OUTPUT [or FINISH-OUTPUT]
   when outputting partial lines, especially to buffered streams.
   [See code below.] (Usually you can omit this if what you're printing
   ends in a newline.)

2. Use the "expression" (rather than "statement") nature of the
   language to help you simplify things. That is, rather than this:

     (if (> guess num)
       (format t "Too high, try again: ")
       (format t "Too low, try again: ")

   you can write this:

       (format t "Too ~a, try again: " (if (> guess num) "high" "low"))

3. FORMAT -- which is *much* more powerful than C's PRINTF! -- has a
   built-in feature to make that slightly shorter still (but note that
   this conditional requires the order "~:[false~;true~]"):

       (format t "Too ~:[low~;high~], try again: " (> guess num))

4. When you get a little further you might want to start exploring
   the majesty & mystery of LOOP as an alternative to DO. I don't
   suggest jumping into it right now, but as a hint of what's to
   come, below is a version using LOOP.

Put that all together (with one or two other tweaks, such as the
addition of an optional upper LIMIT arg), and one gets this version:

   > (defun game (&optional (limit 100))
       (format t "Enter a number between 0 and ~d: " (1- limit))
       (force-output)
       (loop with num = (random limit)
	     for guess = (read)
	     and guesses from 1
	     until (= guess num) 
	 do (format t "Too ~:[low~;high~], try again: " (> guess num))
	    (force-output)
	 finally (format t "Right!~%It took you ~A guesses.~%" guesses))) 

   GAME
   > (game)
   Enter a number between 0 and 99: 50
   Too high, try again: 25
   Too low, try again: 37
   Too low, try again: 42
   Too low, try again: 46
   Too low, try again: 48
   Right!
   It took you 6 guesses.
   NIL
   > (game 250)
   Enter a number between 0 and 249: 125
   Too high, try again: 62
   Too high, try again: 31
   Too high, try again: 15
   Too low, try again: 25
   Too high, try again: 20
   Too low, try again: 22
   Too low, try again: 23
   Right!
   It took you 8 guesses.
   NIL
   > 


-Rob

-----
Rob Warnock			<rpw3@rpw3.org>
627 26th Avenue			<URL:http://rpw3.org/>
San Mateo, CA 94403		(650)572-2607