Subject: Re: Printing introduces newlines
From: rpw3@rpw3.org (Rob Warnock)
Date: Wed, 12 Nov 2008 20:02:25 -0600
Newsgroups: comp.lang.lisp
Message-ID: <256dnaIiJ9ssF4bUnZ2dnUVZ_uydnZ2d@speakeasy.net>
Thomas M. Hermann <tmh.public@gmail.com> wrote:
+---------------
| Francogrex <fra...@grex.org> wrote:
| > (setf z (loop for i from 1 to 100 collect i))
| > (setf test nil)
| > (dotimes (i (length z))
| >   (when (oddp (nth i z)) (setf test (append (list (nth i z)) test))))
...
| I bestow upon you the award for the most redundant steps per line
| of code. First, let's generate your list of odd numbers correctly.
| 
| (loop for number from 1 to 100
|    when (oddp number) collect number)
+---------------

Oh, *puh-LEEZE!*  You can do better than that!  ;-}  ;-}

   (loop for number from 1 to 100 by 2 collect number)

+---------------
| If you actually want the numbers in reverse order,
| reverse the 100 and the 1.
+---------------

And either change FROM to DOWNFROM or TO to DOWNTO
[since CLHS 6.1.2.1.1 doesn't allow negative BY increments].
And since 100 isn't ODDP, you need to start from 99:

   (loop for number from 99 downto 1 by 2 collect number)

or:

   (loop for number downfrom 99 to 1 by 2 collect number)

+---------------
| Now, for output, you need to read the section in your favorite lisp
| reference on FORMAT.
+---------------

Well, not FORMAT per se, but rather *PRINT-PRETTY*. Binding it
to NIL should get rid of the OP's "spurious" newlines, which
can also be done with the :PRETTY keyword arg to WRITE:

    > (setf *print-right-margin* 30) ; Distinguish REPL value from WRITE output

    30
    > (write (loop for number from 1 to 100 by 2 collect number)
	     :pretty nil)
    (1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99)
    (1 3 5 7 9 11 13 15 17 19 21
     23 25 27 29 31 33 35 37 39
     41 43 45 47 49 51 53 55 57
     59 61 63 65 67 69 71 73 75
     77 79 81 83 85 87 89 91 93
     95 97 99)
    > 

Since pretty-printing is typically a serious performance hog anyway
[see many past threads here on that issue], you'll generally want to
disable it if you're doing any sort of massive textual output not
intended for humans to read, such as HTML or JavaScript generation.


-Rob

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