Formatting a list

混江龙づ霸主 提交于 2019-12-11 00:46:39

问题


I have the following list: (X X O NIL NIL O NIL NIL O)

I'd like to format it to look like this:

X | X | O
--+---+--
  |   | O
--+---+--
  |   | O

I could probably cobble something together with what little I know about Lisp and FORMAT, but it would probably be pretty gross. Any pointers would be greatly appreciated.


回答1:


* (format t "~{~A | ~A | ~A~%~^--+---+--~%~}"
    (mapcar (lambda (x) (or x " ")) '(X O X NIL X X O X NIL)))
X | O | X
--+---+--
  | X | X
--+---+--
O | X |
NIL



回答2:


* (format t "~{~A | ~A | ~A~%~^--+---+--~%~}"
    (mapcar (lambda (x) (or x " ")) '(X O X NIL X X O X NIL)))
X | O | X
--+---+--
  | X | X
--+---+--
O | X |
NIL

A little explanation about the format string in the above. Crucial here are the '~{' '~}' and '~^'. A pair of matching Tilde braces take a list as input argument and iterate over it. The ~^ controls an early escape from this loop, if the list being iterated over is empty. Relevant documentation ~{ and ~^.



来源:https://stackoverflow.com/questions/4361045/formatting-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!