如何使用格式指令生成列表索引

问题描述 投票:4回答:2

是否有办法获得与此相同的输出:(手是一张牌列表)

(loop for card in hand
           with i = 1
           do
             (format t "~&~a. ~a~%" i card)
             (incf i))
1. (5 . HEARTS)
2. (5 . CLUBS)
3. (10 . DIAMONDS)
4. (JACK . DIAMONDS)
5. (8 . CLUBS)

但仅使用一个调用进行格式化?到目前为止,我已经有了这个,但是我不知道如何增加索引。

(format nil "~{~%1. ~a~}~%" hand)
1. (5 . HEARTS)
1. (5 . CLUBS)
1. (10 . DIAMONDS)
1. (JACK . DIAMONDS)
1. (8 . CLUBS)

我还尝试过在Call Function指令旁边使用闭包,但是您必须为每次调用重置计数器,这感觉非常不舒服。

(let ((counter 0))
  (defun increment (output-stream format-argument colonp at-sign-p &rest directive-parameters)
    (declare (ignore colonp at-sign-p directive-parameters))
    (incf counter)
    (format output-stream "~a. ~a" counter format-argument))
  (defun reset-counter ()
    (setf counter 0)))

(format t "~&~{~&~/increment/~}" '(a c b d))
1. A
2. C
3. B
4. D
formatting lisp common-lisp
2个回答
5
投票

对我来说,最简单的方法是在此处循环。我要编写的函数是:

(defun format-hand (stream hand)
  (loop
     with width = (ceiling (log (length hand) 10))
     for index from 1
     for (value . color) in hand
     do (format stream "~&~vd. ~@(~a~) of ~(~a~)" width index value color)))

width部分可以省略,如果您知道那只手的牌数不能超过9张。它用于在格式化输出中对齐索引。例如,用非常长的手:

(let ((hand '((5 . hearts) (5 . clubs) (10 . diamonds) 
              (jack . diamonds) (8 . clubs))))
  (format-hand t (concatenate 'list hand hand hand hand)))

 1. 5 of hearts
 2. 5 of clubs
 3. 10 of diamonds
 4. Jack of diamonds
 5. 8 of clubs
 6. 5 of hearts
 7. 5 of clubs
 8. 10 of diamonds
 9. Jack of diamonds
10. 8 of clubs
11. 5 of hearts
12. 5 of clubs
13. 10 of diamonds
14. Jack of diamonds
15. 8 of clubs
16. 5 of hearts
17. 5 of clubs
18. 10 of diamonds
19. Jack of diamonds
20. 8 of clubs

带有花式unicode符号的另一个示例(请参见GETF

GETF

8
投票

您的循环形式:

(defun format-hand (stream hand)
  (loop
     with width = (ceiling (log (length hand) 10))
     for index from 1
     for (value . color) in hand
     for symbol = (getf '(hearts "♥" diamonds "♦" spades "♠" clubs "♣") color)
     do (format stream "~&~vd. ~a ~a" width index symbol value)))

(format-hand t '((5 . hearts) (5 . clubs) (10 . diamonds)
               (jack . diamonds) (8 . clubs)))

1. ♥ 5
2. ♣ 5
3. ♦ 10
4. ♦ JACK
5. ♣ 8

通常将其写为:

(loop for card in hand
           with i = 1
           do
             (format t "~&~a. ~a~%" i card)
             (incf i))

简单处理问题的一种方法是提供带有数字的列表:

(loop for card in hand and i from 1
      do (format t "~&~a. ~a~%" i card))
© www.soinside.com 2019 - 2024. All rights reserved.