use*_*087 4 lisp formatting common-lisp
有没有办法获得与此相同的输出:(手是卡片列表)
(loop for card in hand
with i = 1
do
(format t "~&~a. ~a~%" i card)
(incf i))
Run Code Online (Sandbox Code Playgroud)
1. (5 . HEARTS)
2. (5 . CLUBS)
3. (10 . DIAMONDS)
4. (JACK . DIAMONDS)
5. (8 . CLUBS)
Run Code Online (Sandbox Code Playgroud)
但只使用一次调用格式化?到目前为止,我有这个,但我不知道如何增加索引。
(format nil "~{~%1. ~a~}~%" hand)
Run Code Online (Sandbox Code Playgroud)
1. (5 . HEARTS)
1. (5 . CLUBS)
1. (10 . DIAMONDS)
1. (JACK . DIAMONDS)
1. (8 . CLUBS)
Run Code Online (Sandbox Code Playgroud)
我还尝试在 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))
Run Code Online (Sandbox Code Playgroud)
1. A
2. C
3. B
4. D
Run Code Online (Sandbox Code Playgroud)
你的循环形式:
(loop for card in hand
with i = 1
do
(format t "~&~a. ~a~%" i card)
(incf i))
Run Code Online (Sandbox Code Playgroud)
人们通常会这样写:
(loop for card in hand and i from 1
do (format t "~&~a. ~a~%" i card))
Run Code Online (Sandbox Code Playgroud)
简单处理问题的一种方法是提供一个带有数字的列表:
(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
Run Code Online (Sandbox Code Playgroud)
对我来说最简单的方法是在这里循环。我要写的函数是:
(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)))
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
另一个带有花哨 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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
65 次 |
最近记录: |