[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.lisp

Re: counting list items in FORMAT statement

William James

2/1/2016 12:42:00 PM

Dr. Edmund Weitz wrote:

> I have a variable *PLACES* that holds a list of lists, like so:
>
> * (defparameter *places* '((1 2 3) nil nil (4 6) (8 5) (0) nil (7)))
> *PLACES*
>
> I want each element of *PLACES* to be printed in reverse and on a line
> of its own while preceded by its position in *PLACES*, i.e. I want
>
> 0: 3 2 1
> 1:
> 2:
> 3: 6 4
> 4: 5 8
> 5: 0
> 6:
> 7: 7
>
> The following statement works fine, and I could just use it and be
> happy with it:
>
> * (dotimes (i (length *places*))
> (format t "~A:~{ ~A~}~%" i (reverse (nth i *places*))))
> 0: 3 2 1
> 1:
> 2:
> 3: 6 4
> 4: 5 8
> 5: 0
> 6:
> 7: 7
> NIL
>
> But... - just out of curiosity - I'm asking myself if it would be
> possible to get rid of the DOTIMES loop and have the positions
> automatically be printed by a FORMAT statement that'll take *PLACES*
> as its only format argument. The solution that I came up with is
>
> * (let ((my-counter 0))
> (defun my-counter-printer (stream format-arg colon-p at-sign-p)
> (declare (ignore format-arg colon-p at-sign-p))
> (princ my-counter stream)
> (incf my-counter)))
> Converted MY-COUNTER-PRINTER.
>
> MY-COUNTER-PRINTER
> * (format t "~{~/my-counter-printer/:~{ ~A~}~%~}"
> (mapcan #'(lambda (place) (list nil (reverse place)))
> *places*))
> 0: 3 2 1
> 1:
> 2:
> 3: 6 4
> 4: 5 8
> 5: 0
> 6:
> 7: 7
> NIL
> *
>
> It kind of works but I admit that
>
> - it is plain ugly,
>
> - it'll only work once or I'll have to provide a facility to reset
> MY-COUNTER,
>
> - it doesn't fullfill my own "specs" 'cause I have to mangle *PLACES*
> before I can hand it over to my FORMAT statement.
>
> Is there a way to really get what I want? Did I miss something while
> reading 22.3 of the CLHS?
>
> Thanks for your time,
> Edi.
>
> PS: Let me re-iterate: This is just out of curiosity. I'm perfectly
> happy with the DOTIMES loop above and I'm quite sure that stuffing all
> the logic into one FORMAT statement wouldn't really increase the
> program's readability.

MatzLisp (Ruby):

[[1,2,3],[],[],[4,6],[8,5],[0],[],[7]].
each_with_index{|xs,i| puts "#{i}: #{xs.reverse.join " "}"}

0: 3 2 1
1:
2:
3: 6 4
4: 5 8
5: 0
6:
7: 7


--
Elie [Wiesel] thus could have remained at Birkenau to await the Russians.
Although his father had permission to stay with him as a hospital patient or
orderly, father and son talked it over and decided to move out with the
Germans. --- Robert Faurisson