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

How to generate list indices with format directives

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

(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

你的循环形式:

(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))

简单处理该问题的一种方法是提供一个包含数字的列表:

(defun numbering (list &key (i0 1))
  (loop for i from i0 and element in list
        collect i collect element))

CL-USER > (format t "~{~%~a. ~a~}~%" (numbering hand))

1. (5 . HEARTS)
2. (5 . CLUBS)
3. (10 . DIAMONDS)
4. (JACK . DIAMONDS)
5. (8 . CLUBS)
NIL

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

(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)))

如果您知道手牌永远不会超过 9 张,则可以省略 width 部分。它用于对齐格式化输出中的索引。例如,手很长:

(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):

(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