在Common Lisp FORMAT中,递归格式如何工作 [英] In Common Lisp FORMAT how does recursive formatting work

查看:110
本文介绍了在Common Lisp FORMAT中,递归格式如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要生成一个带有可变字符串长度的带空格的字符串.不太聪明的解决方案涉及到format:

I need to generate a space-padded string with a variable string length. The not-so-clever solution that works involved nesting of format:

(format nil (format nil "~~~d,,a" 10) "asdf")

现在,我想通过使用format~?进行递归处理使其更加智能.我希望这样的事情可以满足我的要求:

Now, I wanted to make it a bit more clever by using format's ~? for recursive processing. I would expect that something like this should do what I want:

(format nil "~@?" "~~~d,,a" 10 "asdf")

,但是我得到的只是格式字符串,即~10,,a,而不是填充的asdf字符串.也许我在这里误解了递归"一词,但是我希望CL形成了内部格式字符串后,应该继续实际使用它.我想念什么吗?

but what I get is just the formatting string, i.e. ~10,,a, not the padded asdf string. Perhaps I misunderstood the word 'recursive' here, but I would expect that having formed the inner format string, CL should proceed to actually use it. Am I missing something?

推荐答案

格式指令的可变参数

FORMAT允许您将v用作控制字符串中指令的参数,以从参数列表中弹出参数.

FORMAT allows you to use v as an argument to a directive in the control string to pop arguments from the argument list.

CL-USER> (format nil "~va" 10 "asdf")
"asdf      "

可能使用了多个v.

CL-USER> (format nil "~v,,,va" 10 #\- "asdf")
"asdf------"

使用~?

Recursive processing with ~?

递归处理指令旨在将不同的调用"嵌入到控制字符串中的FORMAT.例如,可能会使用提示输入是"或否"答案的功能.

The recursive processing directive is meant for embedding a different "call" to FORMAT inside a control string. For example, a function to prompt for a yes or no answer might be implemented with it.

(defun y-or-n-prompt (control-string &rest args)
  (format t "~&~? [y/n]: " control-string args)
  ;;...
  )

现在,呼叫者可以像使用FORMAT一样使用此格式设置提示,而不必担心该提示对用户的外观细节(在开头或[y/n]:提示处添加新行)最后).

The caller can now format a prompt with this as they would with FORMAT without having to worry about the details of what the prompt should look like to the user (adding a new line at the beginning or the [y/n]: prompt at the end).

CL-USER> (y-or-n-prompt "foo ~d bar" 12)
foo 12 bar [y/n]: 
NIL

~?的结果将不被FORMAT处理,因此不能用于构建控制字符串.通常,在运行时构建控制字符串不是一个好主意,因为它易于出错(例如,您必须转义字符串中所有不需要的波浪号),并阻止实现在编译时处理控制字符串.

The result of ~? will not be processed by FORMAT, so it cannot be used to build a control string. In general, building control strings at run time is a bad idea, because it's error prone (for example, you must escape any unwanted tildes in the string) and prevents the implementation from processing the control string at compile time.

这篇关于在Common Lisp FORMAT中,递归格式如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆